@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,5 +1,5 @@
1
1
  import { type OrganizationLeaveRequestResult, type OrganizationMembership, type OrganizationSyncPauseResult } from "../../workflows/organizations/index.js";
2
- import { type DomainScope } from "../../workflows/sync/index.js";
2
+ import { type DomainScope } from "../../workflows/sync/coordination.js";
3
3
  import { type ContainerContents } from "../containerContents/index.js";
4
4
  import type { InternalRuntime } from "../runtime/workflowRuntime.js";
5
5
  /** The user's own conduit to the organizations they belong to. */
@@ -1,6 +1,6 @@
1
1
  import { refreshOrganizationMemberships, setOrganizationLeaveRequested, setOrganizationSyncPaused, } from "../../workflows/organizations/index.js";
2
2
  import { loadCurrentMembersHead } from "../../workflows/organizations/memberships/leaveRequestMembersEvidence.js";
3
- import { getOrCreateOrganizationSyncPauses, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../workflows/sync/index.js";
3
+ import { getOrCreateOrganizationSyncPauses, hasDomainSyncCoordinatorPendingWork, requestAllDomainSyncLanes, subscribeToDomainSyncCoordinator, waitForDomainSyncCoordinatorToSettle, } from "../../workflows/sync/coordination.js";
4
4
  import { carriesLocalWrites, } from "../containerContents/index.js";
5
5
  // Long enough for a typical upload burst, short enough to answer a tap.
6
6
  const PAUSE_FLUSH_TIMEOUT_MS = 10_000;
@@ -1 +1 @@
1
- {"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,8BAA8B,EAC9B,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sBAAsB,EAAE,MAAM,uEAAuE,CAAC;AAC/G,OAAO,EAEL,iCAAiC,EACjC,mCAAmC,EACnC,yBAAyB,EACzB,gCAAgC,EAChC,oCAAoC,GACrC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAEL,kBAAkB,GACnB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ACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type OrganizationContentHost,\n type OrganizationLeaveRequestResult,\n type OrganizationMembership,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationLeaveRequested,\n setOrganizationSyncPaused,\n} from \"../../workflows/organizations\";\nimport { loadCurrentMembersHead } from \"../../workflows/organizations/memberships/leaveRequestMembersEvidence\";\nimport {\n type DomainScope,\n getOrCreateOrganizationSyncPauses,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../workflows/sync\";\nimport {\n type ContainerContents,\n carriesLocalWrites,\n} from \"../containerContents\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\n\n// Long enough for a typical upload burst, short enough to answer a tap.\nconst PAUSE_FLUSH_TIMEOUT_MS = 10_000;\n\n/** The user's own conduit to the organizations they belong to. */\nexport interface OrganizationMemberships {\n /**\n * Reads the user's memberships and applies their pause choices on this\n * device. Null when offline or the list could not be read.\n */\n refresh(): Promise<OrganizationMembership[] | null>;\n /** Pauses or resumes one organization for all of the user's devices. */\n setSyncPaused(\n organizationId: string,\n paused: boolean,\n ): Promise<OrganizationSyncPauseResult>;\n /**\n * Asks the organization's administrators to remove the user, or withdraws\n * that request. Signed with the user's identity key; an administrator still\n * has to approve it.\n */\n setLeaveRequested(\n organizationId: string,\n requested: boolean,\n ): Promise<OrganizationLeaveRequestResult>;\n /** The organizations paused on this device, read from local storage. */\n loadPausedOrganizationIds(): Promise<ReadonlySet<string>>;\n /** Notifies when the paused set for the current scope changes. */\n subscribeToSyncPauses(listener: () => void): () => void;\n /**\n * Hands each membership list a refresh reads for the current scope, so a\n * choice made on another device reaches every view of it.\n */\n subscribeToMemberships(\n listener: (memberships: readonly OrganizationMembership[]) => void,\n ): () => void;\n}\n\ntype MembershipsListener = (\n memberships: readonly OrganizationMembership[],\n) => void;\n\nconst membershipListenersByScope = new WeakMap<\n DomainScope,\n Set<MembershipsListener>\n>();\n\n/**\n * The scope's document reconciler. Containers it reconciled before a pause\n * stay marked as listed, so a resume has to forget that before reconciling.\n */\nexport interface OrganizationContentReconciler {\n resetDiscovered(): void;\n reconcileNow(options: { readonly freshListing: true }): Promise<void>;\n}\n\ninterface SettleRetry {\n retry: () => Promise<boolean>;\n running: boolean;\n unsubscribe: () => void;\n}\n\nconst settleRetriesByScope = new WeakMap<DomainScope, SettleRetry>();\n\n// One retry per scope: it runs whenever the scope's sync lanes go idle and\n// stops once it reports the work done.\nexport function retryWhenWritesSettle(\n domainScope: DomainScope,\n retry: () => Promise<boolean>,\n): void {\n const existing = settleRetriesByScope.get(domainScope);\n if (existing) {\n existing.retry = retry;\n return;\n }\n const entry: SettleRetry = { retry, running: false, unsubscribe: () => {} };\n settleRetriesByScope.set(domainScope, entry);\n const attempt = () => {\n if (entry.running || hasDomainSyncCoordinatorPendingWork(domainScope)) {\n return;\n }\n entry.running = true;\n void entry\n .retry()\n .then(\n (done) => {\n if (!done) return;\n entry.unsubscribe();\n settleRetriesByScope.delete(domainScope);\n },\n () => undefined,\n )\n .finally(() => {\n entry.running = false;\n });\n };\n entry.unsubscribe = subscribeToDomainSyncCoordinator(domainScope, attempt);\n // The lanes may already have gone idle before the subscription existed.\n attempt();\n}\n\n// Bound to the scope the operation started in: the tree is opened once, and\n// every action re-checks the scope so stale work never reaches another\n// identity's device state.\nfunction createOrganizationContentHost(\n runtime: InternalWorkflowRuntimeInput,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n isCurrent: () => boolean,\n): OrganizationContentHost {\n const { domainScope } = runtime.state;\n const tree = containerContents.openTree();\n return {\n async forgetOrganizationContent(organizationId) {\n // A scope that ended has nothing left to retry.\n if (!isCurrent()) return true;\n return tree.forgetOrganizationContent(organizationId);\n },\n async hasUnsyncedOrganizationWrites(organizationId) {\n if (!isCurrent()) return true;\n const pending = await containerContents\n .documentQueries()\n .listPendingWrites();\n return pending.some(\n (item) =>\n item.organizationId === organizationId && carriesLocalWrites(item),\n );\n },\n async flushWrites() {\n requestAllDomainSyncLanes(domainScope);\n await waitForDomainSyncCoordinatorToSettle(domainScope, {\n timeoutMs: PAUSE_FLUSH_TIMEOUT_MS,\n });\n },\n async refetchContent() {\n if (!isCurrent()) return;\n // Re-lists the whole tree and every container's documents. The resumed\n // organization's folders were listed before the pause, and a hydration\n // may already have restored them, so they must be forgotten explicitly.\n // A sweep that started listing while paused would miss them, so this\n // one queues behind it rather than joining it.\n const reconciler = openReconciler();\n reconciler.resetDiscovered();\n await reconciler.reconcileNow({ freshListing: true });\n },\n retryWhenWritesSettle: (retry) => retryWhenWritesSettle(domainScope, retry),\n };\n}\n\nfunction canReachServer(runtime: InternalWorkflowRuntimeInput): boolean {\n return (\n runtime.infra.dbStatus === \"ready\" &&\n runtime.auth.isAuthenticated &&\n runtime.state.online\n );\n}\n\nfunction setLeaveRequestedFor(\n runtimeService: InternalRuntime,\n organizationId: string,\n requested: boolean,\n): Promise<OrganizationLeaveRequestResult> {\n const runtime = runtimeService.workflowInput();\n const { userId } = runtime.auth;\n const { signingKeyPair } = runtime.crypto;\n if (!canReachServer(runtime) || !userId || !signingKeyPair) {\n return Promise.resolve({\n httpStatus: null,\n message: \"Connect to ask to leave an organization.\",\n status: \"failed\",\n });\n }\n const { domainScope } = runtime.state;\n return setOrganizationLeaveRequested({\n apiClient: runtime.apiClient,\n loadMembersHead: () =>\n loadCurrentMembersHead({\n organizationId,\n runtime,\n stillCurrent: () =>\n runtimeService.workflowInput().state.domainScope === domainScope,\n }),\n organizationId,\n requested,\n signer: { signingKeyPair, userId },\n });\n}\n\nexport function createOrganizationMemberships(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n): OrganizationMemberships {\n const membershipInput = (runtime: InternalWorkflowRuntimeInput) => {\n const { domainScope } = runtime.state;\n const isCurrent = () =>\n runtimeService.workflowInput().state.domainScope === domainScope;\n return {\n apiClient: runtime.apiClient,\n domainScope,\n execSql: runtime.infra.execSql,\n host: createOrganizationContentHost(\n runtime,\n containerContents,\n openReconciler,\n isCurrent,\n ),\n isCurrent,\n };\n };\n return {\n async refresh() {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) return null;\n const memberships = await refreshOrganizationMemberships(\n membershipInput(runtime),\n );\n const listeners = membershipListenersByScope.get(\n runtime.state.domainScope,\n );\n if (memberships && listeners) {\n for (const listener of [...listeners]) listener(memberships);\n }\n return memberships;\n },\n async setSyncPaused(organizationId, paused) {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) {\n return {\n httpStatus: null,\n message: \"Connect to change sync for an organization.\",\n status: \"failed\",\n };\n }\n return setOrganizationSyncPaused({\n ...membershipInput(runtime),\n organizationId,\n paused,\n });\n },\n setLeaveRequested: (organizationId, requested) =>\n setLeaveRequestedFor(runtimeService, organizationId, requested),\n async loadPausedOrganizationIds() {\n const runtime = runtimeService.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") return new Set<string>();\n const pauses = getOrCreateOrganizationSyncPauses(\n runtime.state.domainScope,\n );\n await pauses.load(runtime.infra.execSql);\n return pauses.pausedOrganizationIds();\n },\n subscribeToSyncPauses(listener) {\n return getOrCreateOrganizationSyncPauses(\n runtimeService.workflowInput().state.domainScope,\n ).subscribe(listener);\n },\n subscribeToMemberships(listener) {\n const { domainScope } = runtimeService.workflowInput().state;\n const listeners =\n membershipListenersByScope.get(domainScope) ?? new Set();\n membershipListenersByScope.set(domainScope, listeners);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"]}
1
+ {"version":3,"file":"organizationMemberships.js","sourceRoot":"","sources":["organizationMemberships.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,8BAA8B,EAC9B,6BAA6B,EAC7B,yBAAyB,GAC1B,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,sBAAsB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AAW,EAAE,SAAS,CAAC,CAAC;YACvD,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YACxB,OAAO,GAAG,EAAE;gBACV,SAAS,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;YAC7B,CAAC,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n type OrganizationContentHost,\n type OrganizationLeaveRequestResult,\n type OrganizationMembership,\n type OrganizationSyncPauseResult,\n refreshOrganizationMemberships,\n setOrganizationLeaveRequested,\n setOrganizationSyncPaused,\n} from \"../../workflows/organizations\";\nimport { loadCurrentMembersHead } from \"../../workflows/organizations/memberships/leaveRequestMembersEvidence\";\nimport {\n type DomainScope,\n getOrCreateOrganizationSyncPauses,\n hasDomainSyncCoordinatorPendingWork,\n requestAllDomainSyncLanes,\n subscribeToDomainSyncCoordinator,\n waitForDomainSyncCoordinatorToSettle,\n} from \"../../workflows/sync/coordination\";\nimport {\n type ContainerContents,\n carriesLocalWrites,\n} from \"../containerContents\";\nimport type {\n InternalRuntime,\n InternalWorkflowRuntimeInput,\n} from \"../runtime/workflowRuntime\";\n\n// Long enough for a typical upload burst, short enough to answer a tap.\nconst PAUSE_FLUSH_TIMEOUT_MS = 10_000;\n\n/** The user's own conduit to the organizations they belong to. */\nexport interface OrganizationMemberships {\n /**\n * Reads the user's memberships and applies their pause choices on this\n * device. Null when offline or the list could not be read.\n */\n refresh(): Promise<OrganizationMembership[] | null>;\n /** Pauses or resumes one organization for all of the user's devices. */\n setSyncPaused(\n organizationId: string,\n paused: boolean,\n ): Promise<OrganizationSyncPauseResult>;\n /**\n * Asks the organization's administrators to remove the user, or withdraws\n * that request. Signed with the user's identity key; an administrator still\n * has to approve it.\n */\n setLeaveRequested(\n organizationId: string,\n requested: boolean,\n ): Promise<OrganizationLeaveRequestResult>;\n /** The organizations paused on this device, read from local storage. */\n loadPausedOrganizationIds(): Promise<ReadonlySet<string>>;\n /** Notifies when the paused set for the current scope changes. */\n subscribeToSyncPauses(listener: () => void): () => void;\n /**\n * Hands each membership list a refresh reads for the current scope, so a\n * choice made on another device reaches every view of it.\n */\n subscribeToMemberships(\n listener: (memberships: readonly OrganizationMembership[]) => void,\n ): () => void;\n}\n\ntype MembershipsListener = (\n memberships: readonly OrganizationMembership[],\n) => void;\n\nconst membershipListenersByScope = new WeakMap<\n DomainScope,\n Set<MembershipsListener>\n>();\n\n/**\n * The scope's document reconciler. Containers it reconciled before a pause\n * stay marked as listed, so a resume has to forget that before reconciling.\n */\nexport interface OrganizationContentReconciler {\n resetDiscovered(): void;\n reconcileNow(options: { readonly freshListing: true }): Promise<void>;\n}\n\ninterface SettleRetry {\n retry: () => Promise<boolean>;\n running: boolean;\n unsubscribe: () => void;\n}\n\nconst settleRetriesByScope = new WeakMap<DomainScope, SettleRetry>();\n\n// One retry per scope: it runs whenever the scope's sync lanes go idle and\n// stops once it reports the work done.\nexport function retryWhenWritesSettle(\n domainScope: DomainScope,\n retry: () => Promise<boolean>,\n): void {\n const existing = settleRetriesByScope.get(domainScope);\n if (existing) {\n existing.retry = retry;\n return;\n }\n const entry: SettleRetry = { retry, running: false, unsubscribe: () => {} };\n settleRetriesByScope.set(domainScope, entry);\n const attempt = () => {\n if (entry.running || hasDomainSyncCoordinatorPendingWork(domainScope)) {\n return;\n }\n entry.running = true;\n void entry\n .retry()\n .then(\n (done) => {\n if (!done) return;\n entry.unsubscribe();\n settleRetriesByScope.delete(domainScope);\n },\n () => undefined,\n )\n .finally(() => {\n entry.running = false;\n });\n };\n entry.unsubscribe = subscribeToDomainSyncCoordinator(domainScope, attempt);\n // The lanes may already have gone idle before the subscription existed.\n attempt();\n}\n\n// Bound to the scope the operation started in: the tree is opened once, and\n// every action re-checks the scope so stale work never reaches another\n// identity's device state.\nfunction createOrganizationContentHost(\n runtime: InternalWorkflowRuntimeInput,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n isCurrent: () => boolean,\n): OrganizationContentHost {\n const { domainScope } = runtime.state;\n const tree = containerContents.openTree();\n return {\n async forgetOrganizationContent(organizationId) {\n // A scope that ended has nothing left to retry.\n if (!isCurrent()) return true;\n return tree.forgetOrganizationContent(organizationId);\n },\n async hasUnsyncedOrganizationWrites(organizationId) {\n if (!isCurrent()) return true;\n const pending = await containerContents\n .documentQueries()\n .listPendingWrites();\n return pending.some(\n (item) =>\n item.organizationId === organizationId && carriesLocalWrites(item),\n );\n },\n async flushWrites() {\n requestAllDomainSyncLanes(domainScope);\n await waitForDomainSyncCoordinatorToSettle(domainScope, {\n timeoutMs: PAUSE_FLUSH_TIMEOUT_MS,\n });\n },\n async refetchContent() {\n if (!isCurrent()) return;\n // Re-lists the whole tree and every container's documents. The resumed\n // organization's folders were listed before the pause, and a hydration\n // may already have restored them, so they must be forgotten explicitly.\n // A sweep that started listing while paused would miss them, so this\n // one queues behind it rather than joining it.\n const reconciler = openReconciler();\n reconciler.resetDiscovered();\n await reconciler.reconcileNow({ freshListing: true });\n },\n retryWhenWritesSettle: (retry) => retryWhenWritesSettle(domainScope, retry),\n };\n}\n\nfunction canReachServer(runtime: InternalWorkflowRuntimeInput): boolean {\n return (\n runtime.infra.dbStatus === \"ready\" &&\n runtime.auth.isAuthenticated &&\n runtime.state.online\n );\n}\n\nfunction setLeaveRequestedFor(\n runtimeService: InternalRuntime,\n organizationId: string,\n requested: boolean,\n): Promise<OrganizationLeaveRequestResult> {\n const runtime = runtimeService.workflowInput();\n const { userId } = runtime.auth;\n const { signingKeyPair } = runtime.crypto;\n if (!canReachServer(runtime) || !userId || !signingKeyPair) {\n return Promise.resolve({\n httpStatus: null,\n message: \"Connect to ask to leave an organization.\",\n status: \"failed\",\n });\n }\n const { domainScope } = runtime.state;\n return setOrganizationLeaveRequested({\n apiClient: runtime.apiClient,\n loadMembersHead: () =>\n loadCurrentMembersHead({\n organizationId,\n runtime,\n stillCurrent: () =>\n runtimeService.workflowInput().state.domainScope === domainScope,\n }),\n organizationId,\n requested,\n signer: { signingKeyPair, userId },\n });\n}\n\nexport function createOrganizationMemberships(\n runtimeService: InternalRuntime,\n containerContents: ContainerContents,\n openReconciler: () => OrganizationContentReconciler,\n): OrganizationMemberships {\n const membershipInput = (runtime: InternalWorkflowRuntimeInput) => {\n const { domainScope } = runtime.state;\n const isCurrent = () =>\n runtimeService.workflowInput().state.domainScope === domainScope;\n return {\n apiClient: runtime.apiClient,\n domainScope,\n execSql: runtime.infra.execSql,\n host: createOrganizationContentHost(\n runtime,\n containerContents,\n openReconciler,\n isCurrent,\n ),\n isCurrent,\n };\n };\n return {\n async refresh() {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) return null;\n const memberships = await refreshOrganizationMemberships(\n membershipInput(runtime),\n );\n const listeners = membershipListenersByScope.get(\n runtime.state.domainScope,\n );\n if (memberships && listeners) {\n for (const listener of [...listeners]) listener(memberships);\n }\n return memberships;\n },\n async setSyncPaused(organizationId, paused) {\n const runtime = runtimeService.workflowInput();\n if (!canReachServer(runtime)) {\n return {\n httpStatus: null,\n message: \"Connect to change sync for an organization.\",\n status: \"failed\",\n };\n }\n return setOrganizationSyncPaused({\n ...membershipInput(runtime),\n organizationId,\n paused,\n });\n },\n setLeaveRequested: (organizationId, requested) =>\n setLeaveRequestedFor(runtimeService, organizationId, requested),\n async loadPausedOrganizationIds() {\n const runtime = runtimeService.workflowInput();\n if (runtime.infra.dbStatus !== \"ready\") return new Set<string>();\n const pauses = getOrCreateOrganizationSyncPauses(\n runtime.state.domainScope,\n );\n await pauses.load(runtime.infra.execSql);\n return pauses.pausedOrganizationIds();\n },\n subscribeToSyncPauses(listener) {\n return getOrCreateOrganizationSyncPauses(\n runtimeService.workflowInput().state.domainScope,\n ).subscribe(listener);\n },\n subscribeToMemberships(listener) {\n const { domainScope } = runtimeService.workflowInput().state;\n const listeners =\n membershipListenersByScope.get(domainScope) ?? new Set();\n membershipListenersByScope.set(domainScope, listeners);\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n"]}
@@ -1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AAK,CAAC,kBAAkB;QAC5C,0BAA0B,EAAE,KAAK,CAAC,OAAO,CAAC,0BAA0B;QACpE,eAAe;QACf,+BAA+B,EAC7B,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,YAAY,EAAE;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { CurrentPolicyReferenceResolver } from \"../../data/principals/currentPolicyReferenceResolver\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../data/principals/principalPolicyEvidence\";\nimport {\n type PreparedPrincipalContainerRematerializationBatch,\n type PrincipalRematerializationPredecessor,\n preparePrincipalContainerRematerializationBatch,\n} from \"../../workflows/containers/rematerialization\";\nimport { resolveDocumentCreateAuthor } from \"../../workflows/documents\";\n\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\n\nexport async function preparePrincipalContainerMutations(input: {\n readonly preceding?: PrincipalRematerializationPredecessor | undefined;\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentGrants\">;\n readonly groupId: string;\n readonly nextPolicy: PrincipalPolicyCurrentEvidence;\n readonly resolveAuthoredPolicyReferences?:\n | CurrentPolicyReferenceResolver\n | undefined;\n readonly organizationId: string;\n readonly revokedContainerId?: string | undefined;\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly stillCurrent: () => boolean;\n readonly recitationStillCurrent?: (() => boolean) | undefined;\n}): Promise<PreparedPrincipalContainerRematerializationBatch> {\n const author = resolveDocumentCreateAuthor(input.runtime);\n const targetSecretKey = input.runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !targetSecretKey) {\n throw new Error(\n \"Organization container rematerialization context is unavailable\",\n );\n }\n return preparePrincipalContainerRematerializationBatch({\n preceding: input.preceding,\n stillCurrent: input.stillCurrent,\n recitationStillCurrent: input.recitationStillCurrent,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient: input.runtime.apiClient,\n author,\n execSql: input.runtime.infra.execSql,\n grants: [\n ...new Map(\n [...input.currentPolicy.currentGrants, ...input.nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: input.groupId,\n nextPolicy: input.nextPolicy,\n resolveAuthoredPolicyReferences: input.resolveAuthoredPolicyReferences,\n revokedContainerId: input.revokedContainerId,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n}\n"]}
1
+ {"version":3,"file":"principalContainerMutations.js","sourceRoot":"","sources":["principalContainerMutations.ts"],"names":[],"mappings":"AAGA,OAAO,EAGL,+CAA+C,GAChD,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,2BAA2B,EAAE,MAAM,2BAA2B,CAAC;AAIxE,MAAM,CAAC,KAAK,UAAU,kCAAkC,CAAC,KAaxD;IACC,MAAM,MAAM,GAAG,2BAA2B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC1D,MAAM,eAAe,GAAG,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,SAAS,CAAC;IAC7E,IAAI,CAAC,MAAM,IAAI,CAAC,eAAe,EAAE,CAAC;QAChC,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAC;IACJ,CAAC;IACD,OAAO,+CAA+C,CAAC;QACrD,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;QACpD,sBAAsB,EAAE,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,sBAAsB;QACjE,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,SAAS;QAClC,MAAM;QACN,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,MAAM,EAAE;YACN,GAAG,IAAI,GAAG,CACR,CAAC,GAAG,KAAK,CAAC,aAAa,CAAC,aAAa,EAAE,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,GAAG,CACpE,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,WAAW,EAAE,KAAK,CAAU,CAC/C,CACF,CAAC,MAAM,EAAE;SACX;QACD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;QACtE,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,0BAA0B,EAAE,KAAK,CAAC,OAAO,CAAC,0BAA0B;QACpE,eAAe;QACf,+BAA+B,EAC7B,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,YAAY,EAAE;KACjD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../data/principalContracts/principalPolicyEvidence\";\nimport type { CurrentPolicyReferenceResolver } from \"../../data/principals/currentPolicyReferenceResolver\";\nimport {\n type PreparedPrincipalContainerRematerializationBatch,\n type PrincipalRematerializationPredecessor,\n preparePrincipalContainerRematerializationBatch,\n} from \"../../workflows/containers/rematerialization\";\nimport { resolveDocumentCreateAuthor } from \"../../workflows/documents\";\n\nimport type { InternalWorkflowRuntimeInput } from \"../runtime/workflowRuntime\";\n\nexport async function preparePrincipalContainerMutations(input: {\n readonly preceding?: PrincipalRematerializationPredecessor | undefined;\n readonly currentPolicy: Pick<PrincipalPolicyBundleResponse, \"currentGrants\">;\n readonly groupId: string;\n readonly nextPolicy: PrincipalPolicyCurrentEvidence;\n readonly resolveAuthoredPolicyReferences?:\n | CurrentPolicyReferenceResolver\n | undefined;\n readonly organizationId: string;\n readonly revokedContainerId?: string | undefined;\n readonly runtime: InternalWorkflowRuntimeInput;\n readonly stillCurrent: () => boolean;\n readonly recitationStillCurrent?: (() => boolean) | undefined;\n}): Promise<PreparedPrincipalContainerRematerializationBatch> {\n const author = resolveDocumentCreateAuthor(input.runtime);\n const targetSecretKey = input.runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!author || !targetSecretKey) {\n throw new Error(\n \"Organization container rematerialization context is unavailable\",\n );\n }\n return preparePrincipalContainerRematerializationBatch({\n preceding: input.preceding,\n stillCurrent: input.stillCurrent,\n recitationStillCurrent: input.recitationStillCurrent,\n reportSecurityIncident: input.runtime.util.reportSecurityIncident,\n apiClient: input.runtime.apiClient,\n author,\n execSql: input.runtime.infra.execSql,\n grants: [\n ...new Map(\n [...input.currentPolicy.currentGrants, ...input.nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: input.groupId,\n nextPolicy: input.nextPolicy,\n resolveAuthoredPolicyReferences: input.resolveAuthoredPolicyReferences,\n revokedContainerId: input.revokedContainerId,\n resolveTrustedUserIdentity: input.runtime.resolveTrustedUserIdentity,\n targetSecretKey,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { computeUserIdentityBundleFingerprint } from "../../internal/crypto/index.js";
2
2
  import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
3
- import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
3
+ import { principalHeadMatchesReference } from "../../data/principalContracts/organizationAuthorityDescriptor.js";
4
4
  import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
5
5
  import { DatabaseUnavailableError } from "../../data/sqlite/availability/databaseUnavailable.js";
6
6
  import { UnverifiedUserIdentityError, } from "../../data/trustedUserIdentity/index.js";
@@ -1 +1 @@
1
- {"version":3,"file":"recipientAdmission.js","sourceRoot":"","sources":["recipientAdmission.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,mBAAmB,CAAC;AAEzE,OAAO,EAAE,gCAAgC,EAAE,M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AAC,YAAY,EAAE,SAAS,CAAC,IAAI,CAAC,EACpE,CAAC;YACD,MAAM,IAAI,oCAAoC,CAC5C,uDAAuD,CACxD,CAAC;QACJ,CAAC;QACD,aAAa,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAC8C,EAC9C,MAAc;IAEd,MAAM,QAAQ,GAAG,kCAAkC,CAAC,OAAO,CAAC,CAAC;IAC7D,MAAM,SAAS,GAAG,MAAM,2BAA2B,CACjD,OAAO,EACP,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAC9B,MAAM,CACP,CAAC;IACF,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE;QAC1B,MAAM,IAAI,wBAAwB,CAChC,mEAAmE,CACpE,CAAC;IACJ,OAAO,EAAE,GAAG,QAAQ,EAAE,SAAS,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { computeUserIdentityBundleFingerprint } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { DatabaseUnavailableError } from \"../../data/sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n UnverifiedUserIdentityError,\n} from \"../../data/trustedUserIdentity\";\nimport {\n isRosterVouchedRecipient,\n type RosterAdmissionEvidence,\n type RosterAdmissionPin,\n} from \"../../workflows/organizations/memberships/rosterVouchedAdmission\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport {\n currentOrganizationMutation,\n currentOrganizationSigningMutation,\n} from \"./principalMutationScope\";\nimport { createRosterAdmissionEvidence } from \"./rosterAdmissionEvidence\";\n\nexport { loadServedStateEnvelopes } from \"./rosterAdmissionEvidence\";\n\ntype AdmissionRuntimeService = Pick<\n InternalRuntime,\n \"identityLinks\" | \"sessionGeneration\" | \"workflowInput\"\n>;\n\n/** Thrown inside the staged scope so a refused recipient publishes nothing. */\nclass RecipientNotVouched extends Error {}\n\nasync function stagedPin(\n candidate: NonNullable<Awaited<ReturnType<StagedUserIdentityResolver>>>,\n): Promise<RosterAdmissionPin> {\n return {\n encapsulationKeyFingerprint: candidate.encapsulationKeyFingerprint,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(candidate),\n signingKeyFingerprint: candidate.signingKeyFingerprint,\n verified: false,\n };\n}\n\n/**\n * Admit against the server's first answers without pinning them: the\n * recipient's answer, and that of any historical signer the chain needs but\n * this device has not pinned (a departed admin seen only in older Members\n * states), are staged. Each is checked against its committed Members bundle,\n * and all are pinned as observed only once the signed roster vouches for the\n * recipient's exact identity bundle. A substituted answer leaves no pin, so a\n * corrected retry or the honest identity link still succeeds.\n */\nasync function isStagedRosterVouchedRecipient(\n userId: string,\n evidence: RosterAdmissionEvidence,\n resolver: TrustedUserIdentityResolver,\n assertCurrent: (() => void) | undefined,\n): Promise<boolean> {\n // Without staging, admit only a durable pin: never pin before the roster.\n if (!resolver.withPinnedIdentities)\n return isRosterVouchedRecipient(userId, evidence);\n try {\n return await resolver.withPinnedIdentities(\n [userId],\n async (resolve) => {\n const candidate = await resolve(userId);\n const vouched =\n candidate !== null &&\n (await isRosterVouchedRecipient(userId, {\n ...evidence,\n loadPin: async (id) => {\n const pin = await evidence.loadPin(id);\n if (pin) return pin;\n const staged = id === userId ? candidate : await resolve(id);\n return staged ? stagedPin(staged) : null;\n },\n }));\n if (!vouched) throw new RecipientNotVouched();\n return true;\n },\n { publish: true, assertCurrent },\n );\n } catch (error) {\n if (error instanceof RecipientNotVouched) return false;\n throw error;\n }\n}\n\n/**\n * Whether the signed roster vouches for `userId` on this device, for exactly\n * the domain-scoped signing and encapsulation identity bundle the server\n * serves. Served material that fails verification is recorded as a security\n * incident before the error propagates.\n */\nexport function isReportedRosterVouchedRecipient(input: {\n readonly evidence: RosterAdmissionEvidence;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly userId: string;\n /** The admission's lifetime, checked inside every pin write. */\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<boolean> {\n const { evidence, userId } = input;\n return runWithSecurityIncidentReporting(\n input.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"container.share.roster_vouch\",\n organizationId: input.organizationId,\n },\n () =>\n isStagedRosterVouchedRecipient(\n userId,\n evidence,\n input.resolveTrustedUserIdentity,\n input.assertCurrent,\n ),\n );\n}\n\ntype RecipientAdmission =\n | { readonly status: \"verified\" }\n | { readonly status: \"roster\"; readonly head: ReferencedPrincipalHead };\n\nasync function requireOrganizationRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<RecipientAdmission> {\n try {\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n return { status: \"verified\" };\n } catch (error) {\n const runtime = service.workflowInput();\n const organizationId = runtime.auth.organizationId;\n if (!(error instanceof UnverifiedUserIdentityError) || !organizationId)\n throw error;\n const evidence = createRosterAdmissionEvidence(\n service,\n admittingExecSql,\n organizationId,\n );\n if (!evidence) throw error;\n let head: ReferencedPrincipalHead | undefined;\n const vouched = await isReportedRosterVouchedRecipient({\n assertCurrent: admissionLifetime(service, admittingExecSql),\n evidence: {\n ...evidence,\n async loadCurrentMembers() {\n const members = await evidence.loadCurrentMembers();\n head = members.head;\n return members;\n },\n },\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n userId,\n });\n if (!vouched || !head) throw error;\n return { status: \"roster\", head };\n }\n}\n\nfunction admissionLifetime(service: AdmissionRuntimeService, execSql: ExecSql) {\n const scope = currentOrganizationMutation(service);\n return () => {\n if (scope.runtime.infra.execSql !== execSql || !scope.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active identity or database changed while admitting this user. Try again.\",\n );\n };\n}\n\n/** Full-bundle roster authentication admits read, write, and admin shares. */\nexport async function requireShareRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n _accessLevel: ContainerAccessLevel,\n): Promise<void> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n await requireOrganizationRecipient(service, admittingExecSql, userId);\n assertCurrent();\n}\n\nexport type GroupMemberAdmission = (\n members: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n) => Promise<void>;\n\n/** The proof is usable only at its exact Members head, within this runtime. */\nexport async function requireGroupMemberAdmission(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<GroupMemberAdmission> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n const admission = await requireOrganizationRecipient(\n service,\n admittingExecSql,\n userId,\n );\n assertCurrent();\n return async (members) => {\n assertCurrent();\n if (!members.currentProjection.some((member) => member.userId === userId)) {\n // A retry may find the user removed since the proof. Enrollment still\n // requires this device's self/link anchor, never an earlier roster proof.\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n } else if (\n admission.status === \"roster\" &&\n !principalHeadMatchesReference(members.currentState, admission.head)\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Members changed while admitting this user. Try again.\",\n );\n }\n assertCurrent();\n };\n}\n\n/** Capture the mutation scope before obtaining its head-bound admission proof. */\nexport async function admitGroupMutation(\n service: AdmissionRuntimeService &\n Pick<InternalRuntime, \"identityTrustDomain\">,\n userId: string,\n) {\n const mutation = currentOrganizationSigningMutation(service);\n const admission = await requireGroupMemberAdmission(\n service,\n mutation.runtime.infra.execSql,\n userId,\n );\n if (!mutation.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n return { ...mutation, admission };\n}\n"]}
1
+ {"version":3,"file":"recipientAdmission.js","sourceRoot":"","sources":["recipientAdmission.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,mBAAmB,CAAC;AAEzE,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EAAE,6BAA6B,EAAE,MAAM,+DAA+D,CAAC;AAC9G,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAE/F,OAAO,EAAE,wBAAwB,EAAE,MAAM,oDAAoD,CAAC;AAE9F,OAAO,EAGL,2BAA2B,GAC5B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,wBAAwB,GAGzB,MAAM,kEAAkE,CAAC;AAE1E,OAAO,EACL,2BAA2B,EAC3B,kCAAkC,GACnC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAE1E,OAAO,EAAE,wBAAwB,EAAE,MAAM,2BAA2B,CAAC;AAOrE,+EAA+E;AAC/E,MAAM,mBAAoB,SAAQ,KAAK;CAAG;AAE1C,KAAK,UAAU,SAAS,CACtB,SAAuE;IAEvE,OAAO;QACL,2BAA2B,EAAE,SAAS,CAAC,2BAA2B;QAClE,yBAAyB,EACvB,MAAM,oCAAoC,CAAC,SAAS,CAAC;QACvD,qBAAqB,EAAE,SAAS,CAAC,qBAAqB;QACtD,QAAQ,EAAE,KAAK;KAChB,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,KAAK,UAAU,8BAA8B,CAC3C,MAAc,EACd,QAAiC,EACjC,QAAqC,EACrC,aAAuC;IAEvC,0EAA0E;IAC1E,IAAI,CAAC,QAAQ,CAAC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AChB,IAAI,CAAC,OAAO,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,KAAK,MAAM,CAAC,EAAE,CAAC;YAC1E,sEAAsE;YACtE,0EAA0E;YAC1E,MAAM,OAAO,CAAC,aAAa,CAAC,eAAe,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC;QACxE,CAAC;aAAM,IACL,SAAS,CAAC,MAAM,KAAK,QAAQ;YAC7B,CAAC,6BAA6B,CAAC,OAAO,CAAC,YAAY,EAAE,SAAS,CAAC,IAAI,CAAC,EACpE,CAAC;YACD,MAAM,IAAI,oCAAoC,CAC5C,uDAAuD,CACxD,CAAC;QACJ,CAAC;QACD,aAAa,EAAE,CAAC;IAClB,CAAC,CAAC;AACJ,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,KAAK,UAAU,kBAAkB,CACtC,OAC8C,EAC9C,MAAc;IAEd,MAAM,QAAQ,GAAG,kCAAkC,CAAC,OAAO,CAAC,CAAC;IAC7D,MAAM,SAAS,GAAG,MAAM,2BAA2B,CACjD,OAAO,EACP,QAAQ,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,EAC9B,MAAM,CACP,CAAC;IACF,IAAI,CAAC,QAAQ,CAAC,YAAY,EAAE;QAC1B,MAAM,IAAI,wBAAwB,CAChC,mEAAmE,CACpE,CAAC;IACJ,OAAO,EAAE,GAAG,QAAQ,EAAE,SAAS,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { computeUserIdentityBundleFingerprint } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport { principalHeadMatchesReference } from \"../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport { DatabaseUnavailableError } from \"../../data/sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n UnverifiedUserIdentityError,\n} from \"../../data/trustedUserIdentity\";\nimport {\n isRosterVouchedRecipient,\n type RosterAdmissionEvidence,\n type RosterAdmissionPin,\n} from \"../../workflows/organizations/memberships/rosterVouchedAdmission\";\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport {\n currentOrganizationMutation,\n currentOrganizationSigningMutation,\n} from \"./principalMutationScope\";\nimport { createRosterAdmissionEvidence } from \"./rosterAdmissionEvidence\";\n\nexport { loadServedStateEnvelopes } from \"./rosterAdmissionEvidence\";\n\ntype AdmissionRuntimeService = Pick<\n InternalRuntime,\n \"identityLinks\" | \"sessionGeneration\" | \"workflowInput\"\n>;\n\n/** Thrown inside the staged scope so a refused recipient publishes nothing. */\nclass RecipientNotVouched extends Error {}\n\nasync function stagedPin(\n candidate: NonNullable<Awaited<ReturnType<StagedUserIdentityResolver>>>,\n): Promise<RosterAdmissionPin> {\n return {\n encapsulationKeyFingerprint: candidate.encapsulationKeyFingerprint,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(candidate),\n signingKeyFingerprint: candidate.signingKeyFingerprint,\n verified: false,\n };\n}\n\n/**\n * Admit against the server's first answers without pinning them: the\n * recipient's answer, and that of any historical signer the chain needs but\n * this device has not pinned (a departed admin seen only in older Members\n * states), are staged. Each is checked against its committed Members bundle,\n * and all are pinned as observed only once the signed roster vouches for the\n * recipient's exact identity bundle. A substituted answer leaves no pin, so a\n * corrected retry or the honest identity link still succeeds.\n */\nasync function isStagedRosterVouchedRecipient(\n userId: string,\n evidence: RosterAdmissionEvidence,\n resolver: TrustedUserIdentityResolver,\n assertCurrent: (() => void) | undefined,\n): Promise<boolean> {\n // Without staging, admit only a durable pin: never pin before the roster.\n if (!resolver.withPinnedIdentities)\n return isRosterVouchedRecipient(userId, evidence);\n try {\n return await resolver.withPinnedIdentities(\n [userId],\n async (resolve) => {\n const candidate = await resolve(userId);\n const vouched =\n candidate !== null &&\n (await isRosterVouchedRecipient(userId, {\n ...evidence,\n loadPin: async (id) => {\n const pin = await evidence.loadPin(id);\n if (pin) return pin;\n const staged = id === userId ? candidate : await resolve(id);\n return staged ? stagedPin(staged) : null;\n },\n }));\n if (!vouched) throw new RecipientNotVouched();\n return true;\n },\n { publish: true, assertCurrent },\n );\n } catch (error) {\n if (error instanceof RecipientNotVouched) return false;\n throw error;\n }\n}\n\n/**\n * Whether the signed roster vouches for `userId` on this device, for exactly\n * the domain-scoped signing and encapsulation identity bundle the server\n * serves. Served material that fails verification is recorded as a security\n * incident before the error propagates.\n */\nexport function isReportedRosterVouchedRecipient(input: {\n readonly evidence: RosterAdmissionEvidence;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly userId: string;\n /** The admission's lifetime, checked inside every pin write. */\n readonly assertCurrent?: (() => void) | undefined;\n}): Promise<boolean> {\n const { evidence, userId } = input;\n return runWithSecurityIncidentReporting(\n input.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"container.share.roster_vouch\",\n organizationId: input.organizationId,\n },\n () =>\n isStagedRosterVouchedRecipient(\n userId,\n evidence,\n input.resolveTrustedUserIdentity,\n input.assertCurrent,\n ),\n );\n}\n\ntype RecipientAdmission =\n | { readonly status: \"verified\" }\n | { readonly status: \"roster\"; readonly head: ReferencedPrincipalHead };\n\nasync function requireOrganizationRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<RecipientAdmission> {\n try {\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n return { status: \"verified\" };\n } catch (error) {\n const runtime = service.workflowInput();\n const organizationId = runtime.auth.organizationId;\n if (!(error instanceof UnverifiedUserIdentityError) || !organizationId)\n throw error;\n const evidence = createRosterAdmissionEvidence(\n service,\n admittingExecSql,\n organizationId,\n );\n if (!evidence) throw error;\n let head: ReferencedPrincipalHead | undefined;\n const vouched = await isReportedRosterVouchedRecipient({\n assertCurrent: admissionLifetime(service, admittingExecSql),\n evidence: {\n ...evidence,\n async loadCurrentMembers() {\n const members = await evidence.loadCurrentMembers();\n head = members.head;\n return members;\n },\n },\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n userId,\n });\n if (!vouched || !head) throw error;\n return { status: \"roster\", head };\n }\n}\n\nfunction admissionLifetime(service: AdmissionRuntimeService, execSql: ExecSql) {\n const scope = currentOrganizationMutation(service);\n return () => {\n if (scope.runtime.infra.execSql !== execSql || !scope.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active identity or database changed while admitting this user. Try again.\",\n );\n };\n}\n\n/** Full-bundle roster authentication admits read, write, and admin shares. */\nexport async function requireShareRecipient(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n _accessLevel: ContainerAccessLevel,\n): Promise<void> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n await requireOrganizationRecipient(service, admittingExecSql, userId);\n assertCurrent();\n}\n\nexport type GroupMemberAdmission = (\n members: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n) => Promise<void>;\n\n/** The proof is usable only at its exact Members head, within this runtime. */\nexport async function requireGroupMemberAdmission(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n userId: string,\n): Promise<GroupMemberAdmission> {\n const assertCurrent = admissionLifetime(service, admittingExecSql);\n assertCurrent();\n const admission = await requireOrganizationRecipient(\n service,\n admittingExecSql,\n userId,\n );\n assertCurrent();\n return async (members) => {\n assertCurrent();\n if (!members.currentProjection.some((member) => member.userId === userId)) {\n // A retry may find the user removed since the proof. Enrollment still\n // requires this device's self/link anchor, never an earlier roster proof.\n await service.identityLinks.requireVerified(userId, admittingExecSql);\n } else if (\n admission.status === \"roster\" &&\n !principalHeadMatchesReference(members.currentState, admission.head)\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Members changed while admitting this user. Try again.\",\n );\n }\n assertCurrent();\n };\n}\n\n/** Capture the mutation scope before obtaining its head-bound admission proof. */\nexport async function admitGroupMutation(\n service: AdmissionRuntimeService &\n Pick<InternalRuntime, \"identityTrustDomain\">,\n userId: string,\n) {\n const mutation = currentOrganizationSigningMutation(service);\n const admission = await requireGroupMemberAdmission(\n service,\n mutation.runtime.infra.execSql,\n userId,\n );\n if (!mutation.stillCurrent())\n throw new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n return { ...mutation, admission };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { computeUserIdentityBundleFingerprint, KeyingVerificationError, } from "../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
3
- import { requireOrganizationGroupHead } from "../../data/principals/organizationAuthorityDescriptor.js";
3
+ import { requireOrganizationGroupHead } from "../../data/principalContracts/organizationAuthorityDescriptor.js";
4
4
  import { loadCurrentOrganizationAuthority } from "../../workflows/organizations/currentOrganizationAuthority.js";
5
5
  import { currentOrganizationMutation } from "./principalMutationScope.js";
6
6
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"rosterAdmissionEvidence.js","sourceRoot":"","sources":["rosterAdmissionEvidence.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,4BAA4B,EAAE,MAAM,uDAAuD,CAAC;AAErG,OAAO,EAAE,gCAAgC,EAAE,MAAM,4DAA4D,CAAC;AAI9G,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0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BAAwB,CAAC,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC;KACrD,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n computeUserIdentityBundleFingerprint,\n KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport type {\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { requireOrganizationGroupHead } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { loadCurrentOrganizationAuthority } from \"../../workflows/organizations/currentOrganizationAuthority\";\nimport type { RosterAdmissionEvidence } from \"../../workflows/organizations/memberships/rosterVouchedAdmission\";\n\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { currentOrganizationMutation } from \"./principalMutationScope\";\n\n/**\n * The server's member envelopes for one state, or null when it has no such\n * state. A response that fails its schema or names another state is served\n * material failing verification, so it surfaces as a `KeyingVerificationError`\n * for incident reporting; other failures stay availability errors.\n */\nexport async function loadServedStateEnvelopes(\n reader: Pick<ApiClient, \"getPrincipalMemberEnvelopesResult\">,\n state: Pick<\n PrincipalStateResponse,\n \"principalId\" | \"principalType\" | \"stateHash\"\n >,\n): Promise<CurrentPrincipalMemberEnvelopesResponse | null> {\n const result = await reader.getPrincipalMemberEnvelopesResult(\n state.principalType,\n state.principalId,\n state.stateHash,\n );\n if (result.ok) return result.data;\n if (result.kind === \"http\" && result.status === 404) return null;\n if (result.kind === \"shape\")\n throw new KeyingVerificationError(\"invalid_shape\", result.message);\n result.report();\n throw new Error(result.message);\n}\n\ntype AdmissionRuntimeService = Pick<\n InternalRuntime,\n \"identityLinks\" | \"sessionGeneration\" | \"workflowInput\"\n>;\n\nexport function createRosterAdmissionEvidence(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n organizationId: string,\n): RosterAdmissionEvidence | null {\n const { runtime, stillCurrent } = currentOrganizationMutation(service);\n const resolve = runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolve) return null;\n return {\n async loadCurrentMembers() {\n const authority = await loadCurrentOrganizationAuthority({\n execSql: runtime.infra.execSql,\n organizationId,\n resolveCurrentPolicy: resolve,\n stillCurrent,\n });\n const { memberGroupId } = authority.descriptor;\n const members = await authority.readGroup(memberGroupId);\n assertProjectionVerificationCurrent(members.stillCurrent);\n return {\n projection: members.current.currentProjection,\n envelopes: members.current.currentMemberEnvelopes.envelopes,\n head: requireOrganizationGroupHead(authority.descriptor, memberGroupId),\n };\n },\n async loadHistoryPage(head, beforeVersion) {\n const resolved = await resolve({\n organizationId,\n reference: head,\n preferLocalCurrent: true,\n 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 async loadPin(userId) {\n const pin = await service.identityLinks.loadAdmissionPin(\n userId,\n admittingExecSql,\n );\n return pin\n ? {\n encapsulationKeyFingerprint:\n pin.identity.encapsulationKeyFingerprint,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(pin.identity),\n signingKeyFingerprint: pin.identity.signingKeyFingerprint,\n verified: pin.verified,\n }\n : null;\n },\n loadStateEnvelopes: (state) =>\n loadServedStateEnvelopes(runtime.apiClient, state),\n };\n}\n"]}
1
+ {"version":3,"file":"rosterAdmissionEvidence.js","sourceRoot":"","sources":["rosterAdmissionEvidence.ts"],"names":[],"mappings":"AACA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,GACxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,4BAA4B,EAAE,MAAM,+DAA+D,CAAC;AAE7G,OAAO,EAAE,gCAAgC,EAAE,MAAM,4DAA4D,CAAC;AAI9G,OAAO,EA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AC,KAAK,EAAE,EAAE,CAC5B,wBAAwB,CAAC,OAAO,CAAC,SAAS,EAAE,KAAK,CAAC;KACrD,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n computeUserIdentityBundleFingerprint,\n KeyingVerificationError,\n} from \"@tearleads/crypto\";\nimport type {\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { requireOrganizationGroupHead } from \"../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { loadCurrentOrganizationAuthority } from \"../../workflows/organizations/currentOrganizationAuthority\";\nimport type { RosterAdmissionEvidence } from \"../../workflows/organizations/memberships/rosterVouchedAdmission\";\n\nimport type { InternalRuntime } from \"../runtime/workflowRuntime\";\nimport { currentOrganizationMutation } from \"./principalMutationScope\";\n\n/**\n * The server's member envelopes for one state, or null when it has no such\n * state. A response that fails its schema or names another state is served\n * material failing verification, so it surfaces as a `KeyingVerificationError`\n * for incident reporting; other failures stay availability errors.\n */\nexport async function loadServedStateEnvelopes(\n reader: Pick<ApiClient, \"getPrincipalMemberEnvelopesResult\">,\n state: Pick<\n PrincipalStateResponse,\n \"principalId\" | \"principalType\" | \"stateHash\"\n >,\n): Promise<CurrentPrincipalMemberEnvelopesResponse | null> {\n const result = await reader.getPrincipalMemberEnvelopesResult(\n state.principalType,\n state.principalId,\n state.stateHash,\n );\n if (result.ok) return result.data;\n if (result.kind === \"http\" && result.status === 404) return null;\n if (result.kind === \"shape\")\n throw new KeyingVerificationError(\"invalid_shape\", result.message);\n result.report();\n throw new Error(result.message);\n}\n\ntype AdmissionRuntimeService = Pick<\n InternalRuntime,\n \"identityLinks\" | \"sessionGeneration\" | \"workflowInput\"\n>;\n\nexport function createRosterAdmissionEvidence(\n service: AdmissionRuntimeService,\n admittingExecSql: ExecSql,\n organizationId: string,\n): RosterAdmissionEvidence | null {\n const { runtime, stillCurrent } = currentOrganizationMutation(service);\n const resolve = runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolve) return null;\n return {\n async loadCurrentMembers() {\n const authority = await loadCurrentOrganizationAuthority({\n execSql: runtime.infra.execSql,\n organizationId,\n resolveCurrentPolicy: resolve,\n stillCurrent,\n });\n const { memberGroupId } = authority.descriptor;\n const members = await authority.readGroup(memberGroupId);\n assertProjectionVerificationCurrent(members.stillCurrent);\n return {\n projection: members.current.currentProjection,\n envelopes: members.current.currentMemberEnvelopes.envelopes,\n head: requireOrganizationGroupHead(authority.descriptor, memberGroupId),\n };\n },\n async loadHistoryPage(head, beforeVersion) {\n const resolved = await resolve({\n organizationId,\n reference: head,\n preferLocalCurrent: true,\n 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 async loadPin(userId) {\n const pin = await service.identityLinks.loadAdmissionPin(\n userId,\n admittingExecSql,\n );\n return pin\n ? {\n encapsulationKeyFingerprint:\n pin.identity.encapsulationKeyFingerprint,\n identityBundleFingerprint:\n await computeUserIdentityBundleFingerprint(pin.identity),\n signingKeyFingerprint: pin.identity.signingKeyFingerprint,\n verified: pin.verified,\n }\n : null;\n },\n loadStateEnvelopes: (state) =>\n loadServedStateEnvelopes(runtime.apiClient, state),\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
2
- import type { PrincipalPolicyCheckpointEvidence } from "../../principals/principalPolicyEvidence.js";
2
+ import type { PrincipalPolicyCheckpointEvidence } from "../../principalContracts/principalPolicyEvidence.js";
3
3
  import type { ContainerMutationAuthor } from "./types.js";
4
4
  export declare class ContainerAuthorAccessError extends Error {
5
5
  readonly code = "unauthorized";
@@ -1 +1 @@
1
- {"version":3,"file":"authorAccess.js","sourceRoot":"","sources":["authorAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAGlD,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IAC1C,IAAI,GAAG,cAAc,CAAC;IACtB,MAAM,GAAG,GAAG,CAAC;IAEtB,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;IAC3C,CAAC;CACF;AAED,mFAAmF;AACnF,MAAM,UAAU,2BAA2B,CAAC,KAK3C;IACC,MAAM,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IAC7D,IACE,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,cAAc,KAAK,KAAK,CAAC,MAAM,CAAC,cAAc,CAAC;QAE5E,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;IACJ,MAAM,MAAM,GAAG,wCAAwC,CAAC;QACtD,MAAM;QACN,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;KAClC,CAAC,CAAC;IACH,IACE,MAAM,KAAK,OAAO;QAClB,CAAC,CAAC,KAAK,CAAC,aAAa,KAAK,OAAO,IAAI,MAAM,KAAK,OAAO,CAAC;QAExD,MAAM,IAAI,0BAA0B,CAClC,0BAA0B,KAAK,CAAC,aAAa,8BAA8B,CAC5E,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n resolveContainerStatePathUserAccessLevel,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { readContainerState } from \"./projection\";\nimport type { ContainerMutationAuthor } from \"./types\";\n\nexport class ContainerAuthorAccessError extends Error {\n readonly code = \"unauthorized\";\n readonly status = 403;\n\n constructor(message: string) {\n super(message);\n this.name = \"ContainerAuthorAccessError\";\n }\n}\n\n/** Call after verifying the path; readable keys alone do not authorize signing. */\nexport function assertContainerAuthorAccess(input: {\n author: ContainerMutationAuthor;\n minimumAccess: \"write\" | \"admin\";\n principalPolicies: readonly PrincipalPolicyCheckpointEvidence[];\n projection: ContainerWriterProjectionResponse;\n}): void {\n const states = input.projection.path.map(readContainerState);\n if (\n states.some((state) => state.organizationId !== input.author.organizationId)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container author organization differs from the verified path\",\n );\n const access = resolveContainerStatePathUserAccessLevel({\n states,\n principalPolicies: input.principalPolicies,\n userId: input.author.signerUserId,\n });\n if (\n access !== \"admin\" &&\n !(input.minimumAccess === \"write\" && access === \"write\")\n )\n throw new ContainerAuthorAccessError(\n `Container signer lacks ${input.minimumAccess} access on the verified path`,\n );\n}\n"]}
1
+ {"version":3,"file":"authorAccess.js","sourceRoot":"","sources":["authorAccess.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,wCAAwC,GACzC,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AAGlD,MAAM,OAAO,0BAA2B,SAAQ,KAAK;IAC1C,IAAI,GAAG,cAAc,CAAC;IACtB,MAAM,GAAG,GAAG,CAAC;IAEtB,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,4BAA4B,CAAC;IAC3C,CAAC;CACF;AAED,mFAAmF;AACnF,MAAM,UAAU,2BAA2B,CAAC,KAK3C;IACC,MAAM,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IAC7D,IACE,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,cAAc,KAAK,KAAK,CAAC,MAAM,CAAC,cAAc,CAAC;QAE5E,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;IACJ,MAAM,MAAM,GAAG,wCAAwC,CAAC;QACtD,MAAM;QACN,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,YAAY;KAClC,CAAC,CAAC;IACH,IACE,MAAM,KAAK,OAAO;QAClB,CAAC,CAAC,KAAK,CAAC,aAAa,KAAK,OAAO,IAAI,MAAM,KAAK,OAAO,CAAC;QAExD,MAAM,IAAI,0BAA0B,CAClC,0BAA0B,KAAK,CAAC,aAAa,8BAA8B,CAC5E,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n resolveContainerStatePathUserAccessLevel,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { readContainerState } from \"./projection\";\nimport type { ContainerMutationAuthor } from \"./types\";\n\nexport class ContainerAuthorAccessError extends Error {\n readonly code = \"unauthorized\";\n readonly status = 403;\n\n constructor(message: string) {\n super(message);\n this.name = \"ContainerAuthorAccessError\";\n }\n}\n\n/** Call after verifying the path; readable keys alone do not authorize signing. */\nexport function assertContainerAuthorAccess(input: {\n author: ContainerMutationAuthor;\n minimumAccess: \"write\" | \"admin\";\n principalPolicies: readonly PrincipalPolicyCheckpointEvidence[];\n projection: ContainerWriterProjectionResponse;\n}): void {\n const states = input.projection.path.map(readContainerState);\n if (\n states.some((state) => state.organizationId !== input.author.organizationId)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container author organization differs from the verified path\",\n );\n const access = resolveContainerStatePathUserAccessLevel({\n states,\n principalPolicies: input.principalPolicies,\n userId: input.author.signerUserId,\n });\n if (\n access !== \"admin\" &&\n !(input.minimumAccess === \"write\" && access === \"write\")\n )\n throw new ContainerAuthorAccessError(\n `Container signer lacks ${input.minimumAccess} access on the verified path`,\n );\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"heldContainerHeads.js","sourceRoot":"","sources":["heldContainerHeads.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,OAAO,EAAgB,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAmB/E,6EAA6E;AAC7E,gFAAgF;AAChF,MAAM,cAAc,GAAG,IAAI,OAAO,EAA2B,CAAC;AAC9D,4EAA4E;AAC5E,+EAA+E;AAC/E,MAAM,SAAS,GAAG,GAAG,CAAC;AACtB,MAAM,YAAY,GAAG,GAAG,CAAC;AAEzB,SAAS,cAAc,CAAC,OAAgB;IACtC,MAAM,SAAS,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;IACnD,IAAI,IAAI,GAAG,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACzC,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,IAAI,GAAG,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC;QACjD,cAAc,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC;IACtC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAED,SAAS,UAAU,CACjB,GAAmB,EACnB,GAAW,EACX,KAAQ,EACR,GAAW;IAEX,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;IAChB,GAAG,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACpB,IAAI,GAAG,CAAC,IAAI,GAAG,GAAG,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AAC,QAAQ,CAAC,MAAM,EAAE,CAAC;aAClC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,cAAc,KAAK,cAAc,CAAC;aAC1D,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,eAAe,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC;KACjD,CAAC;AACJ,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,iBAAiB,CAC/B,KAA6C,EAC7C,WAAmB;IAEnB,MAAM,IAAI,GAAwB,EAAE,CAAC;IACrC,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,IAAI,EAAE,GAAkB,WAAW,CAAC;IACpC,OAAO,EAAE,KAAK,IAAI,EAAE,CAAC;QACnB,IAAI,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC,MAAM,IAAI,yBAAyB;YAAE,OAAO,IAAI,CAAC;QAC1E,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QACb,MAAM,IAAI,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAC3B,IAAI,CAAC,IAAI;YAAE,OAAO,IAAI,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QACnB,EAAE,GAAG,IAAI,CAAC,KAAK,CAAC,iBAAiB,CAAC;IACpC,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWire } from \"@tearleads/validators/request\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { type ExecSql, resolveCanonicalExecSql } from \"../../sqlite/sqlSchema\";\nimport type { AuthoredContainerMutationHead } from \"./mutationAcknowledgement\";\n\nexport interface HeldContainerHead {\n readonly bundle: AccessManifestBundleWire;\n readonly state: ContainerAccessManifestState;\n}\n\ninterface HeldContainers {\n readonly heads: Map<string, HeldContainerHead>;\n readonly policies: Map<\n string,\n {\n readonly organizationId: string;\n readonly policy: PrincipalPolicyCheckpointEvidence;\n }\n >;\n}\n\n// Opportunistic, process-local evidence, not a persistent cache or freshness\n// oracle. No secret keys are retained. Eviction merely limits cascade coverage.\nconst heldByDatabase = new WeakMap<ExecSql, HeldContainers>();\n// Executor-wide limits: another organization's activity may evict evidence,\n// which only skips optional recitations and never changes durable checkpoints.\nconst MAX_HEADS = 256;\nconst MAX_POLICIES = 512;\n\nfunction heldContainers(execSql: ExecSql): HeldContainers {\n const canonical = resolveCanonicalExecSql(execSql);\n let held = heldByDatabase.get(canonical);\n if (!held) {\n held = { heads: new Map(), policies: new Map() };\n heldByDatabase.set(canonical, held);\n }\n return held;\n}\n\nfunction boundedSet<T>(\n map: Map<string, T>,\n key: string,\n value: T,\n max: number,\n) {\n map.delete(key);\n map.set(key, value);\n if (map.size > max) {\n const oldest = map.keys().next().value;\n if (oldest !== undefined) map.delete(oldest);\n }\n}\n\nfunction rememberHead(\n execSql: ExecSql,\n head: Pick<VerifiedContainerAccessManifest, \"state\" | \"manifestHash\">,\n build: () => HeldContainerHead,\n): void {\n const heads = heldContainers(execSql).heads;\n const previous = heads.get(head.state.containerId);\n if (previous && previous.state.epoch >= head.state.epoch) {\n if (previous.bundle.manifestHash === head.manifestHash) {\n boundedSet(heads, head.state.containerId, previous, MAX_HEADS);\n }\n return;\n }\n boundedSet(\n heads,\n head.state.containerId,\n structuredClone(build()),\n MAX_HEADS,\n );\n}\n\n/** Called only after the complete projection and its durable pins validate. */\nexport function rememberVerifiedContainerHeads(input: {\n readonly organizationId: string;\n readonly execSql: ExecSql;\n readonly heads: readonly VerifiedContainerAccessManifest[];\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n}): void {\n for (const policy of input.policies) {\n if (\n policy.principalType === \"organization\" &&\n policy.principalId !== input.organizationId\n ) {\n throw new Error(\"Held principal policy belongs to another organization\");\n }\n }\n // Group signed states contain no organization ID. Their scope is supplied\n // by the already-verified projection/policy caller, not inferred here.\n for (const head of input.heads) {\n if (head.state.organizationId !== input.organizationId) {\n throw new Error(\"Held container head belongs to another organization\");\n }\n }\n for (const head of input.heads) {\n rememberHead(input.execSql, head, () => ({\n state: head.state,\n bundle: {\n event: readCanonicalRecord(head.event, \"Verified container event\"),\n manifest: readCanonicalRecord(\n head.manifest,\n \"Verified container manifest\",\n ),\n manifestHash: head.manifestHash,\n state: readCanonicalRecord(head.state, \"Verified container state\"),\n },\n }));\n }\n const policies = heldContainers(input.execSql).policies;\n for (const policy of input.policies) {\n const key = `${input.organizationId}:${policy.principalType}:${policy.principalId}`;\n const previous = policies.get(key);\n if (previous && previous.policy.version > policy.version) continue;\n if (\n previous?.policy.version === policy.version &&\n previous.policy.stateHash !== policy.stateHash\n )\n continue;\n boundedSet(\n policies,\n key,\n { organizationId: input.organizationId, policy: structuredClone(policy) },\n MAX_POLICIES,\n );\n }\n}\n\n/** Caller must first correlate the exact response and durably acknowledge it. */\nexport function rememberAcknowledgedContainerHead(\n execSql: ExecSql,\n plan: Pick<\n AuthoredContainerMutationHead,\n \"body\" | \"event\" | \"eventHash\" | \"manifest\" | \"manifestHash\" | \"state\"\n >,\n): HeldContainerHead {\n const head: HeldContainerHead = {\n state: plan.state,\n bundle: {\n event: readCanonicalRecord(\n {\n event: plan.event,\n eventHash: plan.eventHash,\n body: plan.body,\n },\n \"Acknowledged container event\",\n ),\n manifest: readCanonicalRecord(\n plan.manifest,\n \"Acknowledged container manifest\",\n ),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Acknowledged container state\"),\n },\n };\n rememberHead(execSql, plan, () => head);\n return head;\n}\n\nexport function heldContainerSnapshot(\n execSql: ExecSql,\n organizationId: string,\n) {\n const held = heldContainers(execSql);\n return {\n heads: new Map(\n [...held.heads]\n .filter(([, head]) => head.state.organizationId === organizationId)\n .map(([id, head]) => [id, structuredClone(head)] as const),\n ),\n policies: [...held.policies.values()]\n .filter((entry) => entry.organizationId === organizationId)\n .map((entry) => structuredClone(entry.policy)),\n };\n}\n\n/** Resolve parent edges only; parentManifestHash is historical keying evidence. */\nexport function heldContainerPath(\n heads: ReadonlyMap<string, HeldContainerHead>,\n containerId: string,\n): HeldContainerHead[] | null {\n const path: HeldContainerHead[] = [];\n const seen = new Set<string>();\n let id: string | null = containerId;\n while (id !== null) {\n if (seen.has(id) || path.length >= MAX_CONTAINER_PATH_LENGTH) return null;\n seen.add(id);\n const head = heads.get(id);\n if (!head) return null;\n path.unshift(head);\n id = head.state.parentContainerId;\n }\n return path;\n}\n"]}
1
+ {"version":3,"file":"heldContainerHeads.js","sourceRoot":"","sources":["heldContainerHeads.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAEjE,OAAO,EAAgB,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAmB/E,6EAA6E;AAC7E,gFAAgF;AAChF,MAAM,cAAc,GAAG,IAAI,OAAO,EAA2B,CAAC;AAC9D,4EAA4E;AAC5E,+EAA+E;AAC/E,MAAM,SAAS,GAAG,GAAG,CAAC;AACtB,MAAM,YAAY,GAAG,GAAG,CAAC;AAEzB,SAAS,cAAc,CAAC,OAAgB;IACtC,MAAM,SAAS,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;IACnD,IAAI,IAAI,GAAG,cAAc,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IACzC,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,IAAI,GAAG,EAAE,KAAK,EAAE,IAAI,GAAG,EAAE,EAAE,QAAQ,EAAE,IAAI,GAAG,EAAE,EAAE,CAAC;QACjD,cAAc,CAAC,GAAG,CAAC,SAAS,EAA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from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWire } from \"@tearleads/validators/request\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { type ExecSql, resolveCanonicalExecSql } from \"../../sqlite/sqlSchema\";\nimport type { AuthoredContainerMutationHead } from \"./mutationAcknowledgement\";\n\nexport interface HeldContainerHead {\n readonly bundle: AccessManifestBundleWire;\n readonly state: ContainerAccessManifestState;\n}\n\ninterface HeldContainers {\n readonly heads: Map<string, HeldContainerHead>;\n readonly policies: Map<\n string,\n {\n readonly organizationId: string;\n readonly policy: PrincipalPolicyCheckpointEvidence;\n }\n >;\n}\n\n// Opportunistic, process-local evidence, not a persistent cache or freshness\n// oracle. No secret keys are retained. Eviction merely limits cascade coverage.\nconst heldByDatabase = new WeakMap<ExecSql, HeldContainers>();\n// Executor-wide limits: another organization's activity may evict evidence,\n// which only skips optional recitations and never changes durable checkpoints.\nconst MAX_HEADS = 256;\nconst MAX_POLICIES = 512;\n\nfunction heldContainers(execSql: ExecSql): HeldContainers {\n const canonical = resolveCanonicalExecSql(execSql);\n let held = heldByDatabase.get(canonical);\n if (!held) {\n held = { heads: new Map(), policies: new Map() };\n heldByDatabase.set(canonical, held);\n }\n return held;\n}\n\nfunction boundedSet<T>(\n map: Map<string, T>,\n key: string,\n value: T,\n max: number,\n) {\n map.delete(key);\n map.set(key, value);\n if (map.size > max) {\n const oldest = map.keys().next().value;\n if (oldest !== undefined) map.delete(oldest);\n }\n}\n\nfunction rememberHead(\n execSql: ExecSql,\n head: Pick<VerifiedContainerAccessManifest, \"state\" | \"manifestHash\">,\n build: () => HeldContainerHead,\n): void {\n const heads = heldContainers(execSql).heads;\n const previous = heads.get(head.state.containerId);\n if (previous && previous.state.epoch >= head.state.epoch) {\n if (previous.bundle.manifestHash === head.manifestHash) {\n boundedSet(heads, head.state.containerId, previous, MAX_HEADS);\n }\n return;\n }\n boundedSet(\n heads,\n head.state.containerId,\n structuredClone(build()),\n MAX_HEADS,\n );\n}\n\n/** Called only after the complete projection and its durable pins validate. */\nexport function rememberVerifiedContainerHeads(input: {\n readonly organizationId: string;\n readonly execSql: ExecSql;\n readonly heads: readonly VerifiedContainerAccessManifest[];\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n}): void {\n for (const policy of input.policies) {\n if (\n policy.principalType === \"organization\" &&\n policy.principalId !== input.organizationId\n ) {\n throw new Error(\"Held principal policy belongs to another organization\");\n }\n }\n // Group signed states contain no organization ID. Their scope is supplied\n // by the already-verified projection/policy caller, not inferred here.\n for (const head of input.heads) {\n if (head.state.organizationId !== input.organizationId) {\n throw new Error(\"Held container head belongs to another organization\");\n }\n }\n for (const head of input.heads) {\n rememberHead(input.execSql, head, () => ({\n state: head.state,\n bundle: {\n event: readCanonicalRecord(head.event, \"Verified container event\"),\n manifest: readCanonicalRecord(\n head.manifest,\n \"Verified container manifest\",\n ),\n manifestHash: head.manifestHash,\n state: readCanonicalRecord(head.state, \"Verified container state\"),\n },\n }));\n }\n const policies = heldContainers(input.execSql).policies;\n for (const policy of input.policies) {\n const key = `${input.organizationId}:${policy.principalType}:${policy.principalId}`;\n const previous = policies.get(key);\n if (previous && previous.policy.version > policy.version) continue;\n if (\n previous?.policy.version === policy.version &&\n previous.policy.stateHash !== policy.stateHash\n )\n continue;\n boundedSet(\n policies,\n key,\n { organizationId: input.organizationId, policy: structuredClone(policy) },\n MAX_POLICIES,\n );\n }\n}\n\n/** Caller must first correlate the exact response and durably acknowledge it. */\nexport function rememberAcknowledgedContainerHead(\n execSql: ExecSql,\n plan: Pick<\n AuthoredContainerMutationHead,\n \"body\" | \"event\" | \"eventHash\" | \"manifest\" | \"manifestHash\" | \"state\"\n >,\n): HeldContainerHead {\n const head: HeldContainerHead = {\n state: plan.state,\n bundle: {\n event: readCanonicalRecord(\n {\n event: plan.event,\n eventHash: plan.eventHash,\n body: plan.body,\n },\n \"Acknowledged container event\",\n ),\n manifest: readCanonicalRecord(\n plan.manifest,\n \"Acknowledged container manifest\",\n ),\n manifestHash: plan.manifestHash,\n state: readCanonicalRecord(plan.state, \"Acknowledged container state\"),\n },\n };\n rememberHead(execSql, plan, () => head);\n return head;\n}\n\nexport function heldContainerSnapshot(\n execSql: ExecSql,\n organizationId: string,\n) {\n const held = heldContainers(execSql);\n return {\n heads: new Map(\n [...held.heads]\n .filter(([, head]) => head.state.organizationId === organizationId)\n .map(([id, head]) => [id, structuredClone(head)] as const),\n ),\n policies: [...held.policies.values()]\n .filter((entry) => entry.organizationId === organizationId)\n .map((entry) => structuredClone(entry.policy)),\n };\n}\n\n/** Resolve parent edges only; parentManifestHash is historical keying evidence. */\nexport function heldContainerPath(\n heads: ReadonlyMap<string, HeldContainerHead>,\n containerId: string,\n): HeldContainerHead[] | null {\n const path: HeldContainerHead[] = [];\n const seen = new Set<string>();\n let id: string | null = containerId;\n while (id !== null) {\n if (seen.has(id) || path.length >= MAX_CONTAINER_PATH_LENGTH) return null;\n seen.add(id);\n const head = heads.get(id);\n if (!head) return null;\n path.unshift(head);\n id = head.state.parentContainerId;\n }\n return path;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicies.js","sourceRoot":"","sources":["principalPolicies.ts"],"names":[],"mappings":"AAIA;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAGC;IAED,OAAO;QACL,aAAa,EAAE,MAAM,CAAC,aAAa;QACnC,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,SAAS,EAAE,MAAM,CAAC,SAAS;KAC5B,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,MAGC;IAED,OAAO;QACL,MAAM,CAAC,aAAa;QACpB,MAAM,CAAC,WAAW;QAClB,MAAM,CAAC,OAAO;QACd,MAAM,CAAC,QAAQ;QACf,MAAM,CAAC,SAAS;KACjB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,uBAAuB,CAErC,QAAsB;IACtB,MAAM,aAAa,GAAG,IAAI,GAAG,EAAa,CAAC;IAE3C,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE,CAAC;QAC9B,aAAa,CAAC,GAAG,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC;IACxD,CAAC;IAED,OAAO,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,CAAC;AACrC,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyRef } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\n\n/**\n * The head a container mutation cites for a policy it was planned against.\n * The API authorizes from its own verified copy of that head, so the policy\n * itself never travels.\n */\nexport function principalPolicyRef(\n policy: Pick<\n VerifiedPrincipalPolicy,\n \"principalId\" | \"principalType\" | \"stateHash\" | \"version\"\n >,\n): PrincipalPolicyRef {\n return {\n principalType: policy.principalType,\n principalId: policy.principalId,\n version: policy.version,\n stateHash: policy.stateHash,\n };\n}\n\nfunction principalPolicyKey(\n policy: Pick<\n VerifiedPrincipalPolicy,\n \"keyEpoch\" | \"principalId\" | \"principalType\" | \"stateHash\" | \"version\"\n >,\n): string {\n return [\n policy.principalType,\n policy.principalId,\n policy.version,\n policy.keyEpoch,\n policy.stateHash,\n ].join(\":\");\n}\n\nexport function uniquePrincipalPolicies<\n T extends PrincipalPolicyCurrentEvidence,\n>(policies: readonly T[]): T[] {\n const policiesByKey = new Map<string, T>();\n\n for (const policy of policies) {\n policiesByKey.set(principalPolicyKey(policy), policy);\n }\n\n return [...policiesByKey.values()];\n}\n"]}
1
+ {"version":3,"file":"principalPolicies.js","sourceRoot":"","sources":["principalPolicies.ts"],"names":[],"mappings":"AAIA;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAChC,MAGC;IAED,OAAO;QACL,aAAa,EAAE,MAAM,CAAC,aAAa;QACnC,WAAW,EAAE,MAAM,CAAC,WAAW;QAC/B,OAAO,EAAE,MAAM,CAAC,OAAO;QACvB,SAAS,EAAE,MAAM,CAAC,SAAS;KAC5B,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,MAGC;IAED,OAAO;QACL,MAAM,CAAC,aAAa;QACpB,MAAM,CAAC,WAAW;QAClB,MAAM,CAAC,OAAO;QACd,MAAM,CAAC,QAAQ;QACf,MAAM,CAAC,SAAS;KACjB,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;AACd,CAAC;AAED,MAAM,UAAU,uBAAuB,CAErC,QAAsB;IACtB,MAAM,aAAa,GAAG,IAAI,GAAG,EAAa,CAAC;IAE3C,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE,CAAC;QAC9B,aAAa,CAAC,GAAG,CAAC,kBAAkB,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,CAAC;IACxD,CAAC;IAED,OAAO,CAAC,GAAG,aAAa,CAAC,MAAM,EAAE,CAAC,CAAC;AACrC,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyRef } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principalContracts/principalPolicyEvidence\";\n\n/**\n * The head a container mutation cites for a policy it was planned against.\n * The API authorizes from its own verified copy of that head, so the policy\n * itself never travels.\n */\nexport function principalPolicyRef(\n policy: Pick<\n VerifiedPrincipalPolicy,\n \"principalId\" | \"principalType\" | \"stateHash\" | \"version\"\n >,\n): PrincipalPolicyRef {\n return {\n principalType: policy.principalType,\n principalId: policy.principalId,\n version: policy.version,\n stateHash: policy.stateHash,\n };\n}\n\nfunction principalPolicyKey(\n policy: Pick<\n VerifiedPrincipalPolicy,\n \"keyEpoch\" | \"principalId\" | \"principalType\" | \"stateHash\" | \"version\"\n >,\n): string {\n return [\n policy.principalType,\n policy.principalId,\n policy.version,\n policy.keyEpoch,\n policy.stateHash,\n ].join(\":\");\n}\n\nexport function uniquePrincipalPolicies<\n T extends PrincipalPolicyCurrentEvidence,\n>(policies: readonly T[]): T[] {\n const policiesByKey = new Map<string, T>();\n\n for (const policy of policies) {\n policiesByKey.set(principalPolicyKey(policy), policy);\n }\n\n return [...policiesByKey.values()];\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { AccessEvent, AccessManifest, ContainerAccessManifestState, ContainerCreateAccessEventBody, ContainerDirectGrant, ContainerGrantAccessEventBody, ContainerGrantPrincipalHead, ContainerKekKeyring, ContainerKekRecipientTarget, ContainerKeyEpoch, ContainerKeyWrap, ContainerMoveAccessEventBody, ContainerRekeyAccessEventBody, ContainerRevokeAccessEventBody, ContainerUserRecipientKey } from "../../../internal/crypto/index.js";
2
2
  import type { AccessManifestBundleWire, ContainerCreateWithMetadataDocumentRequest, ContainerMutationRequest, ContainerRotationRequest } from "../../../internal/validators/request/index.js";
3
3
  import type { ContainerCreateWithMetadataDocumentResponse, ContainerKekResponse, ContainerMutationResponse, ContainerRotationResponse, ContainerWriterProjectionResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
4
- import type { PrincipalPolicyCurrentEvidence } from "../../principals/principalPolicyEvidence.js";
4
+ import type { PrincipalPolicyCurrentEvidence } from "../../principalContracts/principalPolicyEvidence.js";
5
5
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
6
6
  import type { ContainerMutationRequestOptions } from "./mutationRequestOptions.js";
7
7
  import type { ContainerReciteApi } from "./reciteApi.js";
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerCreateAccessEventBody,\n ContainerDirectGrant,\n ContainerGrantAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKekKeyring,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerMoveAccessEventBody,\n ContainerRekeyAccessEventBody,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerCreateWithMetadataDocumentRequest,\n ContainerMutationRequest,\n ContainerRotationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerKekResponse,\n ContainerMutationResponse,\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { ContainerMutationRequestOptions } from \"./mutationRequestOptions\";\nimport type { ContainerReciteApi } from \"./reciteApi\";\n\nexport interface ContainerMutationAuthor {\n organizationId: string;\n signerDeviceId: string;\n signerKeyFingerprint: string;\n signerPrivateKey: Uint8Array;\n signerUserId: string;\n}\n\nexport interface BuildContainerCreatePlanInput {\n author: ContainerMutationAuthor;\n containerId?: string | undefined;\n containerKey: Uint8Array;\n containerKeyEpochId?: string | undefined;\n eventId?: string | undefined;\n /**\n * Optional group grant to bake into the\n * create manifest, wrapping the new container key to that principal in\n * addition to the normal parent-inheritance wrap. Used to birth a child\n * container that is directly readable by a group — e.g. the org public\n * metadata container granted to the reserved Members group. The principal's\n * verified policy must also be supplied via `principalPolicies` so the server\n * can derive the recipient target.\n */\n managedPrincipalGrant?:\n | {\n accessLevel: ContainerDirectGrant[\"accessLevel\"];\n principalEncapsulationPublicKey: string;\n principalHead: ContainerGrantPrincipalHead;\n }\n | undefined;\n metadataDocumentId?: string | undefined;\n systemSlot?: string | null | undefined;\n parentProjection: ContainerWriterProjectionResponse;\n principalPolicies?: readonly PrincipalPolicyCurrentEvidence[] | undefined;\n signedAt?: string | undefined;\n}\n\nexport interface ContainerCreatePlan {\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyEpochHash: string;\n keyTargetHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n metadataDocumentId: string;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargets: ContainerKekRecipientTarget[];\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerCreatePlan {\n containerKey: Uint8Array;\n plan: ContainerCreatePlan;\n}\n\nexport interface ContainerCreatePlanContext\n extends BuildContainerCreatePlanInput {\n containerKeyPublicKey: string;\n containerId: string;\n containerKeyEpochId: string;\n eventId: string;\n metadataDocumentId: string;\n parent: ParentContainerCreateContext;\n signedAt: string;\n}\n\nexport interface ContainerMutationSubmitFailure {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report: () => void;\n readonly stalePrincipalHeads?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n readonly status: number | null;\n}\n\nexport type ContainerMutationSubmitResult<T> =\n | {\n readonly data: T;\n readonly ok: true;\n }\n | ContainerMutationSubmitFailure;\n\nexport interface ContainerCreateApi {\n createContainerResult(\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n createContainerWithMetadataDocumentResult(\n input: ContainerCreateWithMetadataDocumentRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<\n ContainerMutationSubmitResult<ContainerCreateWithMetadataDocumentResponse>\n >;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport interface ContainerShareApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n shareContainer(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationResponse | null>;\n /** Tells a stale path, which a fresh projection clears, from a refusal. */\n shareContainerResult?(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n evictContainerWriterProjection?(containerId: string): void;\n}\n\n/**\n * A status-bearing rotation outcome. A refusal that names\n * `requiredContainerIds` is answerable: sign those descendant rekeys and\n * resubmit with them carried.\n */\nexport type ContainerRotationResult =\n | { readonly ok: true; readonly data: ContainerRotationResponse }\n | {\n readonly ok: false;\n readonly code?: string | undefined;\n /** Surface a failure that was submitted with `reportErrors: false`. */\n readonly report?: (() => void) | undefined;\n readonly requiredContainerIds?: readonly string[] | undefined;\n readonly status: number | null;\n };\n\nexport interface ContainerMoveApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n moveContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n moveContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerRevokeApi extends ContainerReciteApi {\n evictContainerWriterProjection?(containerId: string): void;\n evictWriterProjectionsCiting?(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n revokeContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n revokeContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface CreateRemoteContainerResult {\n containerKey: Uint8Array;\n containerId: string;\n metadataDocumentId: string;\n plan: ContainerCreatePlan;\n response: ContainerMutationResponse;\n}\n\nexport interface ContainerSharePlan {\n body: ContainerGrantAccessEventBody;\n /** The unchanged epoch's stored keyring, echoed back by the server. */\n previousKeyring?: Record<string, unknown> | null | undefined;\n containerId: string;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n recipientTarget: ContainerKekRecipientTarget;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerSharePlan {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n}\n\nexport interface ContainerRevokePlan {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRevokePlan {\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n}\n\nexport interface ContainerRekeyPlan {\n body: ContainerRekeyAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRekeyPlan {\n containerKey: Uint8Array;\n plan: ContainerRekeyPlan;\n writerProjection: ContainerWriterProjectionResponse;\n}\n\nexport interface ContainerRekeyApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n rekeyContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; see DocumentSyncApi. */\n rekeyContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerMovePlan {\n body: ContainerMoveAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerMovePlan {\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n}\n\nexport interface BuildMaterializedContainerMovePlanInput {\n author: ContainerMutationAuthor;\n containerKeyEpochId?: string | undefined;\n destinationParentProjection: ContainerWriterProjectionResponse;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\nexport interface ParentContainerCreateContext {\n manifest: ContainerWriterProjectionResponse[\"path\"][number];\n kek: ContainerKekResponse;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n AccessEvent,\n AccessManifest,\n ContainerAccessManifestState,\n ContainerCreateAccessEventBody,\n ContainerDirectGrant,\n ContainerGrantAccessEventBody,\n ContainerGrantPrincipalHead,\n ContainerKekKeyring,\n ContainerKekRecipientTarget,\n ContainerKeyEpoch,\n ContainerKeyWrap,\n ContainerMoveAccessEventBody,\n ContainerRekeyAccessEventBody,\n ContainerRevokeAccessEventBody,\n ContainerUserRecipientKey,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWire,\n ContainerCreateWithMetadataDocumentRequest,\n ContainerMutationRequest,\n ContainerRotationRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerCreateWithMetadataDocumentResponse,\n ContainerKekResponse,\n ContainerMutationResponse,\n ContainerRotationResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { ContainerMutationRequestOptions } from \"./mutationRequestOptions\";\nimport type { ContainerReciteApi } from \"./reciteApi\";\n\nexport interface ContainerMutationAuthor {\n organizationId: string;\n signerDeviceId: string;\n signerKeyFingerprint: string;\n signerPrivateKey: Uint8Array;\n signerUserId: string;\n}\n\nexport interface BuildContainerCreatePlanInput {\n author: ContainerMutationAuthor;\n containerId?: string | undefined;\n containerKey: Uint8Array;\n containerKeyEpochId?: string | undefined;\n eventId?: string | undefined;\n /**\n * Optional group grant to bake into the\n * create manifest, wrapping the new container key to that principal in\n * addition to the normal parent-inheritance wrap. Used to birth a child\n * container that is directly readable by a group — e.g. the org public\n * metadata container granted to the reserved Members group. The principal's\n * verified policy must also be supplied via `principalPolicies` so the server\n * can derive the recipient target.\n */\n managedPrincipalGrant?:\n | {\n accessLevel: ContainerDirectGrant[\"accessLevel\"];\n principalEncapsulationPublicKey: string;\n principalHead: ContainerGrantPrincipalHead;\n }\n | undefined;\n metadataDocumentId?: string | undefined;\n systemSlot?: string | null | undefined;\n parentProjection: ContainerWriterProjectionResponse;\n principalPolicies?: readonly PrincipalPolicyCurrentEvidence[] | undefined;\n signedAt?: string | undefined;\n}\n\nexport interface ContainerCreatePlan {\n body: ContainerCreateAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyEpochHash: string;\n keyTargetHash: string;\n manifest: AccessManifest;\n manifestHash: string;\n metadataDocumentId: string;\n parentContainerId: string | null;\n parentManifestHash: string | null;\n recipientTargets: ContainerKekRecipientTarget[];\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerCreatePlan {\n containerKey: Uint8Array;\n plan: ContainerCreatePlan;\n}\n\nexport interface ContainerCreatePlanContext\n extends BuildContainerCreatePlanInput {\n containerKeyPublicKey: string;\n containerId: string;\n containerKeyEpochId: string;\n eventId: string;\n metadataDocumentId: string;\n parent: ParentContainerCreateContext;\n signedAt: string;\n}\n\nexport interface ContainerMutationSubmitFailure {\n readonly code?: string | undefined;\n readonly message: string;\n readonly ok: false;\n readonly report: () => void;\n readonly stalePrincipalHeads?:\n | readonly ReferencedPrincipalStateResponse[]\n | undefined;\n readonly status: number | null;\n}\n\nexport type ContainerMutationSubmitResult<T> =\n | {\n readonly data: T;\n readonly ok: true;\n }\n | ContainerMutationSubmitFailure;\n\nexport interface ContainerCreateApi {\n createContainerResult(\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n createContainerWithMetadataDocumentResult(\n input: ContainerCreateWithMetadataDocumentRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<\n ContainerMutationSubmitResult<ContainerCreateWithMetadataDocumentResponse>\n >;\n evictContainerWriterProjection(containerId: string): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport interface ContainerShareApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n shareContainer(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationResponse | null>;\n /** Tells a stale path, which a fresh projection clears, from a refusal. */\n shareContainerResult?(\n containerId: string,\n input: ContainerMutationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerMutationSubmitResult<ContainerMutationResponse>>;\n evictContainerWriterProjection?(containerId: string): void;\n}\n\n/**\n * A status-bearing rotation outcome. A refusal that names\n * `requiredContainerIds` is answerable: sign those descendant rekeys and\n * resubmit with them carried.\n */\nexport type ContainerRotationResult =\n | { readonly ok: true; readonly data: ContainerRotationResponse }\n | {\n readonly ok: false;\n readonly code?: string | undefined;\n /** Surface a failure that was submitted with `reportErrors: false`. */\n readonly report?: (() => void) | undefined;\n readonly requiredContainerIds?: readonly string[] | undefined;\n readonly status: number | null;\n };\n\nexport interface ContainerMoveApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n moveContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n moveContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerRevokeApi extends ContainerReciteApi {\n evictContainerWriterProjection?(containerId: string): void;\n evictWriterProjectionsCiting?(containerIds: readonly string[]): void;\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n revokeContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; without it nothing can be carried. */\n revokeContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface CreateRemoteContainerResult {\n containerKey: Uint8Array;\n containerId: string;\n metadataDocumentId: string;\n plan: ContainerCreatePlan;\n response: ContainerMutationResponse;\n}\n\nexport interface ContainerSharePlan {\n body: ContainerGrantAccessEventBody;\n /** The unchanged epoch's stored keyring, echoed back by the server. */\n previousKeyring?: Record<string, unknown> | null | undefined;\n containerId: string;\n event: AccessEvent;\n eventHash: string;\n grant: ContainerDirectGrant;\n keyEpoch: ContainerKeyEpoch;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n recipientTarget: ContainerKekRecipientTarget;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerSharePlan {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n}\n\nexport interface ContainerRevokePlan {\n body: ContainerRevokeAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRevokePlan {\n containerKey: Uint8Array;\n plan: ContainerRevokePlan;\n}\n\nexport interface ContainerRekeyPlan {\n body: ContainerRekeyAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n userRecipientKeys: ContainerUserRecipientKey[];\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerRekeyPlan {\n containerKey: Uint8Array;\n plan: ContainerRekeyPlan;\n writerProjection: ContainerWriterProjectionResponse;\n}\n\nexport interface ContainerRekeyApi extends ContainerReciteApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n rekeyContainer(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResponse | null>;\n /** Optional status-bearing variant; see DocumentSyncApi. */\n rekeyContainerResult?(\n containerId: string,\n input: ContainerRotationRequest,\n options?: ContainerMutationRequestOptions,\n ): Promise<ContainerRotationResult>;\n}\n\nexport interface ContainerMovePlan {\n body: ContainerMoveAccessEventBody;\n containerId: string;\n containerKeyEpochId: string;\n event: AccessEvent;\n eventHash: string;\n keyEpoch: ContainerKeyEpoch;\n keyring: ContainerKekKeyring;\n manifest: AccessManifest;\n manifestHash: string;\n previousManifest: AccessManifestBundleWire;\n request: ContainerMutationRequest;\n state: ContainerAccessManifestState;\n wraps: ContainerKeyWrap[];\n}\n\nexport interface MaterializedContainerMovePlan {\n containerKey: Uint8Array;\n plan: ContainerMovePlan;\n}\n\nexport interface BuildMaterializedContainerMovePlanInput {\n author: ContainerMutationAuthor;\n containerKeyEpochId?: string | undefined;\n destinationParentProjection: ContainerWriterProjectionResponse;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection: ContainerWriterProjectionResponse;\n signedAt?: string | undefined;\n targetSecretKey: Uint8Array;\n}\n\nexport interface ParentContainerCreateContext {\n manifest: ContainerWriterProjectionResponse[\"path\"][number];\n kek: ContainerKekResponse;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"accessManifestCheckpointEnforcement.js","sourceRoot":"","sources":["accessManifestCheckpointEnforcement.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAK5G,SAAS,SAAS,CAAC,QAAkD;IACnE,MAAM,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,EAAE,GAAG,QAAQ,CAAC,UAAU,CAAC;IACrE,OAAO,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,EAAE,cAAc,EAAE,QAAQ,CAAC,CAAC,CAAC;AAChE,CAAC;AAED,SAAS,iBAAiB,CACxB,SAA8D;IAE9D,MAAM,QAAQ,GAAG,IAAI,GAA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AK,IAAI,CAAC,YAAY,CAAC,CAAC;QACpE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;IACxC,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iCAAiC,CAAC,KAUvD;IACC,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,mCAAmC,CAAC;QACpC,MAAM,EAAE,gCAAgC,CAAC,KAAK,CAAC;QAC/C,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,eAAe,EAAE,KAAK,CAAC,eAAe;KACvC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAYtD;IACC,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,kCAAkC,CAAC;QACnC,MAAM,EAAE,gCAAgC,CAAC,KAAK,CAAC;QAC/C,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;QACtD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,eAAe,EAAE,KAAK,CAAC,eAAe;KACvC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport type { AccessManifestCheckpointAdvance } from \"../../persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nfunction objectKey(manifest: VerifiedAccessManifestCheckpointEvidence): string {\n const { objectKind, organizationId, objectId } = manifest.checkpoint;\n return JSON.stringify([objectKind, organizationId, objectId]);\n}\n\nfunction manifestsByObject(\n manifests: readonly VerifiedAccessManifestCheckpointEvidence[],\n): Map<string, Map<string, VerifiedAccessManifestCheckpointEvidence>> {\n const byObject = new Map<\n string,\n Map<string, VerifiedAccessManifestCheckpointEvidence>\n >();\n for (const manifest of manifests) {\n const key = objectKey(manifest);\n let byHash = byObject.get(key);\n if (!byHash) {\n byHash = new Map();\n byObject.set(key, byHash);\n }\n byHash.set(manifest.manifestHash, manifest);\n }\n return byObject;\n}\n\nfunction accessManifestCheckpointAdvances(input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): AccessManifestCheckpointAdvance[] {\n const evidenceByObject = manifestsByObject(input.verifiedManifests);\n const headsByObject = manifestsByObject(input.verifiedHeads);\n const advances: AccessManifestCheckpointAdvance[] = [];\n\n for (const [key, headsByHash] of headsByObject) {\n if (headsByHash.size !== 1) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares conflicting access manifest heads for ${key}`,\n );\n }\n const head = headsByHash.values().next().value;\n if (!head) {\n continue;\n }\n const predecessors = [\n ...(evidenceByObject.get(key)?.values() ?? []),\n ].filter((manifest) => manifest.manifestHash !== head.manifestHash);\n advances.push({ head, predecessors });\n }\n\n return advances;\n}\n\nexport async function validateAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n policies: input.policies,\n authorizationPolicies: input.authorizationPolicies,\n stillCurrent: input.stillCurrent,\n verifiedBundles: input.verifiedBundles,\n });\n}\n\nexport async function enforceAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n documentPurgeCheckpoint: input.documentPurgeCheckpoint,\n organizationId: input.organizationId,\n policies: input.policies,\n authorizationPolicies: input.authorizationPolicies,\n stillCurrent: input.stillCurrent,\n verifiedBundles: input.verifiedBundles,\n });\n}\n"]}
1
+ {"version":3,"file":"accessManifestCheckpointEnforcement.js","sourceRoot":"","sources":["accessManifestCheckpointEnforcement.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAK5G,SAAS,SAAS,CAAC,QAAkD;IACnE,MAAM,EAAE,UAAU,EAAE,cAAc,EAAE,QAAQ,EA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S;QACX,CAAC;QACD,MAAM,YAAY,GAAG;YACnB,GAAG,CAAC,gBAAgB,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC;SAC/C,CAAC,MAAM,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,YAAY,KAAK,IAAI,CAAC,YAAY,CAAC,CAAC;QACpE,QAAQ,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;IACxC,CAAC;IAED,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,iCAAiC,CAAC,KAUvD;IACC,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,mCAAmC,CAAC;QACpC,MAAM,EAAE,gCAAgC,CAAC,KAAK,CAAC;QAC/C,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,eAAe,EAAE,KAAK,CAAC,eAAe;KACvC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CAAC,KAYtD;IACC,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,kCAAkC,CAAC;QACnC,MAAM,EAAE,gCAAgC,CAAC,KAAK,CAAC;QAC/C,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;QACtD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,qBAAqB,EAAE,KAAK,CAAC,qBAAqB;QAClD,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,eAAe,EAAE,KAAK,CAAC,eAAe;KACvC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport type { AccessManifestCheckpointAdvance } from \"../../persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\nfunction objectKey(manifest: VerifiedAccessManifestCheckpointEvidence): string {\n const { objectKind, organizationId, objectId } = manifest.checkpoint;\n return JSON.stringify([objectKind, organizationId, objectId]);\n}\n\nfunction manifestsByObject(\n manifests: readonly VerifiedAccessManifestCheckpointEvidence[],\n): Map<string, Map<string, VerifiedAccessManifestCheckpointEvidence>> {\n const byObject = new Map<\n string,\n Map<string, VerifiedAccessManifestCheckpointEvidence>\n >();\n for (const manifest of manifests) {\n const key = objectKey(manifest);\n let byHash = byObject.get(key);\n if (!byHash) {\n byHash = new Map();\n byObject.set(key, byHash);\n }\n byHash.set(manifest.manifestHash, manifest);\n }\n return byObject;\n}\n\nfunction accessManifestCheckpointAdvances(input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): AccessManifestCheckpointAdvance[] {\n const evidenceByObject = manifestsByObject(input.verifiedManifests);\n const headsByObject = manifestsByObject(input.verifiedHeads);\n const advances: AccessManifestCheckpointAdvance[] = [];\n\n for (const [key, headsByHash] of headsByObject) {\n if (headsByHash.size !== 1) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares conflicting access manifest heads for ${key}`,\n );\n }\n const head = headsByHash.values().next().value;\n if (!head) {\n continue;\n }\n const predecessors = [\n ...(evidenceByObject.get(key)?.values() ?? []),\n ].filter((manifest) => manifest.manifestHash !== head.manifestHash);\n advances.push({ head, predecessors });\n }\n\n return advances;\n}\n\nexport async function validateAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n policies: input.policies,\n authorizationPolicies: input.authorizationPolicies,\n stillCurrent: input.stillCurrent,\n verifiedBundles: input.verifiedBundles,\n });\n}\n\nexport async function enforceAccessManifestCheckpoints(input: {\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly policies: readonly PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedBundles?: readonly VerifiedManifestBundle[] | undefined;\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n}): Promise<void> {\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: accessManifestCheckpointAdvances(input),\n documentPurgeCheckpoint: input.documentPurgeCheckpoint,\n organizationId: input.organizationId,\n policies: input.policies,\n authorizationPolicies: input.authorizationPolicies,\n stillCurrent: input.stillCurrent,\n verifiedBundles: input.verifiedBundles,\n });\n}\n"]}
@@ -2,7 +2,7 @@ import { type AccessManifestCheckpoint, type VerifiedAccessManifestCheckpointEvi
2
2
  import { type AccessManifestBundleWireResponse, type ContainerKeyingPathResponse } from "../../../internal/validators/response/index.js";
3
3
  import type { DocumentPurgeCheckpoint } from "../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence.js";
4
4
  import type { VerifiedManifestBundle } from "../../persistence/verifiedManifestBundlePersistence.js";
5
- import type { PrincipalPolicyCheckpointEvidence } from "../../principals/principalPolicyEvidence.js";
5
+ import type { PrincipalPolicyCheckpointEvidence } from "../../principalContracts/principalPolicyEvidence.js";
6
6
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
7
7
  import { type OpenPrincipalPolicyBundleReader } from "../types.js";
8
8
  export interface ProjectionCheckpointContext {
@@ -1 +1 @@
1
- {"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAE5F,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAGzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EACL,mCAAmC,GAEpC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAmBnE,MAAM,UAAU,iCAAiC,CAAC,KAIjD;IACC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,oEAAoE,CACrE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,kBAAkB,EAAE,EAAE;QACtB,OAAO,EAAE,KAAK,CAA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O,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n} from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // The caller's principal policy bundle store, opened per executor.\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
1
+ {"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,8BAA8B,EAAE,MAAM,4CAA4C,CAAC;AAE5F,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAGzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,oCAAoC,CAAC;AAE1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AACjE,OAAO,EACL,mCAAmC,GAEpC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,gCAAgC,EAChC,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,0BAA0B,EAAE,MAAM,uBAAuB,CAAC;AAmBnE,MAAM,UAAU,iCAAiC,CAAC,KAIjD;IACC,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,UAAU,EAAE,CAAC;QACxC,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,oEAAoE,CACrE,CAAC;IACJ,CAAC;IAED,OAAO;QACL,kBAAkB,EAAE,EAAE;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,+BAA+B,EAAE,KAAK,CAAC,+BAA+B;QACtE,gBAAgB,EAAE,IAAI,GAAG,EAAE;QAC3B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,QAAQ,EAAE,EAAE;QACZ,qBAAqB,EAAE,EAAE;QACzB,eAAe,EAAE,EAAE;QACnB,aAAa,EAAE,EAAE;QACjB,iBAAiB,EAAE,EAAE;KACtB,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,OAAoC,EACpC,KAGC;IAED,OA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,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { rememberVerifiedContainerHeads } from \"../../containers/shared/heldContainerHeads\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n} from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // The caller's principal policy bundle store, opened per executor.\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { PrincipalPolicyAuthorization } from "../../../internal/crypto/index.js";
2
2
  import { type VerifiedContainerAccessManifest } from "../../../internal/crypto/index.js";
3
3
  import type { AccessManifestBundleWireResponse, ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
4
- import type { PrincipalPolicyCurrentEvidence } from "../../principals/principalPolicyEvidence.js";
4
+ import type { PrincipalPolicyCurrentEvidence } from "../../principalContracts/principalPolicyEvidence.js";
5
5
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
6
6
  import { type ProjectionCheckpointContext } from "../checkpoints/checkpointContext.js";
7
7
  import type { OpenPrincipalPolicyBundleReader, PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";