@tearleads/client-sdk 0.1.224 → 0.1.226

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 (217) hide show
  1. package/client/organizations/organizationMemberships.d.ts +1 -1
  2. package/client/organizations/organizationMemberships.js +1 -1
  3. package/client/organizations/organizationMemberships.js.map +1 -1
  4. package/client/organizations/principalContainerMutations.js.map +1 -1
  5. package/client/organizations/recipientAdmission.js +1 -1
  6. package/client/organizations/recipientAdmission.js.map +1 -1
  7. package/client/organizations/rosterAdmissionEvidence.js +1 -1
  8. package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
  9. package/data/containers/shared/authorAccess.d.ts +1 -1
  10. package/data/containers/shared/authorAccess.js.map +1 -1
  11. package/data/containers/shared/heldContainerHeads.js.map +1 -1
  12. package/data/containers/shared/principalPolicies.js.map +1 -1
  13. package/data/containers/shared/types.d.ts +1 -1
  14. package/data/containers/shared/types.js.map +1 -1
  15. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -1
  16. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +1 -1
  17. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  18. package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +1 -1
  19. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  20. package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js +1 -1
  21. package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js.map +1 -1
  22. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +1 -1
  23. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -1
  24. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
  25. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  26. package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js +2 -2
  27. package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js.map +1 -1
  28. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.d.ts +1 -1
  29. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
  30. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  31. package/data/keyingProjectionVerification/types.d.ts +1 -1
  32. package/data/keyingProjectionVerification/types.js.map +1 -1
  33. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +1 -1
  34. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
  35. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +1 -1
  36. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  37. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js +1 -1
  38. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -1
  39. package/data/persistence/organizationFounderPersistence.js +1 -1
  40. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  41. package/data/persistence/principalCurrentAcknowledgementPersistence.js +1 -1
  42. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  43. package/data/persistence/principalPolicy/heldPrincipalState.js +1 -1
  44. package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
  45. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +1 -1
  46. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
  47. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
  48. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js +1 -1
  49. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -1
  50. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js +1 -1
  51. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -1
  52. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +1 -1
  53. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
  54. package/data/principals/organizationGroupRoles.js +1 -1
  55. package/data/principals/organizationGroupRoles.js.map +1 -1
  56. package/package.json +1 -1
  57. package/stores/container-contents/operations/forgetOrganizationContentOperation.js +1 -1
  58. package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +1 -1
  59. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js +1 -1
  60. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js.map +1 -1
  61. package/stores/documents/documentStore/initialization/index.js +1 -1
  62. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  63. package/stores/documents/documentStore/storedDocument.js +1 -1
  64. package/stores/documents/documentStore/storedDocument.js.map +1 -1
  65. package/stores/documents/documentStore/sync/syncAttachments.js +1 -1
  66. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  67. package/workflows/container-contents/syncPause/documentRemoval.js +1 -1
  68. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
  69. package/workflows/containers/child/create/index.js.map +1 -1
  70. package/workflows/containers/child/move/moveRequest.js.map +1 -1
  71. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  72. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  73. package/workflows/containers/child/mutationSubmit.d.ts +1 -1
  74. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  75. package/workflows/containers/child/recitePlan.js.map +1 -1
  76. package/workflows/containers/child/rekey/carriedDescendantRekeys.d.ts +1 -1
  77. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
  78. package/workflows/containers/child/rekey/index.d.ts +1 -1
  79. package/workflows/containers/child/rekey/index.js.map +1 -1
  80. package/workflows/containers/child/revoke.d.ts +1 -1
  81. package/workflows/containers/child/revoke.js.map +1 -1
  82. package/workflows/containers/child/rotation/replacementPrincipalPolicyReferences.js.map +1 -1
  83. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
  84. package/workflows/containers/child/rotation/rotationWraps.js.map +1 -1
  85. package/workflows/containers/child/share/sharePlanCore.d.ts +1 -1
  86. package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
  87. package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js +1 -1
  88. package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js.map +1 -1
  89. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  90. package/workflows/containers/rematerialization/principalContainerRematerializationTargets.js.map +1 -1
  91. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  92. package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -1
  93. package/workflows/organizations/currentOrganizationAuthority.js +1 -1
  94. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  95. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js +1 -1
  96. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -1
  97. package/workflows/organizations/groupMetadata/groupMetadataBinding.js.map +1 -1
  98. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
  99. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  100. package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js +2 -2
  101. package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js.map +1 -1
  102. package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
  103. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  104. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  105. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  106. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
  107. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  108. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +1 -1
  109. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  110. package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
  111. package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
  112. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  113. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  114. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
  115. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  116. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
  117. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  118. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  119. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  120. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  121. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  122. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +1 -1
  123. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  124. package/workflows/organizations/memberships/organizationMemberships.d.ts +1 -1
  125. package/workflows/organizations/memberships/organizationMemberships.js +1 -1
  126. package/workflows/organizations/memberships/organizationMemberships.js.map +1 -1
  127. package/workflows/organizations/policyHistory/organizationPolicyHistoryDetails.js.map +1 -1
  128. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js +1 -1
  129. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -1
  130. package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js +1 -1
  131. package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js.map +1 -1
  132. package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js +1 -1
  133. package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js.map +1 -1
  134. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js +1 -1
  135. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
  136. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +1 -1
  137. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
  138. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +1 -1
  139. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  140. package/workflows/organizations/principalPolicy/principalPolicyRecipients.js +1 -1
  141. package/workflows/organizations/principalPolicy/principalPolicyRecipients.js.map +1 -1
  142. package/workflows/organizations/principalPolicy/principalPolicyRequest.js +1 -1
  143. package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +1 -1
  144. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +2 -2
  145. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
  146. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  147. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  148. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +1 -1
  149. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
  150. package/workflows/principals/externalAdminPolicy.d.ts +1 -1
  151. package/workflows/principals/externalAdminPolicy.js +2 -2
  152. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  153. package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js +1 -1
  154. package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js.map +1 -1
  155. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
  156. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  157. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +1 -1
  158. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
  159. package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js +1 -1
  160. package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  161. package/workflows/principals/policyCache/index.js +1 -1
  162. package/workflows/principals/policyCache/index.js.map +1 -1
  163. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
  164. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  165. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
  166. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  167. package/workflows/principals/policyVerification.js +1 -1
  168. package/workflows/principals/policyVerification.js.map +1 -1
  169. package/workflows/principals/principalPolicyService.js +1 -1
  170. package/workflows/principals/principalPolicyService.js.map +1 -1
  171. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js +1 -1
  172. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
  173. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +1 -1
  174. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
  175. package/workflows/principals/publicHistory/publicProjectionDirectory.js +1 -1
  176. package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -1
  177. package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
  178. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
  179. package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js +1 -1
  180. package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js.map +1 -1
  181. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -2
  182. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  183. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
  184. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  185. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.d.ts +1 -1
  186. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
  187. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  188. package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js +1 -1
  189. package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js.map +1 -1
  190. package/workflows/principals/recoveryOperation/principalRecoveryMemo.js +1 -1
  191. package/workflows/principals/recoveryOperation/principalRecoveryMemo.js.map +1 -1
  192. package/workflows/registration/organizationProvisioning.js +2 -2
  193. package/workflows/registration/organizationProvisioning.js.map +1 -1
  194. package/workflows/registration/provisionedPrincipalHistory.js +1 -1
  195. package/workflows/registration/provisionedPrincipalHistory.js.map +1 -1
  196. package/workflows/registration/registrationAccessHeadPersistence.js +1 -1
  197. package/workflows/registration/registrationAccessHeadPersistence.js.map +1 -1
  198. package/workflows/sync/coordination.d.ts +6 -0
  199. package/workflows/sync/coordination.js +6 -0
  200. package/workflows/sync/coordination.js.map +1 -0
  201. package/workflows/sync/index.d.ts +1 -6
  202. package/workflows/sync/index.js +1 -5
  203. package/workflows/sync/index.js.map +1 -1
  204. /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js +0 -0
  205. /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js.map +0 -0
  206. /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.d.ts +0 -0
  207. /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js +0 -0
  208. /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js.map +0 -0
  209. /package/data/{principals → principalContracts}/principalIdentityCommitments.js +0 -0
  210. /package/data/{principals → principalContracts}/principalIdentityCommitments.js.map +0 -0
  211. /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js +0 -0
  212. /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js.map +0 -0
  213. /package/data/{principals → principalContracts}/principalPolicyEvidence.d.ts +0 -0
  214. /package/data/{principals → principalContracts}/principalPolicyEvidence.js +0 -0
  215. /package/data/{principals → principalContracts}/principalPolicyEvidence.js.map +0 -0
  216. /package/data/{principals → principalContracts}/principalPolicyStates.js +0 -0
  217. /package/data/{principals → principalContracts}/principalPolicyStates.js.map +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"leaveRequestMembersEvidence.js","sourceRoot":"","sources":["leaveRequestMembersEvidence.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AACxG,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAElG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAC1F,OAAO,EACL,iCAAiC,GAElC,MAAM,0BAA0B,CAAC;AAQlC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAC1C,KAA2B;IAE3B,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAChE,IAAI,CAAC,oBAAoB;QACvB,MAAM,IAAI,oCAAoC,CAC5C,iDAAiD,CAClD,CAAC;IACJ,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC;QACvD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB;QACpB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,mCAAmC,CAAC,SAAS,CAAC,YAAY,CAAC,CAAC;IAC5D,MAAM,IAAI,GAAG,4BAA4B,CACvC,SAAS,CAAC,UAAU,EACpB,SAAS,CAAC,UAAU,CAAC,aAAa,CACnC,CAAC;IACF,OAAO;QACL,QAAQ,EAAE,IAAI,CAAC,QAAQ;QACvB,cAAc,EAAE,IAAI,CAAC,cAAc;QACnC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,OAAO,EAA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AAE,KAAK,CAAC,YAAY;oBAChC,WAAW,EAAE,aAAa,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE;iBAClE,CAAC,CAAC;gBACH,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;gBAC3D,IAAI,CAAC,QAAQ,CAAC,WAAW;oBACvB,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;gBAC9D,OAAO,QAAQ,CAAC,WAAW,CAAC;YAC9B,CAAC;YACH,CAAC,CAAC,SAAS;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { OrganizationLeaveRequestMembersHead } from \"@tearleads/validators/util\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { loadLocalOrganizationPolicyReference } from \"../readModel/localReadModelDetails\";\nimport {\n createLeaveRequestMembershipCheck,\n type LeaveRequestMembershipCheck,\n} from \"./leaveRequestMembership\";\n\ninterface MembersEvidenceInput {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * The organization's current Members head as the member's own device\n * discovers and verifies it now, for a leave request to cite.\n */\nexport async function loadCurrentMembersHead(\n input: MembersEvidenceInput,\n): Promise<OrganizationLeaveRequestMembersHead> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Asking to leave requires private paged recovery\",\n );\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n const head = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n return {\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n };\n}\n\n/**\n * Checks leave requests against the Members head in the organization policy\n * this device's read model selected, verified exactly through the private\n * paged verifier (from local evidence when it has it), and walks verified\n * Members history the same way when a request cites an earlier key epoch.\n */\nexport function createRuntimeLeaveRequestMembershipCheck(\n input: MembersEvidenceInput & { readonly currentUserId: string },\n): LeaveRequestMembershipCheck {\n const resolve = input.runtime.principalPolicies.createCurrentPolicyResolver();\n return createLeaveRequestMembershipCheck({\n async loadMembersHead() {\n if (!resolve) return null;\n const organizationReference = await loadLocalOrganizationPolicyReference({\n currentUserId: input.currentUserId,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n principalId: input.organizationId,\n principalType: \"organization\",\n });\n if (!organizationReference) return null;\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n organizationReference,\n resolveCurrentPolicy: resolve,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n return requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n },\n loadHistoryPage: resolve\n ? async (head, beforeVersion) => {\n const resolved = await resolve({\n organizationId: input.organizationId,\n reference: head,\n preferLocalCurrent: true,\n stillCurrent: input.stillCurrent,\n historyPage: beforeVersion === undefined ? {} : { beforeVersion },\n });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n if (!resolved.historyPage)\n throw new Error(\"Verified Members history page is missing\");\n return resolved.historyPage;\n }\n : undefined,\n });\n}\n"]}
1
+ {"version":3,"file":"leaveRequestMembersEvidence.js","sourceRoot":"","sources":["leaveRequestMembersEvidence.ts"],"names":[],"mappings":"AACA,OAAO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,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;gBAC3D,IAAI,CAAC,QAAQ,CAAC,WAAW;oBACvB,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;gBAC9D,OAAO,QAAQ,CAAC,WAAW,CAAC;YAC9B,CAAC;YACH,CAAC,CAAC,SAAS;KACd,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { OrganizationLeaveRequestMembersHead } from \"@tearleads/validators/util\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { requireOrganizationGroupHead } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { loadLocalOrganizationPolicyReference } from \"../readModel/localReadModelDetails\";\nimport {\n createLeaveRequestMembershipCheck,\n type LeaveRequestMembershipCheck,\n} from \"./leaveRequestMembership\";\n\ninterface MembersEvidenceInput {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * The organization's current Members head as the member's own device\n * discovers and verifies it now, for a leave request to cite.\n */\nexport async function loadCurrentMembersHead(\n input: MembersEvidenceInput,\n): Promise<OrganizationLeaveRequestMembersHead> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Asking to leave requires private paged recovery\",\n );\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n const head = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n return {\n keyEpoch: head.keyEpoch,\n keyFingerprint: head.keyFingerprint,\n principalId: head.principalId,\n stateHash: head.stateHash,\n version: head.version,\n };\n}\n\n/**\n * Checks leave requests against the Members head in the organization policy\n * this device's read model selected, verified exactly through the private\n * paged verifier (from local evidence when it has it), and walks verified\n * Members history the same way when a request cites an earlier key epoch.\n */\nexport function createRuntimeLeaveRequestMembershipCheck(\n input: MembersEvidenceInput & { readonly currentUserId: string },\n): LeaveRequestMembershipCheck {\n const resolve = input.runtime.principalPolicies.createCurrentPolicyResolver();\n return createLeaveRequestMembershipCheck({\n async loadMembersHead() {\n if (!resolve) return null;\n const organizationReference = await loadLocalOrganizationPolicyReference({\n currentUserId: input.currentUserId,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n principalId: input.organizationId,\n principalType: \"organization\",\n });\n if (!organizationReference) return null;\n const authority = await loadCurrentOrganizationAuthority({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n organizationReference,\n resolveCurrentPolicy: resolve,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(authority.stillCurrent);\n return requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.memberGroupId,\n );\n },\n loadHistoryPage: resolve\n ? async (head, beforeVersion) => {\n const resolved = await resolve({\n organizationId: input.organizationId,\n reference: head,\n preferLocalCurrent: true,\n stillCurrent: input.stillCurrent,\n historyPage: beforeVersion === undefined ? {} : { beforeVersion },\n });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n if (!resolved.historyPage)\n throw new Error(\"Verified Members history page is missing\");\n return resolved.historyPage;\n }\n : undefined,\n });\n}\n"]}
@@ -3,7 +3,7 @@ import type { UpdateOrganizationMembershipRequest } from "../../../internal/vali
3
3
  import type { OrganizationMembershipResponse, OrganizationMembershipsResponse } from "../../../internal/validators/response/index.js";
4
4
  import type { DomainScope } from "../../../data/shared/domainScope.js";
5
5
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
6
- import { type OrganizationSyncPauses } from "../../sync/index.js";
6
+ import { type OrganizationSyncPauses } from "../../sync/coordination.js";
7
7
  /** One organization the user belongs to, with their own choices for it. */
8
8
  export type OrganizationMembership = OrganizationMembershipResponse;
9
9
  export interface OrganizationMembershipApi {
@@ -1,4 +1,4 @@
1
- import { getOrCreateOrganizationSyncPauses, } from "../../sync/index.js";
1
+ import { getOrCreateOrganizationSyncPauses, } from "../../sync/coordination.js";
2
2
  async function forgetEveryPausedOrganization(input) {
3
3
  let complete = true;
4
4
  for (const organizationId of [...input.pauses.pausedOrganizationIds()]) {
@@ -1 +1 @@
1
- {"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,iCAAiC,GAElC,MAAM,YAAY,CAAC;AA2DpB,KAAK,UAAU,6BAA6B,CAAC,KAG5C;IACC,IAAI,QAAQ,GAAG,IAAI,CAAC;IACpB,KAAK,MAAM,cAAc,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,qBAAqB,EAAE,CAAC,EAAE,CAAC;QACvE,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,yBAAyB,CAAC,cAAc,CAAC,CAAC,EAAE,CAAC;YAClE,QAAQ,GAAG,KAAK,CAAC;QACnB,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAGrD;IACC,IAAI,MAAM,6BAA6B,CAAC,KAAK,CAAC;QAAE,OAAO;IACvD,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,GAAG,EAAE,CACpC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC,6BAA6B,CAAC,KAAK,CAAC,CAAC,CACtE,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,KAAkC;IAElC,MAAM,MAAM,GAAG,iCAAiC,CAAC,KAAK,CA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AAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC1C,IAAI,MAAM;QAAE,MAAM,+BAA+B,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,CAAC;;QAC/D,MAAM,IAAI,CAAC,cAAc,EAAE,CAAC;IACjC,OAAO,EAAE,UAAU,EAAE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,SAAS,EAAE,CAAC;AACxD,CAAC","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { UpdateOrganizationMembershipRequest } from \"@tearleads/validators/request\";\nimport type {\n OrganizationMembershipResponse,\n OrganizationMembershipsResponse,\n} from \"@tearleads/validators/response\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n getOrCreateOrganizationSyncPauses,\n type OrganizationSyncPauses,\n} from \"../../sync\";\n\n/** One organization the user belongs to, with their own choices for it. */\nexport type OrganizationMembership = OrganizationMembershipResponse;\n\nexport interface OrganizationMembershipApi {\n listOrganizationMemberships(): Promise<OrganizationMembershipsResponse | null>;\n updateOrganizationMembership(\n organizationId: string,\n input: UpdateOrganizationMembershipRequest,\n ): Promise<RequestResult<OrganizationMembershipResponse>>;\n}\n\n/**\n * What applying a pause needs from the device's content. Wired by the\n * composition root to the container tree and the document sync lanes.\n */\nexport interface OrganizationContentHost {\n /**\n * Removes an organization's content, keeping its metadata root. Refuses,\n * returning false, while any of its writes is unsynced or still queued in\n * an open store.\n */\n forgetOrganizationContent(organizationId: string): Promise<boolean>;\n /** Whether any local write for the organization has not uploaded yet. */\n hasUnsyncedOrganizationWrites(organizationId: string): Promise<boolean>;\n /** Asks every sync lane to upload now and waits briefly for them to idle. */\n flushWrites(): Promise<void>;\n /** Re-lists the whole tree so resumed organizations download again. */\n refetchContent(): Promise<void>;\n /**\n * Runs `retry` each time the scope's sync lanes go idle until it resolves\n * true. A later call replaces the pending retry.\n */\n retryWhenWritesSettle(retry: () => Promise<boolean>): void;\n}\n\ninterface OrganizationMembershipInput {\n readonly apiClient: OrganizationMembershipApi;\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly host: OrganizationContentHost;\n /**\n * Whether the session still uses `domainScope`. A membership list or pause\n * that completes after an identity switch must not touch the new identity's\n * device state.\n */\n readonly isCurrent: () => boolean;\n}\n\nexport type OrganizationSyncPauseResult =\n | { readonly status: \"updated\"; readonly membership: OrganizationMembership }\n | { readonly status: \"unsynced-writes\" }\n | {\n readonly status: \"failed\";\n readonly httpStatus: number | null;\n readonly message: string;\n };\n\nasync function forgetEveryPausedOrganization(input: {\n readonly host: OrganizationContentHost;\n readonly pauses: OrganizationSyncPauses;\n}): Promise<boolean> {\n let complete = true;\n for (const organizationId of [...input.pauses.pausedOrganizationIds()]) {\n if (!(await input.host.forgetOrganizationContent(organizationId))) {\n complete = false;\n }\n }\n return complete;\n}\n\n/**\n * Removes the content of every paused organization that has nothing left to\n * upload. An organization with pending or queued writes keeps syncing those\n * out and is retried once the sync lanes go idle, so pausing never discards\n * unsynced work and a removal does not wait for the next membership read.\n */\nexport async function forgetPausedOrganizationContent(input: {\n readonly host: OrganizationContentHost;\n readonly pauses: OrganizationSyncPauses;\n}): Promise<void> {\n if (await forgetEveryPausedOrganization(input)) return;\n input.host.retryWhenWritesSettle(() =>\n input.pauses.runExclusive(() => forgetEveryPausedOrganization(input)),\n );\n}\n\n/**\n * Reads the user's memberships and applies their pause choices, including\n * ones made on another device: paused organizations leave this device, and\n * resumed ones download again. Returns null when the list is unavailable, in\n * which case the persisted pauses stay in force.\n */\nexport async function refreshOrganizationMemberships(\n input: OrganizationMembershipInput,\n): Promise<OrganizationMembership[] | null> {\n const pauses = getOrCreateOrganizationSyncPauses(input.domainScope);\n return pauses.runExclusive(() => applyMembershipList(input, pauses));\n}\n\nasync function applyMembershipList(\n input: OrganizationMembershipInput,\n pauses: OrganizationSyncPauses,\n): Promise<OrganizationMembership[] | null> {\n const response = await input.apiClient.listOrganizationMemberships();\n if (!response || !input.isCurrent()) return null;\n const change = await pauses.replace(\n input.execSql,\n response.memberships.flatMap((membership) =>\n membership.syncPaused ? [membership.organizationId] : [],\n ),\n );\n await forgetPausedOrganizationContent({ host: input.host, pauses });\n if (change.resumed.length > 0) await input.host.refetchContent();\n return [...response.memberships];\n}\n\n/**\n * Pauses or resumes one organization for every device of this user. Pausing\n * first uploads this device's pending writes and is refused while any remain,\n * so the local copy it removes holds nothing the server lacks.\n */\nexport async function setOrganizationSyncPaused(\n input: OrganizationMembershipInput & {\n readonly organizationId: string;\n readonly paused: boolean;\n },\n): Promise<OrganizationSyncPauseResult> {\n const pauses = getOrCreateOrganizationSyncPauses(input.domainScope);\n return pauses.runExclusive(() => applySyncPauseChoice(input, pauses));\n}\n\nasync function applySyncPauseChoice(\n input: OrganizationMembershipInput & {\n readonly organizationId: string;\n readonly paused: boolean;\n },\n pauses: OrganizationSyncPauses,\n): Promise<OrganizationSyncPauseResult> {\n const { host, organizationId, paused } = input;\n const scopeEnded = {\n httpStatus: null,\n message: \"The session changed before sync could be changed.\",\n status: \"failed\",\n } as const;\n // Queued behind other membership work, the session may have switched\n // identity; the shared API client would then act for the new identity.\n if (!input.isCurrent()) return scopeEnded;\n if (paused) {\n await host.flushWrites();\n if (await host.hasUnsyncedOrganizationWrites(organizationId)) {\n return { status: \"unsynced-writes\" };\n }\n }\n if (!input.isCurrent()) return scopeEnded;\n const result = await input.apiClient.updateOrganizationMembership(\n organizationId,\n { syncPaused: paused },\n );\n if (!result.ok) {\n return {\n httpStatus: result.status,\n message: result.message,\n status: \"failed\",\n };\n }\n // The choice is recorded; a scope that ended meanwhile applies it on its\n // next membership read instead.\n if (!input.isCurrent()) return { membership: result.data, status: \"updated\" };\n await pauses.load(input.execSql);\n const next = new Set(pauses.pausedOrganizationIds());\n if (paused) next.add(organizationId);\n else next.delete(organizationId);\n await pauses.replace(input.execSql, next);\n if (paused) await forgetPausedOrganizationContent({ host, pauses });\n else await host.refetchContent();\n return { membership: result.data, status: \"updated\" };\n}\n"]}
1
+ {"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAQA,OAAO,EACL,iCAAiC,GAElC,MAAM,yBAAyB,CAAC;AA2DjC,KAAK,UAAU,6BAA6B,CAAC,KAG5C;IACC,IAAI,QAAQ,GAAG,IAAI,CAAC;IACpB,KAAK,MAAM,cAAc,IAAI,CAAC,GAAG,KAAK,CAAC,MAAM,CAAC,qBAAqB,EAAE,CAAC,EAAE,CAAC;QACvE,IAAI,CAAC,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,yBAAyB,CAAC,cAAc,CAAC,CAAC,EAAE,CAAC;YAClE,QAAQ,GAAG,KAAK,CAAC;QACnB,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAGrD;IACC,IAAI,MAAM,6BAA6B,CAAC,KAAK,CAAC;QAAE,OAAO;IACvD,KAAK,CAAC,IAAI,CAAC,qBAAqB,CAAC,GAAG,EAAE,CACpC,KAAK,CAAC,MAAM,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC,6BAA6B,CAAC,KAAK,CAAC,CAAC,CACtE,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,KAAkC;IAElC,MAAM,MAAM,GAAG,iCAAiC,CAAC,KAAK,CAAC,WAAW,CAAC,CAAC;IACpE,OAAO,MAAM,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC,mBAAmB,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AACvE,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,KAAkC,EAClC,MAA8B;IAE9B,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,SAAS,CAAC,2BAA2B,EAAE,CAAC;IACrE,IAAI,CA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AACxD,CAAC","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { UpdateOrganizationMembershipRequest } from \"@tearleads/validators/request\";\nimport type {\n OrganizationMembershipResponse,\n OrganizationMembershipsResponse,\n} from \"@tearleads/validators/response\";\nimport type { DomainScope } from \"../../../data/shared/domainScope\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n getOrCreateOrganizationSyncPauses,\n type OrganizationSyncPauses,\n} from \"../../sync/coordination\";\n\n/** One organization the user belongs to, with their own choices for it. */\nexport type OrganizationMembership = OrganizationMembershipResponse;\n\nexport interface OrganizationMembershipApi {\n listOrganizationMemberships(): Promise<OrganizationMembershipsResponse | null>;\n updateOrganizationMembership(\n organizationId: string,\n input: UpdateOrganizationMembershipRequest,\n ): Promise<RequestResult<OrganizationMembershipResponse>>;\n}\n\n/**\n * What applying a pause needs from the device's content. Wired by the\n * composition root to the container tree and the document sync lanes.\n */\nexport interface OrganizationContentHost {\n /**\n * Removes an organization's content, keeping its metadata root. Refuses,\n * returning false, while any of its writes is unsynced or still queued in\n * an open store.\n */\n forgetOrganizationContent(organizationId: string): Promise<boolean>;\n /** Whether any local write for the organization has not uploaded yet. */\n hasUnsyncedOrganizationWrites(organizationId: string): Promise<boolean>;\n /** Asks every sync lane to upload now and waits briefly for them to idle. */\n flushWrites(): Promise<void>;\n /** Re-lists the whole tree so resumed organizations download again. */\n refetchContent(): Promise<void>;\n /**\n * Runs `retry` each time the scope's sync lanes go idle until it resolves\n * true. A later call replaces the pending retry.\n */\n retryWhenWritesSettle(retry: () => Promise<boolean>): void;\n}\n\ninterface OrganizationMembershipInput {\n readonly apiClient: OrganizationMembershipApi;\n readonly domainScope: DomainScope;\n readonly execSql: ExecSql;\n readonly host: OrganizationContentHost;\n /**\n * Whether the session still uses `domainScope`. A membership list or pause\n * that completes after an identity switch must not touch the new identity's\n * device state.\n */\n readonly isCurrent: () => boolean;\n}\n\nexport type OrganizationSyncPauseResult =\n | { readonly status: \"updated\"; readonly membership: OrganizationMembership }\n | { readonly status: \"unsynced-writes\" }\n | {\n readonly status: \"failed\";\n readonly httpStatus: number | null;\n readonly message: string;\n };\n\nasync function forgetEveryPausedOrganization(input: {\n readonly host: OrganizationContentHost;\n readonly pauses: OrganizationSyncPauses;\n}): Promise<boolean> {\n let complete = true;\n for (const organizationId of [...input.pauses.pausedOrganizationIds()]) {\n if (!(await input.host.forgetOrganizationContent(organizationId))) {\n complete = false;\n }\n }\n return complete;\n}\n\n/**\n * Removes the content of every paused organization that has nothing left to\n * upload. An organization with pending or queued writes keeps syncing those\n * out and is retried once the sync lanes go idle, so pausing never discards\n * unsynced work and a removal does not wait for the next membership read.\n */\nexport async function forgetPausedOrganizationContent(input: {\n readonly host: OrganizationContentHost;\n readonly pauses: OrganizationSyncPauses;\n}): Promise<void> {\n if (await forgetEveryPausedOrganization(input)) return;\n input.host.retryWhenWritesSettle(() =>\n input.pauses.runExclusive(() => forgetEveryPausedOrganization(input)),\n );\n}\n\n/**\n * Reads the user's memberships and applies their pause choices, including\n * ones made on another device: paused organizations leave this device, and\n * resumed ones download again. Returns null when the list is unavailable, in\n * which case the persisted pauses stay in force.\n */\nexport async function refreshOrganizationMemberships(\n input: OrganizationMembershipInput,\n): Promise<OrganizationMembership[] | null> {\n const pauses = getOrCreateOrganizationSyncPauses(input.domainScope);\n return pauses.runExclusive(() => applyMembershipList(input, pauses));\n}\n\nasync function applyMembershipList(\n input: OrganizationMembershipInput,\n pauses: OrganizationSyncPauses,\n): Promise<OrganizationMembership[] | null> {\n const response = await input.apiClient.listOrganizationMemberships();\n if (!response || !input.isCurrent()) return null;\n const change = await pauses.replace(\n input.execSql,\n response.memberships.flatMap((membership) =>\n membership.syncPaused ? [membership.organizationId] : [],\n ),\n );\n await forgetPausedOrganizationContent({ host: input.host, pauses });\n if (change.resumed.length > 0) await input.host.refetchContent();\n return [...response.memberships];\n}\n\n/**\n * Pauses or resumes one organization for every device of this user. Pausing\n * first uploads this device's pending writes and is refused while any remain,\n * so the local copy it removes holds nothing the server lacks.\n */\nexport async function setOrganizationSyncPaused(\n input: OrganizationMembershipInput & {\n readonly organizationId: string;\n readonly paused: boolean;\n },\n): Promise<OrganizationSyncPauseResult> {\n const pauses = getOrCreateOrganizationSyncPauses(input.domainScope);\n return pauses.runExclusive(() => applySyncPauseChoice(input, pauses));\n}\n\nasync function applySyncPauseChoice(\n input: OrganizationMembershipInput & {\n readonly organizationId: string;\n readonly paused: boolean;\n },\n pauses: OrganizationSyncPauses,\n): Promise<OrganizationSyncPauseResult> {\n const { host, organizationId, paused } = input;\n const scopeEnded = {\n httpStatus: null,\n message: \"The session changed before sync could be changed.\",\n status: \"failed\",\n } as const;\n // Queued behind other membership work, the session may have switched\n // identity; the shared API client would then act for the new identity.\n if (!input.isCurrent()) return scopeEnded;\n if (paused) {\n await host.flushWrites();\n if (await host.hasUnsyncedOrganizationWrites(organizationId)) {\n return { status: \"unsynced-writes\" };\n }\n }\n if (!input.isCurrent()) return scopeEnded;\n const result = await input.apiClient.updateOrganizationMembership(\n organizationId,\n { syncPaused: paused },\n );\n if (!result.ok) {\n return {\n httpStatus: result.status,\n message: result.message,\n status: \"failed\",\n };\n }\n // The choice is recorded; a scope that ended meanwhile applies it on its\n // next membership read instead.\n if (!input.isCurrent()) return { membership: result.data, status: \"updated\" };\n await pauses.load(input.execSql);\n const next = new Set(pauses.pausedOrganizationIds());\n if (paused) next.add(organizationId);\n else next.delete(organizationId);\n await pauses.replace(input.execSql, next);\n if (paused) await forgetPausedOrganizationContent({ host, pauses });\n else await host.refetchContent();\n return { membership: result.data, status: \"updated\" };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"organizationPolicyHistoryDetails.js","sourceRoot":"","sources":["organizationPolicyHistoryDetails.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,mCAAmC,GAEpC,MAAM,kDAAkD,CAAC;AAE1D,OAAO,E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AAE,UAAU,CAAC;QAC3D,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC1E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,UAAU,CAAC,aAAa,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC;QAC3E,aAAa,GAAG,KAAK,CAAC;IACxB,CAAC;IACD,OAAO;QACL,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACnC,aAAa,EAAE,cAAc;QAC7B,cAAc,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACtC,iBAAiB,EAAE,KAAK,CAAC,IAAI,CAAC,iBAAiB;QAC/C,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACrC,GAAG,KAAK;YACR,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE;SACjD,CAAC,CAAC;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import {\n type PrincipalContainerGrant,\n type PrincipalPolicyStateChainEntry,\n principalPolicyMatchesReference,\n} from \"@tearleads/crypto\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification/types\";\nimport type { OrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { buildOrganizationGroupPolicyHistoryPage } from \"./groupPolicyHistoryPage\";\nimport { verifyOrganizationPolicyHistory } from \"./organizationPolicyHistoryVerification\";\nimport {\n diffPrincipalProjectionMembers,\n type OrganizationPolicyHistory,\n} from \"./policyHistoryReadModel\";\nimport type {\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n} from \"./policyHistoryTypes\";\n\nfunction diffGrants(\n previous: readonly PrincipalContainerGrant[],\n current: readonly PrincipalContainerGrant[],\n): OrganizationPolicyGrantChange[] {\n const before = new Map(\n previous.map((grant) => [grant.containerId, grant.accessLevel]),\n );\n const after = new Map(\n current.map((grant) => [grant.containerId, grant.accessLevel]),\n );\n return [...new Set([...before.keys(), ...after.keys()])]\n .sort()\n .flatMap((containerId) => {\n const previousAccess = before.get(containerId) ?? null;\n const nextAccess = after.get(containerId) ?? null;\n return previousAccess === nextAccess\n ? []\n : [{ containerId, previousAccess, nextAccess }];\n });\n}\n\nfunction describeGroupChange(\n previous: OrganizationGroupHead | undefined,\n current: OrganizationGroupHead | undefined,\n groupState: (head: OrganizationGroupHead) => PrincipalPolicyStateChainEntry,\n): OrganizationPolicyGroupChange {\n const head = current ?? previous;\n if (!head) throw new Error(\"Group change has no state\");\n const oldEntry = previous ? groupState(previous) : null;\n const newEntry = current ? groupState(current) : null;\n return {\n groupId: head.principalId,\n changeType: !previous ? \"created\" : !current ? \"deleted\" : \"updated\",\n previousVersion: previous?.version ?? null,\n version: head.version,\n previousKeyEpoch: previous?.keyEpoch ?? null,\n keyEpoch: head.keyEpoch,\n changes: newEntry\n ? diffPrincipalProjectionMembers({\n previous: oldEntry?.projection ?? [],\n current: newEntry.projection,\n })\n : [],\n grantChanges: newEntry\n ? diffGrants(oldEntry?.grants ?? [], newEntry.grants)\n : [],\n };\n}\n\nfunction diffGroups(\n previousHeads: readonly OrganizationGroupHead[],\n heads: readonly OrganizationGroupHead[],\n groupState: (head: OrganizationGroupHead) => PrincipalPolicyStateChainEntry,\n): OrganizationPolicyGroupChange[] {\n const before = new Map(previousHeads.map((head) => [head.principalId, head]));\n const after = new Map(heads.map((head) => [head.principalId, head]));\n const changes: OrganizationPolicyGroupChange[] = [];\n for (const groupId of [\n ...new Set([...before.keys(), ...after.keys()]),\n ].sort()) {\n const previous = before.get(groupId);\n const current = after.get(groupId);\n if (previous?.stateHash === current?.stateHash) continue;\n changes.push(describeGroupChange(previous, current, groupState));\n }\n return changes;\n}\n\n/** Display only: historical group selections never advance current checkpoints. */\nexport async function buildDetailedOrganizationPolicyHistory(\n input: Parameters<typeof verifyOrganizationPolicyHistory>[0] & {\n readonly resolveHistory: NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"]\n >;\n readonly stillCurrent: () => boolean;\n },\n): Promise<OrganizationPolicyHistory> {\n input = {\n ...input,\n head: structuredClone(input.head),\n page: structuredClone(input.page),\n evidence: structuredClone(input.evidence),\n };\n const { descriptors, references } =\n await verifyOrganizationPolicyHistory(input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await input.resolveHistory({\n organizationId: input.head.principalId,\n evidence: input.evidence.evidence,\n references,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(\n () => input.stillCurrent() && resolved.stillCurrent(),\n );\n const groupState = (\n head: OrganizationGroupHead,\n ): PrincipalPolicyStateChainEntry => {\n const policy = resolved.policies.find((policy) =>\n principalPolicyMatchesReference({ policy, reference: head }),\n );\n const entry = policy?.retainedHistory.find(\n (entry) => entry.state.stateHash === head.stateHash,\n );\n if (!entry) throw new Error(\"Verified group history state is missing\");\n return entry;\n };\n const basic = buildOrganizationGroupPolicyHistoryPage({\n page: input.page,\n groupId: input.head.principalId,\n organizationId: input.head.principalId,\n });\n const byState = new Map<string, OrganizationPolicyGroupChange[]>();\n let previousHeads: readonly OrganizationGroupHead[] = input.page.predecessor\n ? (descriptors.get(input.page.predecessor.state.stateHash)?.groupHeads ??\n [])\n : [];\n for (const { state } of input.page.entries) {\n const heads = descriptors.get(state.stateHash)?.groupHeads;\n if (!heads) throw new Error(\"Verified organization directory is missing\");\n byState.set(state.stateHash, diffGroups(previousHeads, heads, groupState));\n previousHeads = heads;\n }\n return {\n principalId: input.head.principalId,\n principalType: \"organization\",\n organizationId: input.head.principalId,\n nextBeforeVersion: input.page.nextBeforeVersion,\n entries: basic.entries.map((entry) => ({\n ...entry,\n groupChanges: byState.get(entry.stateHash) ?? [],\n })),\n };\n}\n"]}
1
+ {"version":3,"file":"organizationPolicyHistoryDetails.js","sourceRoot":"","sources":["organizationPol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AAK,MAAM,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;QAC3C,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,EAAE,UAAU,CAAC;QAC3D,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,4CAA4C,CAAC,CAAC;QAC1E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,EAAE,UAAU,CAAC,aAAa,EAAE,KAAK,EAAE,UAAU,CAAC,CAAC,CAAC;QAC3E,aAAa,GAAG,KAAK,CAAC;IACxB,CAAC;IACD,OAAO;QACL,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACnC,aAAa,EAAE,cAAc;QAC7B,cAAc,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACtC,iBAAiB,EAAE,KAAK,CAAC,IAAI,CAAC,iBAAiB;QAC/C,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YACrC,GAAG,KAAK;YACR,YAAY,EAAE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,EAAE;SACjD,CAAC,CAAC;KACJ,CAAC;AACJ,CAAC","sourcesContent":["import {\n type PrincipalContainerGrant,\n type PrincipalPolicyStateChainEntry,\n principalPolicyMatchesReference,\n} from \"@tearleads/crypto\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../../data/keyingProjectionVerification/types\";\nimport type { OrganizationGroupHead } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { buildOrganizationGroupPolicyHistoryPage } from \"./groupPolicyHistoryPage\";\nimport { verifyOrganizationPolicyHistory } from \"./organizationPolicyHistoryVerification\";\nimport {\n diffPrincipalProjectionMembers,\n type OrganizationPolicyHistory,\n} from \"./policyHistoryReadModel\";\nimport type {\n OrganizationPolicyGrantChange,\n OrganizationPolicyGroupChange,\n} from \"./policyHistoryTypes\";\n\nfunction diffGrants(\n previous: readonly PrincipalContainerGrant[],\n current: readonly PrincipalContainerGrant[],\n): OrganizationPolicyGrantChange[] {\n const before = new Map(\n previous.map((grant) => [grant.containerId, grant.accessLevel]),\n );\n const after = new Map(\n current.map((grant) => [grant.containerId, grant.accessLevel]),\n );\n return [...new Set([...before.keys(), ...after.keys()])]\n .sort()\n .flatMap((containerId) => {\n const previousAccess = before.get(containerId) ?? null;\n const nextAccess = after.get(containerId) ?? null;\n return previousAccess === nextAccess\n ? []\n : [{ containerId, previousAccess, nextAccess }];\n });\n}\n\nfunction describeGroupChange(\n previous: OrganizationGroupHead | undefined,\n current: OrganizationGroupHead | undefined,\n groupState: (head: OrganizationGroupHead) => PrincipalPolicyStateChainEntry,\n): OrganizationPolicyGroupChange {\n const head = current ?? previous;\n if (!head) throw new Error(\"Group change has no state\");\n const oldEntry = previous ? groupState(previous) : null;\n const newEntry = current ? groupState(current) : null;\n return {\n groupId: head.principalId,\n changeType: !previous ? \"created\" : !current ? \"deleted\" : \"updated\",\n previousVersion: previous?.version ?? null,\n version: head.version,\n previousKeyEpoch: previous?.keyEpoch ?? null,\n keyEpoch: head.keyEpoch,\n changes: newEntry\n ? diffPrincipalProjectionMembers({\n previous: oldEntry?.projection ?? [],\n current: newEntry.projection,\n })\n : [],\n grantChanges: newEntry\n ? diffGrants(oldEntry?.grants ?? [], newEntry.grants)\n : [],\n };\n}\n\nfunction diffGroups(\n previousHeads: readonly OrganizationGroupHead[],\n heads: readonly OrganizationGroupHead[],\n groupState: (head: OrganizationGroupHead) => PrincipalPolicyStateChainEntry,\n): OrganizationPolicyGroupChange[] {\n const before = new Map(previousHeads.map((head) => [head.principalId, head]));\n const after = new Map(heads.map((head) => [head.principalId, head]));\n const changes: OrganizationPolicyGroupChange[] = [];\n for (const groupId of [\n ...new Set([...before.keys(), ...after.keys()]),\n ].sort()) {\n const previous = before.get(groupId);\n const current = after.get(groupId);\n if (previous?.stateHash === current?.stateHash) continue;\n changes.push(describeGroupChange(previous, current, groupState));\n }\n return changes;\n}\n\n/** Display only: historical group selections never advance current checkpoints. */\nexport async function buildDetailedOrganizationPolicyHistory(\n input: Parameters<typeof verifyOrganizationPolicyHistory>[0] & {\n readonly resolveHistory: NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"]\n >;\n readonly stillCurrent: () => boolean;\n },\n): Promise<OrganizationPolicyHistory> {\n input = {\n ...input,\n head: structuredClone(input.head),\n page: structuredClone(input.page),\n evidence: structuredClone(input.evidence),\n };\n const { descriptors, references } =\n await verifyOrganizationPolicyHistory(input);\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await input.resolveHistory({\n organizationId: input.head.principalId,\n evidence: input.evidence.evidence,\n references,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(\n () => input.stillCurrent() && resolved.stillCurrent(),\n );\n const groupState = (\n head: OrganizationGroupHead,\n ): PrincipalPolicyStateChainEntry => {\n const policy = resolved.policies.find((policy) =>\n principalPolicyMatchesReference({ policy, reference: head }),\n );\n const entry = policy?.retainedHistory.find(\n (entry) => entry.state.stateHash === head.stateHash,\n );\n if (!entry) throw new Error(\"Verified group history state is missing\");\n return entry;\n };\n const basic = buildOrganizationGroupPolicyHistoryPage({\n page: input.page,\n groupId: input.head.principalId,\n organizationId: input.head.principalId,\n });\n const byState = new Map<string, OrganizationPolicyGroupChange[]>();\n let previousHeads: readonly OrganizationGroupHead[] = input.page.predecessor\n ? (descriptors.get(input.page.predecessor.state.stateHash)?.groupHeads ??\n [])\n : [];\n for (const { state } of input.page.entries) {\n const heads = descriptors.get(state.stateHash)?.groupHeads;\n if (!heads) throw new Error(\"Verified organization directory is missing\");\n byState.set(state.stateHash, diffGroups(previousHeads, heads, groupState));\n previousHeads = heads;\n }\n return {\n principalId: input.head.principalId,\n principalType: \"organization\",\n organizationId: input.head.principalId,\n nextBeforeVersion: input.page.nextBeforeVersion,\n entries: basic.entries.map((entry) => ({\n ...entry,\n groupChanges: byState.get(entry.stateHash) ?? [],\n })),\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { computePrincipalStatePayloadCiphertextHash, KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
- import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
2
+ import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
3
3
  function reject(message) {
4
4
  throw new KeyingVerificationError("hash_mismatch", `Organization policy history: ${message}`);
5
5
  }
@@ -1 +1 @@
1
- {"version":3,"file":"organizationPolicyHistoryVerification.js","sourceRoot":"","sources":["organizationPolicyHistoryVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0CAA0C,EAC1C,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,0DAA0D,CAAC;AAGlE,SAAS,MAAM,CAAC,OAAe;IAC7B,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,gCAAgC,OAAO,EAAE,CAC1C,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAIrD;IACC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IACvC,MAAM,aAAa,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,OAAO,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;IACpE,IACE,IAAI,CAAC,aAAa,KAAK,cAAc;QACrC,QAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,WAAW;QAC5C,QAAQ,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS;QACrC,QAAQ,CAAC,aAAa,KAAK,aAAa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,EAAU,CAAC;IAC/B,KAAK,MAAM,MAAM,IAAI,QAAQ,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QAC9C,MAAM,QAAQ,GAAG,MAAM,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACrD,IACE,CAAC,QAAQ;YACT,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC;YACjC,CAAC,6BAA6B,CAAC,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC;YAErD,MAAM,CAAC,yDAAyD,CAAC,CAAC;QACpE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { OrganizationPolicyHistoryResponse } from \"@tearleads/validators/response\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { RecoveredPrincipalHistoryPage } from \"../../principals/historyRecovery/loadRecoveredPrincipalHistoryPage\";\n\nfunction reject(message: string): never {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `Organization policy history: ${message}`,\n );\n}\n\n/** Bind every display payload and public source to the privately verified page. */\nexport async function verifyOrganizationPolicyHistory(input: {\n readonly head: ReferencedPrincipalHead;\n readonly page: RecoveredPrincipalHistoryPage;\n readonly evidence: OrganizationPolicyHistoryResponse;\n}) {\n const { head, page, evidence } = input;\n const beforeVersion = (page.entries.at(-1)?.state.version ?? 0) + 1;\n if (\n head.principalType !== \"organization\" ||\n evidence.organizationId !== head.principalId ||\n evidence.stateHash !== head.stateHash ||\n evidence.beforeVersion !== beforeVersion ||\n evidence.nextBeforeVersion !== page.nextBeforeVersion ||\n !evidence.evidence.organization ||\n !principalHeadMatchesReference(evidence.evidence.organization.head, head)\n )\n reject(\"response does not match the requested organization page\");\n const entries = page.predecessor\n ? [page.predecessor, ...page.entries]\n : page.entries;\n if (evidence.evidence.organizationPayloads.length !== entries.length)\n reject(\"directory page is incomplete\");\n const descriptors = new Map<string, OrganizationAuthorityDescriptor>();\n const references: ReferencedPrincipalHead[] = [head];\n const groups = new Map<string, ReferencedPrincipalHead>();\n for (const [\n index,\n item,\n ] of evidence.evidence.organizationPayloads.entries()) {\n const { reference, payload } = item;\n const entry = entries[index];\n if (\n !entry ||\n !principalHeadMatchesReference(entry.state, reference) ||\n payload.principalType !== \"organization\" ||\n payload.principalId !== head.principalId ||\n payload.stateHash !== reference.stateHash ||\n descriptors.has(reference.stateHash)\n )\n reject(\"directory payload scope or order is invalid\");\n const hash = await computePrincipalStatePayloadCiphertextHash(\n payload.ciphertext,\n );\n if (\n hash !== entry.state.payloadCiphertextHash ||\n hash !== payload.ciphertextHash\n )\n reject(\"directory payload does not match its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== head.principalId)\n reject(\"directory belongs to another organization\");\n descriptors.set(reference.stateHash, descriptor);\n references.push(reference, ...descriptor.groupHeads);\n keepNewestGroupHeads(groups, descriptor.groupHeads);\n }\n verifyGroupSources(evidence, groups);\n return { descriptors, references };\n}\n\nfunction keepNewestGroupHeads(\n groups: Map<string, ReferencedPrincipalHead>,\n groupHeads: readonly ReferencedPrincipalHead[],\n) {\n for (const group of groupHeads) {\n const previous = groups.get(group.principalId);\n if (!previous || group.version > previous.version)\n groups.set(group.principalId, group);\n }\n}\n\nfunction verifyGroupSources(\n evidence: OrganizationPolicyHistoryResponse,\n groups: Map<string, ReferencedPrincipalHead>,\n) {\n if (evidence.evidence.groups.length !== groups.size)\n reject(\"unexpected group source\");\n const seen = new Set<string>();\n for (const source of evidence.evidence.groups) {\n const expected = groups.get(source.head.principalId);\n if (\n !expected ||\n seen.has(source.head.principalId) ||\n !principalHeadMatchesReference(source.head, expected)\n )\n reject(\"group source extends beyond the page's signed directory\");\n seen.add(source.head.principalId);\n }\n}\n"]}
1
+ {"version":3,"file":"organizationPolicyHistoryVerification.js","sourceRoot":"","sources":["organizationPolicyHistoryVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0CAA0C,EAC1C,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAG1E,SAAS,MAAM,CAAC,OAAe;IAC7B,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,gCAAgC,OAAO,EAAE,CAC1C,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAIrD;IACC,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC;IACvC,MAAM,aAAa,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,OAAO,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC;IACpE,IACE,IAAI,CAAC,aAAa,KAAK,cAAc;QACrC,QAAQ,CAAC,cAAc,KAAK,IAAI,CAAC,WAAW;QAC5C,QAAQ,CAAC,SAAS,KAAK,IAAI,CAAC,SAAS;QACrC,QAAQ,CAAC,aAAa,KAAK,aAAa;QACxC,QAAQ,CAAC,iBAAiB,KAAK,IAAI,CAAC,iBAAiB;QACrD,CAAC,QAAQ,CAAC,QAAQ,CAAC,YAAY;QAC/B,CAAC,6BAA6B,CAAC,QAAQ,CAAC,QAAQ,CAAC,YAAY,CAAC,IAAI,EAAE,IAAI,CAAC;QAEzE,MAAM,CAAC,yDAAyD,CAAC,CAAC;IACpE,MAAM,OAAO,GAAG,IAAI,CAAC,WAAW;QAC9B,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,IAAI,CAAC,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,MAAM,CAAC,yDAAyD,CAAC,CAAC;QACpE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;IACpC,CAAC;AACH,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { OrganizationPolicyHistoryResponse } from \"@tearleads/validators/response\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { RecoveredPrincipalHistoryPage } from \"../../principals/historyRecovery/loadRecoveredPrincipalHistoryPage\";\n\nfunction reject(message: string): never {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `Organization policy history: ${message}`,\n );\n}\n\n/** Bind every display payload and public source to the privately verified page. */\nexport async function verifyOrganizationPolicyHistory(input: {\n readonly head: ReferencedPrincipalHead;\n readonly page: RecoveredPrincipalHistoryPage;\n readonly evidence: OrganizationPolicyHistoryResponse;\n}) {\n const { head, page, evidence } = input;\n const beforeVersion = (page.entries.at(-1)?.state.version ?? 0) + 1;\n if (\n head.principalType !== \"organization\" ||\n evidence.organizationId !== head.principalId ||\n evidence.stateHash !== head.stateHash ||\n evidence.beforeVersion !== beforeVersion ||\n evidence.nextBeforeVersion !== page.nextBeforeVersion ||\n !evidence.evidence.organization ||\n !principalHeadMatchesReference(evidence.evidence.organization.head, head)\n )\n reject(\"response does not match the requested organization page\");\n const entries = page.predecessor\n ? [page.predecessor, ...page.entries]\n : page.entries;\n if (evidence.evidence.organizationPayloads.length !== entries.length)\n reject(\"directory page is incomplete\");\n const descriptors = new Map<string, OrganizationAuthorityDescriptor>();\n const references: ReferencedPrincipalHead[] = [head];\n const groups = new Map<string, ReferencedPrincipalHead>();\n for (const [\n index,\n item,\n ] of evidence.evidence.organizationPayloads.entries()) {\n const { reference, payload } = item;\n const entry = entries[index];\n if (\n !entry ||\n !principalHeadMatchesReference(entry.state, reference) ||\n payload.principalType !== \"organization\" ||\n payload.principalId !== head.principalId ||\n payload.stateHash !== reference.stateHash ||\n descriptors.has(reference.stateHash)\n )\n reject(\"directory payload scope or order is invalid\");\n const hash = await computePrincipalStatePayloadCiphertextHash(\n payload.ciphertext,\n );\n if (\n hash !== entry.state.payloadCiphertextHash ||\n hash !== payload.ciphertextHash\n )\n reject(\"directory payload does not match its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== head.principalId)\n reject(\"directory belongs to another organization\");\n descriptors.set(reference.stateHash, descriptor);\n references.push(reference, ...descriptor.groupHeads);\n keepNewestGroupHeads(groups, descriptor.groupHeads);\n }\n verifyGroupSources(evidence, groups);\n return { descriptors, references };\n}\n\nfunction keepNewestGroupHeads(\n groups: Map<string, ReferencedPrincipalHead>,\n groupHeads: readonly ReferencedPrincipalHead[],\n) {\n for (const group of groupHeads) {\n const previous = groups.get(group.principalId);\n if (!previous || group.version > previous.version)\n groups.set(group.principalId, group);\n }\n}\n\nfunction verifyGroupSources(\n evidence: OrganizationPolicyHistoryResponse,\n groups: Map<string, ReferencedPrincipalHead>,\n) {\n if (evidence.evidence.groups.length !== groups.size)\n reject(\"unexpected group source\");\n const seen = new Set<string>();\n for (const source of evidence.evidence.groups) {\n const expected = groups.get(source.head.principalId);\n if (\n !expected ||\n seen.has(source.head.principalId) ||\n !principalHeadMatchesReference(source.head, expected)\n )\n reject(\"group source extends beyond the page's signed directory\");\n seen.add(source.head.principalId);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
- import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
2
+ import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
3
3
  /** Couple supplied group receipts to the directory acknowledged in the same batch. */
4
4
  export function assertAcknowledgedDirectoryBindings(organizationId, receipts) {
5
5
  const directories = receipts.filter((receipt) => receipt.currentState.principalType === "organization");
@@ -1 +1 @@
1
- {"version":3,"file":"acknowledgedDirectoryBindings.js","sourceRoot":"","sources":["acknowledgedDirectoryBindings.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,0DAA0D,CAAC;AAElE,sFAAsF;AACtF,MAAM,UAAU,mCAAmC,CACjD,cAAsB,EACtB,QAA+C;IAE/C,MAAM,WAAW,GAAG,QAAQ,CAAC,MAAM,CACjC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,cAAc,CACnE,CAAC;IACF,IACE,WAAW,CAAC,MAAM,KAAK,CAAC;QACxB,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,OAAO,CAAC;QAE1E,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,0DAA0D,CAC3D,CAAC;IACJ,KAAK,MAAM,SAAS,IAAI,WAAW,EAAE,CAAC;QACpC,MAAM,UAAU,GAAG,oCAAoC,CACrD,SAAS,CAAC,cAAc,CAAC,UAAU,CACpC,CAAC;QACF,IACE,SAAS,CAAC,YAAY,CAAC,WAAW,KAAK,cAAc;YACrD,UAAU,CAAC,cAAc,KAAK,cAAc;YAC5C,QAAQ,CAAC,IAAI,CACX,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,CACnB,YAAY,CAAC,aAAa,KAAK,OAAO;gBACtC,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CACnC,6BAA6B,CAAC,IAAI,EAAE,YAAY,CAAC,CAClD,CACJ;YAED,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,2DAA2D,CAC5D,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\n\n/** Couple supplied group receipts to the directory acknowledged in the same batch. */\nexport function assertAcknowledgedDirectoryBindings(\n organizationId: string,\n receipts: readonly PrincipalPolicyPageCurrent[],\n) {\n const directories = receipts.filter(\n (receipt) => receipt.currentState.principalType === \"organization\",\n );\n if (\n directories.length === 0 &&\n receipts.some((receipt) => receipt.currentState.principalType === \"group\")\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledged groups require their organization directory\",\n );\n for (const directory of directories) {\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.currentPayload.ciphertext,\n );\n if (\n directory.currentState.principalId !== organizationId ||\n descriptor.organizationId !== organizationId ||\n receipts.some(\n ({ currentState }) =>\n currentState.principalType === \"group\" &&\n !descriptor.groupHeads.some((head) =>\n principalHeadMatchesReference(head, currentState),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged organization does not bind its group receipt\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"acknowledgedDirectoryBindings.js","sourceRoot":"","sources":["acknowledgedDirectoryBindings.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAE1E,sFAAsF;AACtF,MAAM,UAAU,mCAAmC,CACjD,cAAsB,EACtB,QAA+C;IAE/C,MAAM,WAAW,GAAG,QAAQ,CAAC,MAAM,CACjC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,cAAc,CACnE,CAAC;IACF,IACE,WAAW,CAAC,MAAM,KAAK,CAAC;QACxB,QAAQ,CAAC,IAAI,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,YAAY,CAAC,aAAa,KAAK,OAAO,CAAC;QAE1E,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,0DAA0D,CAC3D,CAAC;IACJ,KAAK,MAAM,SAAS,IAAI,WAAW,EAAE,CAAC;QACpC,MAAM,UAAU,GAAG,oCAAoC,CACrD,SAAS,CAAC,cAAc,CAAC,UAAU,CACpC,CAAC;QACF,IACE,SAAS,CAAC,YAAY,CAAC,WAAW,KAAK,cAAc;YACrD,UAAU,CAAC,cAAc,KAAK,cAAc;YAC5C,QAAQ,CAAC,IAAI,CACX,CAAC,EAAE,YAAY,EAAE,EAAE,EAAE,CACnB,YAAY,CAAC,aAAa,KAAK,OAAO;gBACtC,CAAC,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CACnC,6BAA6B,CAAC,IAAI,EAAE,YAAY,CAAC,CAClD,CACJ;YAED,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,2DAA2D,CAC5D,CAAC;IACN,CAAC;AACH,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\n\n/** Couple supplied group receipts to the directory acknowledged in the same batch. */\nexport function assertAcknowledgedDirectoryBindings(\n organizationId: string,\n receipts: readonly PrincipalPolicyPageCurrent[],\n) {\n const directories = receipts.filter(\n (receipt) => receipt.currentState.principalType === \"organization\",\n );\n if (\n directories.length === 0 &&\n receipts.some((receipt) => receipt.currentState.principalType === \"group\")\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledged groups require their organization directory\",\n );\n for (const directory of directories) {\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.currentPayload.ciphertext,\n );\n if (\n directory.currentState.principalId !== organizationId ||\n descriptor.organizationId !== organizationId ||\n receipts.some(\n ({ currentState }) =>\n currentState.principalType === \"group\" &&\n !descriptor.groupHeads.some((head) =>\n principalHeadMatchesReference(head, currentState),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged organization does not bind its group receipt\",\n );\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
- import { organizationAdminSignerUserIds } from "../../../data/principals/principalPolicyAdminSigners.js";
2
+ import { organizationAdminSignerUserIds } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
3
3
  import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
4
4
  /** Resolve uncertain work and verify the signing administrator before any mutation pins. */
5
5
  export async function loadCurrentOrganizationMutationAuthority(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"currentOrganizationMutationAuthority.js","sourceRoot":"","sources":["currentOrganizationMutationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,8BAA8B,EAAE,MAAM,sDAAsD,CAAC;AACtG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AAEnF,4FAA4F;AAC5F,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,KAQC;IAED,MAAM,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;IAC3B,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,KAAK,CAAC,+BAA+B,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;IAClE,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAChE,MAAM,sBAAsB,GAAG,8BAA8B,CAC3D,SAAS,CAAC,MAAM,CAAC,MAAM,CACxB,CAAC;IACF,IAAI,CAAC,sBAAsB,CAAC,QAAQ,CAAC,KAAK,CAAC,YAAY,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;IAC9D,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,CAAC;AAC/C,CAAC","sourcesContent":["import { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { organizationAdminSignerUserIds } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\n\n/** Resolve uncertain work and verify the signing administrator before any mutation pins. */\nexport async function loadCurrentOrganizationMutationAuthority(\n input: Omit<\n Parameters<typeof loadCurrentOrganizationAuthority>[0],\n \"organizationReference\"\n > & {\n readonly signerUserId: string;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n },\n) {\n const owned = { ...input };\n assertProjectionVerificationCurrent(owned.stillCurrent);\n await owned.recoverPendingPrincipalMutation(owned.organizationId);\n assertProjectionVerificationCurrent(owned.stillCurrent);\n const authority = await loadCurrentOrganizationAuthority(owned);\n const currentOrgAdminUserIds = organizationAdminSignerUserIds(\n authority.admins.policy,\n );\n if (!currentOrgAdminUserIds.includes(owned.signerUserId))\n throw new Error(\"Organization admin authority is required\");\n return { authority, currentOrgAdminUserIds };\n}\n"]}
1
+ {"version":3,"file":"currentOrganizationMutationAuthority.js","sourceRoot":"","sources":["currentOrganizationMutationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,8BAA8B,EAAE,MAAM,8DAA8D,CAAC;AAC9G,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AAEnF,4FAA4F;AAC5F,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,KAQC;IAED,MAAM,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;IAC3B,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,KAAK,CAAC,+BAA+B,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;IAClE,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,SAAS,GAAG,MAAM,gCAAgC,CAAC,KAAK,CAAC,CAAC;IAChE,MAAM,sBAAsB,GAAG,8BAA8B,CAC3D,SAAS,CAAC,MAAM,CAAC,MAAM,CACxB,CAAC;IACF,IAAI,CAAC,sBAAsB,CAAC,QAAQ,CAAC,KAAK,CAAC,YAAY,CAAC;QACtD,MAAM,IAAI,KAAK,CAAC,0CAA0C,CAAC,CAAC;IAC9D,OAAO,EAAE,SAAS,EAAE,sBAAsB,EAAE,CAAC;AAC/C,CAAC","sourcesContent":["import { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { organizationAdminSignerUserIds } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\n\n/** Resolve uncertain work and verify the signing administrator before any mutation pins. */\nexport async function loadCurrentOrganizationMutationAuthority(\n input: Omit<\n Parameters<typeof loadCurrentOrganizationAuthority>[0],\n \"organizationReference\"\n > & {\n readonly signerUserId: string;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n },\n) {\n const owned = { ...input };\n assertProjectionVerificationCurrent(owned.stillCurrent);\n await owned.recoverPendingPrincipalMutation(owned.organizationId);\n assertProjectionVerificationCurrent(owned.stillCurrent);\n const authority = await loadCurrentOrganizationAuthority(owned);\n const currentOrgAdminUserIds = organizationAdminSignerUserIds(\n authority.admins.policy,\n );\n if (!currentOrgAdminUserIds.includes(owned.signerUserId))\n throw new Error(\"Organization admin authority is required\");\n return { authority, currentOrgAdminUserIds };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
+ import { principalPolicyReferenceFromBundle } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
2
3
  import { scopedGroupHistoryProtection } from "../../../data/principals/principalHistoryScopeProtection.js";
3
- import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
4
4
  import { captureAcknowledgedPrincipalPredecessor } from "../../principals/acknowledgements/acknowledgedPrincipalPredecessor.js";
5
5
  import { retainAcknowledgedPrincipalCurrents, } from "./retainAcknowledgedPrincipalCurrents.js";
6
6
  /** Couple directory acknowledgements to any newly created group under the same lease. */
@@ -1 +1 @@
1
- {"version":3,"file":"currentOrganizationMutationRetention.js","sourceRoot":"","sources":["currentOrganizationMutationRetention.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AACxG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAG1G,OAAO,EAAE,uCAAuC,EAAE,MAAM,oEAAoE,CAAC;AAG7H,OAAO,EAEL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AAE/C,yFAAyF;AACzF,MAAM,CAAC,KAAK,UAAU,0CAA0C,CAAC,KAahE;IACC,MAAM,WAAW,GAAG,MAAM,uCAAuC,CAAC;QAChE,GAAG,KAAK,CAAC,iBAAiB;QAC1B,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,KAAK,EAClB,OAAqD,EACrD,EAAE;QACF,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,mCAAmC,CAAC;YACxC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAA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,QAAQ,EAAE,OAAO,CAAC,oBAAoB;oBACtC,QAAQ,EAAE,KAAK,CAAC,iBAAiB;iBAClC;aACF,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { scopedGroupHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"../../principals/acknowledgements/acknowledgedPrincipalPredecessor\";\nimport type { PrincipalPolicyPageReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\n/** Couple directory acknowledgements to any newly created group under the same lease. */\nexport async function createCurrentOrganizationMutationRetention(input: {\n readonly runtime: {\n readonly infra: { readonly execSql: ExecSql };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n };\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly organizationId: string;\n readonly directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"];\n readonly stillCurrent: () => boolean;\n}) {\n const predecessor = await captureAcknowledgedPrincipalPredecessor({\n ...input.directoryRecovery,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n const retain = async (\n entries: readonly AcknowledgedPrincipalCurrentInput[],\n ) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n entries,\n stillCurrent: input.stillCurrent,\n });\n };\n return {\n retainDirectory: (\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n ) =>\n retain([\n { predecessor, request, response, recovery: input.directoryRecovery },\n ]),\n retainCreatedGroup: (receipt: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly organizationResponse: PrincipalPolicyMutationResponse;\n }) => {\n const adminHead = {\n ...principalPolicyReferenceFromBundle(input.authority.admins.current),\n principalType: \"group\" as const,\n };\n return retain([\n {\n initialGroup: true,\n predecessor: null,\n request: receipt.request,\n response: receipt.response,\n recovery: {\n historyReader: input.historyReader,\n expectedHead: receipt.response.head,\n protection: scopedGroupHistoryProtection(\n input.protection,\n input.organizationId,\n input.authority.descriptor.adminGroupId,\n ),\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n loadExternalAuthority: async () => ({\n currentHead: adminHead,\n states: [\n {\n head: adminHead,\n projection: input.authority.admins.policy.projection,\n },\n ],\n }),\n },\n },\n {\n predecessor,\n request: receipt.organizationRequest,\n response: receipt.organizationResponse,\n recovery: input.directoryRecovery,\n },\n ]);\n },\n };\n}\n"]}
1
+ {"version":3,"file":"currentOrganizationMutationRetention.js","sourceRoot":"","sources":["currentOrganizationMutationRetention.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AAGxG,OAAO,EAAE,uCAAuC,EAAE,MAAM,oEA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,CAAC,aAAa;wBAClC,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI;wBACnC,UAAU,EAAE,4BAA4B,CACtC,KAAK,CAAC,UAAU,EAChB,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,YAAY,CACxC;wBACD,0BAA0B,EACxB,KAAK,CAAC,OAAO,CAAC,0BAA0B;wBAC1C,qBAAqB,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC;4BAClC,WAAW,EAAE,SAAS;4BACtB,MAAM,EAAE;gCACN;oCACE,IAAI,EAAE,SAAS;oCACf,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU;iCACrD;6BACF;yBACF,CAAC;qBACH;iBACF;gBACD;oBACE,WAAW;oBACX,OAAO,EAAE,OAAO,CAAC,mBAAmB;oBACpC,QAAQ,EAAE,OAAO,CAAC,oBAAoB;oBACtC,QAAQ,EAAE,KAAK,CAAC,iBAAiB;iBAClC;aACF,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { scopedGroupHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"../../principals/acknowledgements/acknowledgedPrincipalPredecessor\";\nimport type { PrincipalPolicyPageReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\n/** Couple directory acknowledgements to any newly created group under the same lease. */\nexport async function createCurrentOrganizationMutationRetention(input: {\n readonly runtime: {\n readonly infra: { readonly execSql: ExecSql };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n };\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly organizationId: string;\n readonly directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"];\n readonly stillCurrent: () => boolean;\n}) {\n const predecessor = await captureAcknowledgedPrincipalPredecessor({\n ...input.directoryRecovery,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n const retain = async (\n entries: readonly AcknowledgedPrincipalCurrentInput[],\n ) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n entries,\n stillCurrent: input.stillCurrent,\n });\n };\n return {\n retainDirectory: (\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n ) =>\n retain([\n { predecessor, request, response, recovery: input.directoryRecovery },\n ]),\n retainCreatedGroup: (receipt: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly organizationResponse: PrincipalPolicyMutationResponse;\n }) => {\n const adminHead = {\n ...principalPolicyReferenceFromBundle(input.authority.admins.current),\n principalType: \"group\" as const,\n };\n return retain([\n {\n initialGroup: true,\n predecessor: null,\n request: receipt.request,\n response: receipt.response,\n recovery: {\n historyReader: input.historyReader,\n expectedHead: receipt.response.head,\n protection: scopedGroupHistoryProtection(\n input.protection,\n input.organizationId,\n input.authority.descriptor.adminGroupId,\n ),\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n loadExternalAuthority: async () => ({\n currentHead: adminHead,\n states: [\n {\n head: adminHead,\n projection: input.authority.admins.policy.projection,\n },\n ],\n }),\n },\n },\n {\n predecessor,\n request: receipt.organizationRequest,\n response: receipt.organizationResponse,\n recovery: input.directoryRecovery,\n },\n ]);\n },\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
+ import { principalPolicyReferenceFromBundle } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
2
3
  import { scopedGroupHistoryProtection } from "../../../data/principals/principalHistoryScopeProtection.js";
3
- import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
4
4
  import { captureAcknowledgedPrincipalPredecessor } from "../../principals/acknowledgements/acknowledgedPrincipalPredecessor.js";
5
5
  import { createCurrentPrincipalMutationLease, } from "../../principals/principalPolicyService.js";
6
6
  import { loadCurrentGroupPolicyMutationContext } from "../groupPolicy/currentGroupPolicyMutationContext.js";
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeCurrentGroupMutation.js","sourceRoot":"","sources":["runtimeCurrentGroupMutation.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AACxG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAE1G,OAAO,EAAE,uCAAuC,EAAE,MAAM,oEAAoE,CAAC;AAE7H,OAAO,EACL,mCAAmC,GAEpC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AACzG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AAEzF,OAAO,EAEL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AA+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,CAAC,CAAC;IACF,OAAO;QACL,cAAc,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE;QAC1E,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { CurrentPolicyReferenceResolver } from \"../../../data/principals/currentPolicyReferenceResolver\";\nimport { scopedGroupHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"../../principals/acknowledgements/acknowledgedPrincipalPredecessor\";\nimport type { PrincipalPolicyPageReader } from \"../../principals/principalPolicyHistoryReader\";\nimport {\n createCurrentPrincipalMutationLease,\n type PrincipalPolicyRuntime,\n} from \"../../principals/principalPolicyService\";\nimport { loadCurrentGroupPolicyMutationContext } from \"../groupPolicy/currentGroupPolicyMutationContext\";\nimport { resolveCurrentGroupMutationReferences } from \"./currentGroupMutationReferences\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\ntype MutationRuntime = PrincipalPolicyRuntime & {\n readonly apiClient: Pick<\n PrincipalMutationRecoveryApi,\n \"recoverPendingPrincipalMutation\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n};\n\ntype CurrentMutationContext = Awaited<\n ReturnType<typeof loadCurrentGroupPolicyMutationContext>\n>;\n\nexport type RuntimeCurrentGroupMutationContext = CurrentMutationContext & {\n readonly resolveAuthoredPolicyReferences: CurrentPolicyReferenceResolver;\n readonly loadGroup: (\n groupId: string,\n ) => Promise<RuntimeCurrentGroupMutationContext>;\n readonly groupRetention: Pick<\n AcknowledgedPrincipalCurrentInput,\n \"recovery\" | \"predecessor\"\n >;\n readonly retainAcknowledged: (\n receipt: CurrentMutationReceipt,\n ) => Promise<void>;\n};\n\ninterface CurrentMutationReceipt {\n readonly additionalGroups?:\n | readonly (AcknowledgedPrincipalCurrentInput & {\n readonly retiredContainerIds?: readonly string[] | undefined;\n })[]\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly response: CommitOrganizationGroupPolicyResponse;\n readonly retiredContainerIds?: readonly string[] | undefined;\n}\n\ninterface MutationInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/** Keep private prefix custody inside the entire mutation and its acknowledgement. */\nexport function createRuntimeCurrentGroupMutation(runtime: MutationRuntime) {\n const lease = createCurrentPrincipalMutationLease(runtime.principalPolicies);\n if (!lease) return undefined;\n return async <T>(\n input: MutationInput,\n work: (context: RuntimeCurrentGroupMutationContext) => Promise<T>,\n ): Promise<T> => {\n input = { ...input };\n return lease(\n input.stillCurrent,\n async ({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery,\n }) => {\n const loadGroup = async (\n groupId: string,\n ): Promise<RuntimeCurrentGroupMutationContext> => {\n const context = await loadCurrentGroupPolicyMutationContext({\n ...input,\n groupId,\n execSql: runtime.infra.execSql,\n resolveCurrentPolicy,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n stillCurrent,\n });\n const retention = await createCurrentMutationRetention(\n runtime,\n { ...input, groupId },\n context,\n protection,\n historyReader,\n directoryRecovery(context.organizationCurrent.current),\n );\n return {\n ...context,\n ...retention,\n loadGroup,\n resolveAuthoredPolicyReferences: (current, references) =>\n resolveCurrentGroupMutationReferences({\n current,\n predecessor: context.verifiedCurrentPolicy,\n references,\n readPredecessorReference: context.readPredecessorReference,\n stillCurrent: context.stillCurrent,\n }),\n };\n };\n const context = await loadGroup(input.groupId);\n const result = await work(context);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function createCurrentMutationRetention(\n runtime: MutationRuntime,\n input: MutationInput,\n context: CurrentMutationContext,\n protection: PrincipalPolicyHistoryProgressOptions,\n historyReader: PrincipalPolicyPageReader,\n directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"],\n) {\n const common = {\n historyReader,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n const groupRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"] = {\n ...common,\n expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),\n protection: context.isOrganizationAdminsGroup\n ? protection\n : scopedGroupHistoryProtection(\n protection,\n input.organizationId,\n context.adminGroupId,\n ),\n historyVerification: context.isOrganizationAdminsGroup\n ? \"direct-admins\"\n : \"standard\",\n ...(context.isOrganizationAdminsGroup\n ? {}\n : { loadExternalAuthority: async () => context.externalAuthority }),\n };\n const capture = (recovery: AcknowledgedPrincipalCurrentInput[\"recovery\"]) =>\n captureAcknowledgedPrincipalPredecessor({\n ...recovery,\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: context.stillCurrent,\n });\n const groupPredecessor = await capture(groupRecovery);\n const directoryPredecessor = await capture(directoryRecovery);\n const retainAcknowledged = async (\n receipt: CurrentMutationReceipt,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(context.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n entries: [\n ...(receipt.additionalGroups ?? []),\n {\n recovery: groupRecovery,\n predecessor: groupPredecessor,\n request: receipt.request,\n response: receipt.response.groupPolicy,\n },\n {\n recovery: directoryRecovery,\n predecessor: directoryPredecessor,\n request: receipt.organizationRequest,\n response: receipt.response.organizationPolicy,\n },\n ],\n retirements: [\n ...(receipt.additionalGroups ?? []).map((entry) => ({\n principalId: entry.request.state.principalId,\n principalType: \"group\" as const,\n containerIds: entry.retiredContainerIds ?? [],\n })),\n {\n principalId: input.groupId,\n principalType: \"group\",\n containerIds: receipt.retiredContainerIds ?? [],\n },\n ],\n stillCurrent: context.stillCurrent,\n });\n };\n return {\n groupRetention: { recovery: groupRecovery, predecessor: groupPredecessor },\n retainAcknowledged,\n };\n}\n"]}
1
+ {"version":3,"file":"runtimeCurrentGroupMutation.js","sourceRoot":"","sources":["runtimeCurrentGroupMutation.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAElH,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AAExG,OAAO,EAAE,uCAAuC,EAAE,MAAM,oEAAoE,CAAC;AAE7H,OAAO,EACL,mCAAmC,GAEpC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AACzG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AAEzF,OAAO,EAEL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AA+C/C,sFAAsF;AACtF,MAAM,UAAU,iCAAiC,CAAC,OAAwB;IACxE,MAAM,KAAK,GAAG,mCAAmC,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC7E,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,EACV,KAAoB,EACpB,IAAiE,EACrD,EAAE;QACd,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;QACrB,OAAO,KAAK,CACV,KAAK,CAAC,YAAY,EAClB,KAAK,EAAE,EACL,UAAU,EACV,YAAY,EACZ,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EAAE;gBACP,GAAG,CAAC,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC;gBACnC;oBACE,QAAQ,EAAE,aAAa;oBACvB,WAAW,EAAE,gBAAgB;oBAC7B,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,WAAW;iBACvC;gBACD;oBACE,QAAQ,EAAE,iBAAiB;oBAC3B,WAAW,EAAE,oBAAoB;oBACjC,OAAO,EAAE,OAAO,CAAC,mBAAmB;oBACpC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,kBAAkB;iBAC9C;aACF;YACD,WAAW,EAAE;gBACX,GAAG,CAAC,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;oBAClD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;oBAC5C,aAAa,EAAE,OAAgB;oBAC/B,YAAY,EAAE,KAAK,CAAC,mBAAmB,IAAI,EAAE;iBAC9C,CAAC,CAAC;gBACH;oBACE,WAAW,EAAE,KAAK,CAAC,OAAO;oBAC1B,aAAa,EAAE,OAAO;oBACtB,YAAY,EAAE,OAAO,CAAC,mBAAmB,IAAI,EAAE;iBAChD;aACF;YACD,YAAY,EAAE,OAAO,CAAC,YAAY;SACnC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO;QACL,cAAc,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE;QAC1E,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { CurrentPolicyReferenceResolver } from \"../../../data/principals/currentPolicyReferenceResolver\";\nimport { scopedGroupHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"../../principals/acknowledgements/acknowledgedPrincipalPredecessor\";\nimport type { PrincipalPolicyPageReader } from \"../../principals/principalPolicyHistoryReader\";\nimport {\n createCurrentPrincipalMutationLease,\n type PrincipalPolicyRuntime,\n} from \"../../principals/principalPolicyService\";\nimport { loadCurrentGroupPolicyMutationContext } from \"../groupPolicy/currentGroupPolicyMutationContext\";\nimport { resolveCurrentGroupMutationReferences } from \"./currentGroupMutationReferences\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\ntype MutationRuntime = PrincipalPolicyRuntime & {\n readonly apiClient: Pick<\n PrincipalMutationRecoveryApi,\n \"recoverPendingPrincipalMutation\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n};\n\ntype CurrentMutationContext = Awaited<\n ReturnType<typeof loadCurrentGroupPolicyMutationContext>\n>;\n\nexport type RuntimeCurrentGroupMutationContext = CurrentMutationContext & {\n readonly resolveAuthoredPolicyReferences: CurrentPolicyReferenceResolver;\n readonly loadGroup: (\n groupId: string,\n ) => Promise<RuntimeCurrentGroupMutationContext>;\n readonly groupRetention: Pick<\n AcknowledgedPrincipalCurrentInput,\n \"recovery\" | \"predecessor\"\n >;\n readonly retainAcknowledged: (\n receipt: CurrentMutationReceipt,\n ) => Promise<void>;\n};\n\ninterface CurrentMutationReceipt {\n readonly additionalGroups?:\n | readonly (AcknowledgedPrincipalCurrentInput & {\n readonly retiredContainerIds?: readonly string[] | undefined;\n })[]\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly response: CommitOrganizationGroupPolicyResponse;\n readonly retiredContainerIds?: readonly string[] | undefined;\n}\n\ninterface MutationInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/** Keep private prefix custody inside the entire mutation and its acknowledgement. */\nexport function createRuntimeCurrentGroupMutation(runtime: MutationRuntime) {\n const lease = createCurrentPrincipalMutationLease(runtime.principalPolicies);\n if (!lease) return undefined;\n return async <T>(\n input: MutationInput,\n work: (context: RuntimeCurrentGroupMutationContext) => Promise<T>,\n ): Promise<T> => {\n input = { ...input };\n return lease(\n input.stillCurrent,\n async ({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery,\n }) => {\n const loadGroup = async (\n groupId: string,\n ): Promise<RuntimeCurrentGroupMutationContext> => {\n const context = await loadCurrentGroupPolicyMutationContext({\n ...input,\n groupId,\n execSql: runtime.infra.execSql,\n resolveCurrentPolicy,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n stillCurrent,\n });\n const retention = await createCurrentMutationRetention(\n runtime,\n { ...input, groupId },\n context,\n protection,\n historyReader,\n directoryRecovery(context.organizationCurrent.current),\n );\n return {\n ...context,\n ...retention,\n loadGroup,\n resolveAuthoredPolicyReferences: (current, references) =>\n resolveCurrentGroupMutationReferences({\n current,\n predecessor: context.verifiedCurrentPolicy,\n references,\n readPredecessorReference: context.readPredecessorReference,\n stillCurrent: context.stillCurrent,\n }),\n };\n };\n const context = await loadGroup(input.groupId);\n const result = await work(context);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function createCurrentMutationRetention(\n runtime: MutationRuntime,\n input: MutationInput,\n context: CurrentMutationContext,\n protection: PrincipalPolicyHistoryProgressOptions,\n historyReader: PrincipalPolicyPageReader,\n directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"],\n) {\n const common = {\n historyReader,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n const groupRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"] = {\n ...common,\n expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),\n protection: context.isOrganizationAdminsGroup\n ? protection\n : scopedGroupHistoryProtection(\n protection,\n input.organizationId,\n context.adminGroupId,\n ),\n historyVerification: context.isOrganizationAdminsGroup\n ? \"direct-admins\"\n : \"standard\",\n ...(context.isOrganizationAdminsGroup\n ? {}\n : { loadExternalAuthority: async () => context.externalAuthority }),\n };\n const capture = (recovery: AcknowledgedPrincipalCurrentInput[\"recovery\"]) =>\n captureAcknowledgedPrincipalPredecessor({\n ...recovery,\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: context.stillCurrent,\n });\n const groupPredecessor = await capture(groupRecovery);\n const directoryPredecessor = await capture(directoryRecovery);\n const retainAcknowledged = async (\n receipt: CurrentMutationReceipt,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(context.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n entries: [\n ...(receipt.additionalGroups ?? []),\n {\n recovery: groupRecovery,\n predecessor: groupPredecessor,\n request: receipt.request,\n response: receipt.response.groupPolicy,\n },\n {\n recovery: directoryRecovery,\n predecessor: directoryPredecessor,\n request: receipt.organizationRequest,\n response: receipt.response.organizationPolicy,\n },\n ],\n retirements: [\n ...(receipt.additionalGroups ?? []).map((entry) => ({\n principalId: entry.request.state.principalId,\n principalType: \"group\" as const,\n containerIds: entry.retiredContainerIds ?? [],\n })),\n {\n principalId: input.groupId,\n principalType: \"group\",\n containerIds: receipt.retiredContainerIds ?? [],\n },\n ],\n stillCurrent: context.stillCurrent,\n });\n };\n return {\n groupRetention: { recovery: groupRecovery, predecessor: groupPredecessor },\n retainAcknowledged,\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { compareCanonicalStrings, computeContainerKekRecipientTargetHash, computeContainerKeyEpochHash, computePrincipalStateHash, } from "../../../internal/crypto/index.js";
2
2
  import { canonicalKeyingJsonString } from "../../../data/keying/canonicalJson.js";
3
3
  import { readContainerKeyEpoch, readContainerKeyWrap, } from "../../../data/keyingProjectionVerification/readers.js";
4
- import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
4
+ import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
5
5
  function sortedCanonicalValues(values, label) {
6
6
  return [...values].sort((left, right) => compareCanonicalStrings(canonicalKeyingJsonString(left, label), canonicalKeyingJsonString(right, label)));
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sCAAsC,EACtC,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EACL,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AAEzG,SAAS,qBAAqB,CAAI,MAAoB,EAAE,KAAa;IACnE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,uBAAuB,CACrB,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC,EACtC,yBAAyB,CAAC,KAAK,EAAE,KAAK,CAAC,CACxC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8CAA8C,CAC5D,QAAiD,EACjD,QAAiD;IAEjD,MAAM,UAAU,GAAG,CAAC,KAA8C,EAAE,EAAE,CAAC,CAAC;QACtE,GAAG,KAAK;QACR,SAAS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AC;IAC1B,MAAM,SAAS,GAAG,MAAM,yBAAyB,CAAC,KAAK,CAAC,CAAC;IACzD,IACE,CAAC,6BAA6B,CAAC,QAAQ,CAAC,IAAI,EAAE;QAC5C,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,SAAS;QACT,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC;QAEF,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,MAAM,uCAAuC,CAAC;QAC5C,QAAQ,EAAE,OAAO,CAAC,kBAAkB,IAAI,EAAE;QAC1C,SAAS,EAAE,QAAQ,CAAC,kBAAkB;KACvC,CAAC,CAAC;IACH,MAAM,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,EAAE,SAAS,EAAE,GAAG,QAAQ,CAAC;IAC/B,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QAChD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,OAAO,CAAC,gBAAgB;YAC3B,SAAS;SACV;QACD,iBAAiB,EAAE,OAAO,CAAC,UAAU;QACrC,aAAa,EAAE,OAAO,CAAC,MAAM;QAC7B,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,KAAK,CAAC,QAAQ;YACrB,SAAS,EAAE,OAAO,CAAC,eAAe;SACnC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n compareCanonicalStrings,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n computePrincipalStateHash,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport {\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\n/**\n * Each rematerialized container's acknowledgement names its commit by hash;\n * match every hash against the request this client authored.\n */\nasync function assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): Promise<void> {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const label = \"authored group policy container mutation\";\n const keyEpoch = readContainerKeyEpoch(request.keyEpoch, label);\n const recipientTargets = sortedCanonicalValues(\n request.wraps.map((value) => {\n const wrap = readContainerKeyWrap(value, label);\n return {\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n };\n }),\n \"authored recipient target\",\n );\n // The request carries this client's own hash of the manifest it signed,\n // and that manifest names its epoch and event by hash. A rotation's signed\n // body commits its keyring hash, so a substituted keyring must refuse\n // here, before journal recovery clears the saved request. A grant that\n // keeps its epoch commits none; the container acknowledgement checks the\n // retained keyring against the epoch's own.\n const committedKeyringHash = Reflect.get(\n Object(request.body),\n \"keyringHash\",\n );\n if (\n response.manifestHead.manifestHash !== request.expectedManifestHash ||\n response.manifestHead.epoch !== Reflect.get(request.manifest, \"epoch\") ||\n response.eventHash !== Reflect.get(request.manifest, \"eventHash\") ||\n response.containerKek.containerKeyEpochId !== keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||\n response.containerKek.keyEpochHash !==\n (await computeContainerKeyEpochHash(keyEpoch)) ||\n (typeof committedKeyringHash === \"string\" &&\n response.containerKek.keyringHash !== committedKeyringHash) ||\n response.containerKek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(recipientTargets))\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/**\n * The current an acknowledgement commits, rebuilt from this client's own\n * signed request: the server returns only the head it stored, the insertion\n * time it assigned to the state and payload, and hash-form container\n * acknowledgements. A head other than the one the request commits to refuses.\n * Nothing here manufactures predecessor history or pins.\n */\nexport async function acknowledgedPrincipalPolicyCurrent(input: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<PrincipalPolicyPageCurrent> {\n const { request, response } = input;\n const { state } = request;\n const stateHash = await computePrincipalStateHash(state);\n if (\n !principalHeadMatchesReference(response.head, {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash,\n keyFingerprint: state.keyFingerprint,\n })\n )\n throw new Error(\"Principal policy acknowledgement names another head\");\n await assertContainerMutationAcknowledgements({\n requests: request.containerMutations ?? [],\n responses: response.containerMutations,\n });\n const { principalType, principalId } = state;\n const { createdAt } = response;\n return {\n currentState: { ...state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...request.encryptedPayload,\n createdAt,\n },\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: state.keyEpoch,\n envelopes: request.memberEnvelopes,\n },\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,sCAAsC,EACtC,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,yBAAyB,EAAE,MAAM,oCAAoC,CAAC;AAC/E,OAAO,EACL,qBAAqB,EACrB,oBAAoB,GACrB,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,SAAS,qBAAqB,CAAI,MAAoB,EAAE,KAAa;IACnE,OAAO,CAAC,GAAG,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACtC,uBAAuB,CACrB,yBAAyB,CAAC,IAAI,EAAE,KAAK,CAAC,EACtC,yBAAyB,CAAC,KAAK,EAAE,KAAK,CAAC,CACxC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,8CAA8C,CAC5D,QAAiD,EACjD,QAAiD;IAEjD,MAAM,UAAU,GAAG,CAAC,KAA8C,EAAE,EAAE,CAAC,CAAC;QACtE,GAAG,KAAK;QACR,SAAS,EAAE,qBAAqB,CAC9B,KAAK,CAAC,SAAS,EACf,2BAA2B,CAC5B;KACF,CAAC,CAAC;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CAAC,6BAA6B,CAAC,QAAQ,CAAC,IAAI,EAAE;QAC5C,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,SAAS;QACT,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC;QAEF,MAAM,IAAI,KAAK,CAAC,qDAAqD,CAAC,CAAC;IACzE,MAAM,uCAAuC,CAAC;QAC5C,QAAQ,EAAE,OAAO,CAAC,kBAAkB,IAAI,EAAE;QAC1C,SAAS,EAAE,QAAQ,CAAC,kBAAkB;KACvC,CAAC,CAAC;IACH,MAAM,EAAE,aAAa,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC7C,MAAM,EAAE,SAAS,EAAE,GAAG,QAAQ,CAAC;IAC/B,OAAO;QACL,YAAY,EAAE,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE;QAChD,cAAc,EAAE;YACd,aAAa;YACb,WAAW;YACX,SAAS;YACT,GAAG,OAAO,CAAC,gBAAgB;YAC3B,SAAS;SACV;QACD,iBAAiB,EAAE,OAAO,CAAC,UAAU;QACrC,aAAa,EAAE,OAAO,CAAC,MAAM;QAC7B,sBAAsB,EAAE;YACtB,aAAa;YACb,WAAW;YACX,SAAS;YACT,KAAK,EAAE,KAAK,CAAC,QAAQ;YACrB,SAAS,EAAE,OAAO,CAAC,eAAe;SACnC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport {\n compareCanonicalStrings,\n computeContainerKekRecipientTargetHash,\n computeContainerKeyEpochHash,\n computePrincipalStateHash,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../../data/keying/canonicalJson\";\nimport {\n readContainerKeyEpoch,\n readContainerKeyWrap,\n} from \"../../../data/keyingProjectionVerification/readers\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\n/**\n * Each rematerialized container's acknowledgement names its commit by hash;\n * match every hash against the request this client authored.\n */\nasync function assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): Promise<void> {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const label = \"authored group policy container mutation\";\n const keyEpoch = readContainerKeyEpoch(request.keyEpoch, label);\n const recipientTargets = sortedCanonicalValues(\n request.wraps.map((value) => {\n const wrap = readContainerKeyWrap(value, label);\n return {\n recipientId: wrap.recipientId,\n recipientKeyEpochId: wrap.recipientKeyEpochId,\n recipientKeyFingerprint: wrap.recipientKeyFingerprint,\n recipientKind: wrap.recipientKind,\n };\n }),\n \"authored recipient target\",\n );\n // The request carries this client's own hash of the manifest it signed,\n // and that manifest names its epoch and event by hash. A rotation's signed\n // body commits its keyring hash, so a substituted keyring must refuse\n // here, before journal recovery clears the saved request. A grant that\n // keeps its epoch commits none; the container acknowledgement checks the\n // retained keyring against the epoch's own.\n const committedKeyringHash = Reflect.get(\n Object(request.body),\n \"keyringHash\",\n );\n if (\n response.manifestHead.manifestHash !== request.expectedManifestHash ||\n response.manifestHead.epoch !== Reflect.get(request.manifest, \"epoch\") ||\n response.eventHash !== Reflect.get(request.manifest, \"eventHash\") ||\n response.containerKek.containerKeyEpochId !== keyEpoch.id ||\n response.containerKek.containerKeyEpoch !== keyEpoch.keyEpoch ||\n response.containerKek.keyEpochHash !==\n (await computeContainerKeyEpochHash(keyEpoch)) ||\n (typeof committedKeyringHash === \"string\" &&\n response.containerKek.keyringHash !== committedKeyringHash) ||\n response.containerKek.keyTargetHash !==\n (await computeContainerKekRecipientTargetHash(recipientTargets))\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/**\n * The current an acknowledgement commits, rebuilt from this client's own\n * signed request: the server returns only the head it stored, the insertion\n * time it assigned to the state and payload, and hash-form container\n * acknowledgements. A head other than the one the request commits to refuses.\n * Nothing here manufactures predecessor history or pins.\n */\nexport async function acknowledgedPrincipalPolicyCurrent(input: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): Promise<PrincipalPolicyPageCurrent> {\n const { request, response } = input;\n const { state } = request;\n const stateHash = await computePrincipalStateHash(state);\n if (\n !principalHeadMatchesReference(response.head, {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash,\n keyFingerprint: state.keyFingerprint,\n })\n )\n throw new Error(\"Principal policy acknowledgement names another head\");\n await assertContainerMutationAcknowledgements({\n requests: request.containerMutations ?? [],\n responses: response.containerMutations,\n });\n const { principalType, principalId } = state;\n const { createdAt } = response;\n return {\n currentState: { ...state, stateHash, createdAt },\n currentPayload: {\n principalType,\n principalId,\n stateHash,\n ...request.encryptedPayload,\n createdAt,\n },\n currentProjection: request.projection,\n currentGrants: request.grants,\n currentMemberEnvelopes: {\n principalType,\n principalId,\n stateHash,\n epoch: state.keyEpoch,\n envelopes: request.memberEnvelopes,\n },\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { wrapDekForRecipients } from "../../../internal/crypto/index.js";
2
2
  import { base64ToBytes, bytesToBase64 } from "../../../internal/encoding/index.js";
3
- import { assertPrincipalIdentityCommitments } from "../../../data/principals/principalIdentityCommitments.js";
3
+ import { assertPrincipalIdentityCommitments } from "../../../data/principalContracts/principalIdentityCommitments.js";
4
4
  function toPrincipalMemberEnvelopeRequest(input) {
5
5
  return {
6
6
  userId: input.userId,
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyRecipients.js","sourceRoot":"","sources":["principalPolicyRecipients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAMnE,OAAO,EAAE,kCAAkC,EAAE,MAAM,uDAAuD,CAAC;AAQ3G,SAAS,gCAAgC,CAAC,KAOzC;IACC,OAAO;QACL,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,oBAAoB,EAAE,KAAK,CAAC,QAAQ,CAAC,cAAc;QACnD,aAAa,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,aAAa,CAAC;QAC1D,UAAU,EAAE,aAAa,CAAC,KAAK,CAAC,QAAQ,CAAC,UAAU,CAAC;KACrD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAChC,SAAyD;IAEzD,OAAO,SAAS,CAAC,GAAG,CAAC,CAAC,QAAQ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C,MAAM,CAAC,IAAI,IAAI;KACxE,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;IAClD,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,MAAM,iBAAiB,GAAG,MAAM,oBAAoB,CAClD,KAAK,CAAC,SAAS,EACf,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAChE,CAAC;IAEF,OAAO,iBAAiB,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,EAAE,CAC/C,gCAAgC,CAAC;QAC/B,QAAQ;QACR,MAAM,EAAE,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,IAAI,EAAE;KACxC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { wrapDekForRecipients } from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalMemberEnvelopeRequest,\n PrincipalProjectionMemberRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalMemberEnvelopeResponse } from \"@tearleads/validators/response\";\nimport { assertPrincipalIdentityCommitments } from \"../../../data/principals/principalIdentityCommitments\";\nimport type { TrustedUserIdentity } from \"../../../data/trustedUserIdentity\";\n\ntype PrincipalRekeyRecipient = {\n readonly encapsulationPublicKey: Uint8Array;\n readonly userId: string;\n};\n\nfunction toPrincipalMemberEnvelopeRequest(input: {\n readonly envelope: {\n readonly keyFingerprint: string;\n readonly kemCipherText: Uint8Array;\n readonly wrappedKey: Uint8Array;\n };\n readonly userId: string;\n}): PrincipalMemberEnvelopeRequest {\n return {\n userId: input.userId,\n memberKeyFingerprint: input.envelope.keyFingerprint,\n kemCipherText: bytesToBase64(input.envelope.kemCipherText),\n wrappedKey: bytesToBase64(input.envelope.wrappedKey),\n };\n}\n\nexport function toRecipientEntries(\n envelopes: ReadonlyArray<PrincipalMemberEnvelopeResponse>,\n) {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.memberKeyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\n/** Every projected member is a user, so there is no group recipient branch. */\nfunction toRekeyRecipientEntries(input: {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): PrincipalRekeyRecipient[] {\n const usersById = new Map(input.users.map((user) => [user.userId, user]));\n\n return input.projection.map((member) => {\n const user = usersById.get(member.userId);\n if (!user) {\n throw new Error(`Missing recipient key for user ${member.userId}`);\n }\n\n return {\n encapsulationPublicKey: user.encapsulationPublicKey,\n userId: user.userId,\n };\n });\n}\n\nexport async function rewrapProjectionMemberEnvelopes(input: {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly secretKey: Uint8Array;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): Promise<PrincipalMemberEnvelopeRequest[]> {\n const users = new Map(input.users.map((user) => [user.userId, user]));\n await assertPrincipalIdentityCommitments({\n authenticated: false,\n projections: [input.projection],\n resolveTrustedUserIdentity: async (userId) => users.get(userId) ?? null,\n });\n const recipients = toRekeyRecipientEntries(input);\n if (recipients.length === 0) {\n return [];\n }\n const wrappedRecipients = await wrapDekForRecipients(\n input.secretKey,\n recipients.map((recipient) => recipient.encapsulationPublicKey),\n );\n\n return wrappedRecipients.map((envelope, index) =>\n toPrincipalMemberEnvelopeRequest({\n envelope,\n userId: recipients[index]?.userId ?? \"\",\n }),\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyRecipients.js","sourceRoot":"","sources":["principalPolicyRecipients.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CA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,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAIrD;IACC,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC;IACtE,MAAM,kCAAkC,CAAC;QACvC,aAAa,EAAE,KAAK;QACpB,WAAW,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC;QAC/B,0BAA0B,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,IAAI;KACxE,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,uBAAuB,CAAC,KAAK,CAAC,CAAC;IAClD,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,EAAE,CAAC;IACZ,CAAC;IACD,MAAM,iBAAiB,GAAG,MAAM,oBAAoB,CAClD,KAAK,CAAC,SAAS,EACf,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,SAAS,CAAC,sBAAsB,CAAC,CAChE,CAAC;IAEF,OAAO,iBAAiB,CAAC,GAAG,CAAC,CAAC,QAAQ,EAAE,KAAK,EAAE,EAAE,CAC/C,gCAAgC,CAAC;QAC/B,QAAQ;QACR,MAAM,EAAE,UAAU,CAAC,KAAK,CAAC,EAAE,MAAM,IAAI,EAAE;KACxC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import { wrapDekForRecipients } from \"@tearleads/crypto\";\nimport { base64ToBytes, bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n PrincipalMemberEnvelopeRequest,\n PrincipalProjectionMemberRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalMemberEnvelopeResponse } from \"@tearleads/validators/response\";\nimport { assertPrincipalIdentityCommitments } from \"../../../data/principalContracts/principalIdentityCommitments\";\nimport type { TrustedUserIdentity } from \"../../../data/trustedUserIdentity\";\n\ntype PrincipalRekeyRecipient = {\n readonly encapsulationPublicKey: Uint8Array;\n readonly userId: string;\n};\n\nfunction toPrincipalMemberEnvelopeRequest(input: {\n readonly envelope: {\n readonly keyFingerprint: string;\n readonly kemCipherText: Uint8Array;\n readonly wrappedKey: Uint8Array;\n };\n readonly userId: string;\n}): PrincipalMemberEnvelopeRequest {\n return {\n userId: input.userId,\n memberKeyFingerprint: input.envelope.keyFingerprint,\n kemCipherText: bytesToBase64(input.envelope.kemCipherText),\n wrappedKey: bytesToBase64(input.envelope.wrappedKey),\n };\n}\n\nexport function toRecipientEntries(\n envelopes: ReadonlyArray<PrincipalMemberEnvelopeResponse>,\n) {\n return envelopes.map((envelope) => ({\n keyFingerprint: envelope.memberKeyFingerprint,\n kemCipherText: base64ToBytes(envelope.kemCipherText),\n wrappedKey: base64ToBytes(envelope.wrappedKey),\n }));\n}\n\n/** Every projected member is a user, so there is no group recipient branch. */\nfunction toRekeyRecipientEntries(input: {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): PrincipalRekeyRecipient[] {\n const usersById = new Map(input.users.map((user) => [user.userId, user]));\n\n return input.projection.map((member) => {\n const user = usersById.get(member.userId);\n if (!user) {\n throw new Error(`Missing recipient key for user ${member.userId}`);\n }\n\n return {\n encapsulationPublicKey: user.encapsulationPublicKey,\n userId: user.userId,\n };\n });\n}\n\nexport async function rewrapProjectionMemberEnvelopes(input: {\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly secretKey: Uint8Array;\n readonly users: ReadonlyArray<TrustedUserIdentity>;\n}): Promise<PrincipalMemberEnvelopeRequest[]> {\n const users = new Map(input.users.map((user) => [user.userId, user]));\n await assertPrincipalIdentityCommitments({\n authenticated: false,\n projections: [input.projection],\n resolveTrustedUserIdentity: async (userId) => users.get(userId) ?? null,\n });\n const recipients = toRekeyRecipientEntries(input);\n if (recipients.length === 0) {\n return [];\n }\n const wrappedRecipients = await wrapDekForRecipients(\n input.secretKey,\n recipients.map((recipient) => recipient.encapsulationPublicKey),\n );\n\n return wrappedRecipients.map((envelope, index) =>\n toPrincipalMemberEnvelopeRequest({\n envelope,\n userId: recipients[index]?.userId ?? \"\",\n }),\n );\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { buildPrincipalStateSigningInput, encodeBuiltinGroupMetadata, encryptGroupMetadata, generateKemSeedAndKeyPair, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, readGroupMetadata, signPrincipalState, toFingerprint, wrapDekForRecipients, } from "../../../internal/crypto/index.js";
2
2
  import { bytesToBase64 } from "../../../internal/encoding/index.js";
3
- import { createPrincipalProjectionMember } from "../../../data/principals/principalIdentityCommitments.js";
3
+ import { createPrincipalProjectionMember } from "../../../data/principalContracts/principalIdentityCommitments.js";
4
4
  function projectionToStateMembers(projection) {
5
5
  return projection.map((member) => ({ userId: member.userId }));
6
6
  }
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyRequest.js","sourceRoot":"","sources":["principalPolicyRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAE/B,0BAA0B,EAC1B,oBAAoB,EAEpB,yBAAyB,EACzB,iCAAiC,EACjC,mCAAmC,EAGnC,iBAAiB,EAEjB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAQpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,uDAAuD,CAAC;AAmBxG,SAAS,wBAAwB,CAC/B,UAA2D;IAE3D,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;AACjE,CAAC;AAED;;;;;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AC,CAAC;IAEH,OAAO;QACL,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,kBAAkB,EAAE,aAAa;KAClC,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAQ1D;IACC,OAAO,8BAA8B,CAAC;QACpC,GAAG,KAAK;QACR,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,SAAS;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n type EncapsulationKeyPair,\n encodeBuiltinGroupMetadata,\n encryptGroupMetadata,\n type GroupMetadataKey,\n generateKemSeedAndKeyPair,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type PrincipalContainerGrant,\n type PrincipalPolicyExternalAuthority,\n readGroupMetadata,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n CreateOrganizationGroupRequest,\n PrincipalMemberEnvelopeRequest,\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { createPrincipalProjectionMember } from \"../../../data/principals/principalIdentityCommitments\";\n\ninterface BuildInitialGroupPolicyInput {\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly externalAuthority?:\n | PrincipalPolicyExternalAuthority[\"currentHead\"]\n | null;\n readonly groupId: string;\n readonly grants?: readonly PrincipalContainerGrant[] | undefined;\n readonly includeSignerAsAdmin?: boolean;\n readonly name: string;\n readonly metadataKey?: GroupMetadataKey;\n readonly builtinRole?: \"admins\" | \"members\";\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}\n\nfunction projectionToStateMembers(\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n) {\n return projection.map((member) => ({ userId: member.userId }));\n}\n\n/**\n * Code points that must never appear in a group name: control and format\n * characters (bidi overrides, zero-width joiners, newlines), lone surrogates\n * (re-encoded as U+FFFD when signed, so the signed name would no longer match\n * the one sent to the server), and every other default-ignorable code point\n * (Hangul fillers, variation selectors), which render as nothing and would\n * let one name pass for another. A group name is an identifier here, so this\n * deliberately refuses ZWJ emoji sequences as well. One predicate serves the\n * signing-time and the share-time refusal so the two cannot drift.\n */\nfunction hasForbiddenGroupNameCharacter(name: string): boolean {\n return /[\\p{Cc}\\p{Cf}\\p{Cs}\\p{Default_Ignorable_Code_Point}]/u.test(name);\n}\n\n/**\n * The comparison key for a group display name: width- and compatibility-\n * normalized, stripped of control, format, and default-ignorable characters,\n * whitespace-collapsed, and case-folded. Two names that a user cannot tell\n * apart in a picker must compare equal, or a look-alike name would slip past\n * the share-time binding. Cross-script homoglyphs (Latin \"A\" against Greek\n * \"Α\") are not folded: that needs the UTS #39 confusables table, and both\n * names would still have to be signed groups the organization's own admins\n * created.\n */\nexport function canonicalGroupNameKey(name: string): string {\n return (\n name\n .normalize(\"NFKC\")\n .replace(/[\\p{Cc}\\p{Cf}\\p{Default_Ignorable_Code_Point}]/gu, \"\")\n .replace(/\\s+/gu, \" \")\n .trim()\n .toLocaleLowerCase(\"en-US\")\n // Case folding can leave the string un-normalized (U+0130 lowercases to\n // \"i\" plus a combining dot), so normalize once more after it.\n .normalize(\"NFKC\")\n );\n}\n\ntype GroupPolicyNameInput = Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentPayload\"\n>;\n\nexport type GroupPolicyNameReader = (\n bundle: GroupPolicyNameInput,\n) => Promise<string>;\n\n/** Read only after the policy and its organization-directory binding verify. */\nexport async function readGroupPolicyPayloadName(\n bundle: GroupPolicyNameInput,\n readEncryptedName?: GroupPolicyNameReader,\n): Promise<string> {\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (!readEncryptedName)\n throw new Error(\"Group metadata decryption context is unavailable\");\n return readEncryptedName(bundle);\n}\n\n/** One binding predicate for every operation selected by a read-model label. */\nexport async function groupPolicyNameMismatch(\n bundle: GroupPolicyNameInput,\n expectedGroupName: string,\n readEncryptedName?: GroupPolicyNameReader,\n): Promise<\"forbidden_characters\" | \"name_mismatch\" | null> {\n if (hasForbiddenGroupNameCharacter(expectedGroupName)) {\n return \"forbidden_characters\";\n }\n const signedName = await readGroupPolicyPayloadName(\n bundle,\n readEncryptedName,\n );\n if (hasForbiddenGroupNameCharacter(signedName)) return \"forbidden_characters\";\n return canonicalGroupNameKey(signedName) ===\n canonicalGroupNameKey(expectedGroupName)\n ? null\n : \"name_mismatch\";\n}\n\nexport async function signedGroupPolicyRequest(input: {\n readonly currentPolicy?: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly encapsulationPublicKey: string;\n readonly externalAuthority:\n | PrincipalPolicyExternalAuthority[\"currentHead\"]\n | null;\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly grants: ReadonlyArray<PrincipalContainerGrant>;\n readonly memberEnvelopes: ReadonlyArray<PrincipalMemberEnvelopeRequest>;\n readonly payloadCiphertext: string;\n readonly principalId: string;\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly signedAt: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.projection);\n const grants = normalizePrincipalContainerGrants(input.grants);\n const payloadCiphertext = input.payloadCiphertext;\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"group\",\n principalId: input.principalId,\n version: input.currentPolicy\n ? input.currentPolicy.currentState.version + 1\n : 1,\n prevStateHash: input.currentPolicy?.currentState.stateHash ?? null,\n keyEpoch: input.keyEpoch,\n encapsulationPublicKey: input.encapsulationPublicKey,\n keyFingerprint: input.keyFingerprint,\n members: projectionToStateMembers(projection),\n memberEnvelopes: [...input.memberEnvelopes],\n projection,\n grants,\n payloadCiphertext,\n externalAuthority: input.externalAuthority,\n signedAt: input.signedAt,\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants,\n memberEnvelopes: [...input.memberEnvelopes],\n };\n}\n\nexport async function buildInitialGroupPolicyRequest(\n input: BuildInitialGroupPolicyInput,\n): Promise<CreateOrganizationGroupRequest> {\n const groupKem = generateKemSeedAndKeyPair();\n const withSigner = input.includeSignerAsAdmin ?? true;\n const projection = withSigner\n ? [\n await createPrincipalProjectionMember(\n {\n userId: input.signerUserId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.creatorEncapsulationKeyPair.publicKey,\n },\n \"admin\",\n ),\n ]\n : [];\n const memberEnvelopes: PrincipalMemberEnvelopeRequest[] = [];\n\n if (withSigner) {\n const creatorFingerprint = await toFingerprint(\n input.creatorEncapsulationKeyPair.publicKey,\n );\n const [creatorEnvelope] = await wrapDekForRecipients(groupKem.secretKey, [\n input.creatorEncapsulationKeyPair.publicKey,\n ]);\n\n if (!creatorEnvelope) {\n throw new Error(\"Failed to wrap group key for creator\");\n }\n\n memberEnvelopes.push({\n userId: input.signerUserId,\n memberKeyFingerprint: creatorFingerprint,\n kemCipherText: bytesToBase64(creatorEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(creatorEnvelope.wrappedKey),\n });\n }\n const name = input.name.trim();\n // A name is compared by canonical key but displayed raw, so an invisible\n // code point would let one signed name render as another. Refuse them\n // where the name is signed.\n if (name.length === 0 || hasForbiddenGroupNameCharacter(name)) {\n throw new Error(\n \"Group names must be non-empty and contain no control, format, or surrogate characters\",\n );\n }\n const payloadCiphertext = input.builtinRole\n ? encodeBuiltinGroupMetadata(input.builtinRole)\n : input.metadataKey\n ? await encryptGroupMetadata({\n key: input.metadataKey,\n groupId: input.groupId,\n name,\n })\n : (() => {\n throw new Error(\"Group metadata encryption context is unavailable\");\n })();\n const policyRequest = await signedGroupPolicyRequest({\n encapsulationPublicKey: bytesToBase64(groupKem.publicKey),\n externalAuthority: input.externalAuthority ?? null,\n keyEpoch: 1,\n keyFingerprint: await toFingerprint(groupKem.publicKey),\n grants: input.grants ?? [],\n memberEnvelopes,\n payloadCiphertext,\n principalId: input.groupId,\n projection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n\n return {\n groupId: input.groupId,\n initialGroupPolicy: policyRequest,\n };\n}\n\n/**\n * Members at bootstrap holds the registering user alone.\n *\n * It used to also contain the Admins group as a nested member, so that admins\n * were implicitly members. Principals contain only users now, so an admin is an\n * ordinary Members entry — and bootstrap has exactly one user, who is that\n * admin.\n */\nexport async function buildInitialMemberGroupPolicyRequest(input: {\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly groupId: string;\n readonly grants?: readonly PrincipalContainerGrant[] | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<CreateOrganizationGroupRequest> {\n return buildInitialGroupPolicyRequest({\n ...input,\n name: \"Members\",\n builtinRole: \"members\",\n });\n}\n"]}
1
+ {"version":3,"file":"principalPolicyRequest.js","sourceRoot":"","sources":["principalPolicyRequest.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,+BAA+B,EAE/B,0BAA0B,EAC1B,oBAAoB,EAEpB,yBAAyB,EACzB,iCAAiC,EACjC,mCAAmC,EAGnC,iBAAiB,EAEjB,kBAAkB,EAClB,aAAa,EACb,oBAAoB,GACrB,MAAM,mB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AS,CAAC;QACvD,MAAM,EAAE,KAAK,CAAC,MAAM,IAAI,EAAE;QAC1B,eAAe;QACf,iBAAiB;QACjB,WAAW,EAAE,KAAK,CAAC,OAAO;QAC1B,UAAU;QACV,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;QAClC,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IAEH,OAAO;QACL,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,kBAAkB,EAAE,aAAa;KAClC,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,oCAAoC,CAAC,KAQ1D;IACC,OAAO,8BAA8B,CAAC;QACpC,GAAG,KAAK;QACR,IAAI,EAAE,SAAS;QACf,WAAW,EAAE,SAAS;KACvB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n buildPrincipalStateSigningInput,\n type EncapsulationKeyPair,\n encodeBuiltinGroupMetadata,\n encryptGroupMetadata,\n type GroupMetadataKey,\n generateKemSeedAndKeyPair,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type PrincipalContainerGrant,\n type PrincipalPolicyExternalAuthority,\n readGroupMetadata,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n CreateOrganizationGroupRequest,\n PrincipalMemberEnvelopeRequest,\n PrincipalProjectionMemberRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { createPrincipalProjectionMember } from \"../../../data/principalContracts/principalIdentityCommitments\";\n\ninterface BuildInitialGroupPolicyInput {\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly externalAuthority?:\n | PrincipalPolicyExternalAuthority[\"currentHead\"]\n | null;\n readonly groupId: string;\n readonly grants?: readonly PrincipalContainerGrant[] | undefined;\n readonly includeSignerAsAdmin?: boolean;\n readonly name: string;\n readonly metadataKey?: GroupMetadataKey;\n readonly builtinRole?: \"admins\" | \"members\";\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}\n\nfunction projectionToStateMembers(\n projection: ReadonlyArray<PrincipalProjectionMemberRequest>,\n) {\n return projection.map((member) => ({ userId: member.userId }));\n}\n\n/**\n * Code points that must never appear in a group name: control and format\n * characters (bidi overrides, zero-width joiners, newlines), lone surrogates\n * (re-encoded as U+FFFD when signed, so the signed name would no longer match\n * the one sent to the server), and every other default-ignorable code point\n * (Hangul fillers, variation selectors), which render as nothing and would\n * let one name pass for another. A group name is an identifier here, so this\n * deliberately refuses ZWJ emoji sequences as well. One predicate serves the\n * signing-time and the share-time refusal so the two cannot drift.\n */\nfunction hasForbiddenGroupNameCharacter(name: string): boolean {\n return /[\\p{Cc}\\p{Cf}\\p{Cs}\\p{Default_Ignorable_Code_Point}]/u.test(name);\n}\n\n/**\n * The comparison key for a group display name: width- and compatibility-\n * normalized, stripped of control, format, and default-ignorable characters,\n * whitespace-collapsed, and case-folded. Two names that a user cannot tell\n * apart in a picker must compare equal, or a look-alike name would slip past\n * the share-time binding. Cross-script homoglyphs (Latin \"A\" against Greek\n * \"Α\") are not folded: that needs the UTS #39 confusables table, and both\n * names would still have to be signed groups the organization's own admins\n * created.\n */\nexport function canonicalGroupNameKey(name: string): string {\n return (\n name\n .normalize(\"NFKC\")\n .replace(/[\\p{Cc}\\p{Cf}\\p{Default_Ignorable_Code_Point}]/gu, \"\")\n .replace(/\\s+/gu, \" \")\n .trim()\n .toLocaleLowerCase(\"en-US\")\n // Case folding can leave the string un-normalized (U+0130 lowercases to\n // \"i\" plus a combining dot), so normalize once more after it.\n .normalize(\"NFKC\")\n );\n}\n\ntype GroupPolicyNameInput = Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentPayload\"\n>;\n\nexport type GroupPolicyNameReader = (\n bundle: GroupPolicyNameInput,\n) => Promise<string>;\n\n/** Read only after the policy and its organization-directory binding verify. */\nexport async function readGroupPolicyPayloadName(\n bundle: GroupPolicyNameInput,\n readEncryptedName?: GroupPolicyNameReader,\n): Promise<string> {\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n if (\"role\" in metadata)\n return metadata.role === \"admins\" ? \"Admins\" : \"Members\";\n if (!readEncryptedName)\n throw new Error(\"Group metadata decryption context is unavailable\");\n return readEncryptedName(bundle);\n}\n\n/** One binding predicate for every operation selected by a read-model label. */\nexport async function groupPolicyNameMismatch(\n bundle: GroupPolicyNameInput,\n expectedGroupName: string,\n readEncryptedName?: GroupPolicyNameReader,\n): Promise<\"forbidden_characters\" | \"name_mismatch\" | null> {\n if (hasForbiddenGroupNameCharacter(expectedGroupName)) {\n return \"forbidden_characters\";\n }\n const signedName = await readGroupPolicyPayloadName(\n bundle,\n readEncryptedName,\n );\n if (hasForbiddenGroupNameCharacter(signedName)) return \"forbidden_characters\";\n return canonicalGroupNameKey(signedName) ===\n canonicalGroupNameKey(expectedGroupName)\n ? null\n : \"name_mismatch\";\n}\n\nexport async function signedGroupPolicyRequest(input: {\n readonly currentPolicy?: Pick<PrincipalPolicyBundleResponse, \"currentState\">;\n readonly encapsulationPublicKey: string;\n readonly externalAuthority:\n | PrincipalPolicyExternalAuthority[\"currentHead\"]\n | null;\n readonly keyEpoch: number;\n readonly keyFingerprint: string;\n readonly grants: ReadonlyArray<PrincipalContainerGrant>;\n readonly memberEnvelopes: ReadonlyArray<PrincipalMemberEnvelopeRequest>;\n readonly payloadCiphertext: string;\n readonly principalId: string;\n readonly projection: ReadonlyArray<PrincipalProjectionMemberRequest>;\n readonly signedAt: string;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PutPrincipalPolicyRequest> {\n const projection = normalizePrincipalProjectionMembers(input.projection);\n const grants = normalizePrincipalContainerGrants(input.grants);\n const payloadCiphertext = input.payloadCiphertext;\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"group\",\n principalId: input.principalId,\n version: input.currentPolicy\n ? input.currentPolicy.currentState.version + 1\n : 1,\n prevStateHash: input.currentPolicy?.currentState.stateHash ?? null,\n keyEpoch: input.keyEpoch,\n encapsulationPublicKey: input.encapsulationPublicKey,\n keyFingerprint: input.keyFingerprint,\n members: projectionToStateMembers(projection),\n memberEnvelopes: [...input.memberEnvelopes],\n projection,\n grants,\n payloadCiphertext,\n externalAuthority: input.externalAuthority,\n signedAt: input.signedAt,\n signerUserId: input.signerUserId,\n signerUserKeyFingerprint: input.signingFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants,\n memberEnvelopes: [...input.memberEnvelopes],\n };\n}\n\nexport async function buildInitialGroupPolicyRequest(\n input: BuildInitialGroupPolicyInput,\n): Promise<CreateOrganizationGroupRequest> {\n const groupKem = generateKemSeedAndKeyPair();\n const withSigner = input.includeSignerAsAdmin ?? true;\n const projection = withSigner\n ? [\n await createPrincipalProjectionMember(\n {\n userId: input.signerUserId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.creatorEncapsulationKeyPair.publicKey,\n },\n \"admin\",\n ),\n ]\n : [];\n const memberEnvelopes: PrincipalMemberEnvelopeRequest[] = [];\n\n if (withSigner) {\n const creatorFingerprint = await toFingerprint(\n input.creatorEncapsulationKeyPair.publicKey,\n );\n const [creatorEnvelope] = await wrapDekForRecipients(groupKem.secretKey, [\n input.creatorEncapsulationKeyPair.publicKey,\n ]);\n\n if (!creatorEnvelope) {\n throw new Error(\"Failed to wrap group key for creator\");\n }\n\n memberEnvelopes.push({\n userId: input.signerUserId,\n memberKeyFingerprint: creatorFingerprint,\n kemCipherText: bytesToBase64(creatorEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(creatorEnvelope.wrappedKey),\n });\n }\n const name = input.name.trim();\n // A name is compared by canonical key but displayed raw, so an invisible\n // code point would let one signed name render as another. Refuse them\n // where the name is signed.\n if (name.length === 0 || hasForbiddenGroupNameCharacter(name)) {\n throw new Error(\n \"Group names must be non-empty and contain no control, format, or surrogate characters\",\n );\n }\n const payloadCiphertext = input.builtinRole\n ? encodeBuiltinGroupMetadata(input.builtinRole)\n : input.metadataKey\n ? await encryptGroupMetadata({\n key: input.metadataKey,\n groupId: input.groupId,\n name,\n })\n : (() => {\n throw new Error(\"Group metadata encryption context is unavailable\");\n })();\n const policyRequest = await signedGroupPolicyRequest({\n encapsulationPublicKey: bytesToBase64(groupKem.publicKey),\n externalAuthority: input.externalAuthority ?? null,\n keyEpoch: 1,\n keyFingerprint: await toFingerprint(groupKem.publicKey),\n grants: input.grants ?? [],\n memberEnvelopes,\n payloadCiphertext,\n principalId: input.groupId,\n projection,\n signedAt: new Date().toISOString(),\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n\n return {\n groupId: input.groupId,\n initialGroupPolicy: policyRequest,\n };\n}\n\n/**\n * Members at bootstrap holds the registering user alone.\n *\n * It used to also contain the Admins group as a nested member, so that admins\n * were implicitly members. Principals contain only users now, so an admin is an\n * ordinary Members entry — and bootstrap has exactly one user, who is that\n * admin.\n */\nexport async function buildInitialMemberGroupPolicyRequest(input: {\n readonly identityTrustDomain: string;\n readonly creatorEncapsulationKeyPair: EncapsulationKeyPair;\n readonly groupId: string;\n readonly grants?: readonly PrincipalContainerGrant[] | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<CreateOrganizationGroupRequest> {\n return buildInitialGroupPolicyRequest({\n ...input,\n name: \"Members\",\n builtinRole: \"members\",\n });\n}\n"]}