@tearleads/client-sdk 0.1.225 → 0.1.230

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 (375) hide show
  1. package/Tearleads.js +1 -1
  2. package/Tearleads.js.map +1 -1
  3. package/client/containerContents/documentDiscovery.js +4 -1
  4. package/client/containerContents/documentDiscovery.js.map +1 -1
  5. package/client/containerContents/index.d.ts +1 -1
  6. package/client/containerContents/index.js +4 -2
  7. package/client/containerContents/index.js.map +1 -1
  8. package/client/deviceFirst/index.js +1 -1
  9. package/client/deviceFirst/index.js.map +1 -1
  10. package/client/documents/index.js +6 -2
  11. package/client/documents/index.js.map +1 -1
  12. package/client/identity/index.js +1 -1
  13. package/client/identity/index.js.map +1 -1
  14. package/client/identity/userIdentities.d.ts +1 -1
  15. package/client/identity/userIdentities.js +1 -1
  16. package/client/identity/userIdentities.js.map +1 -1
  17. package/client/index.d.ts +2 -0
  18. package/client/index.js +2 -0
  19. package/client/index.js.map +1 -1
  20. package/client/organizations/index.js +1 -1
  21. package/client/organizations/index.js.map +1 -1
  22. package/client/organizations/organizationMemberships.d.ts +1 -1
  23. package/client/organizations/organizationMemberships.js +1 -1
  24. package/client/organizations/organizationMemberships.js.map +1 -1
  25. package/client/organizations/principalContainerMutations.js.map +1 -1
  26. package/client/organizations/principalMutations.js +1 -1
  27. package/client/organizations/principalMutations.js.map +1 -1
  28. package/client/organizations/recipientAdmission.d.ts +1 -1
  29. package/client/organizations/recipientAdmission.js +2 -2
  30. package/client/organizations/recipientAdmission.js.map +1 -1
  31. package/client/organizations/rosterAdmissionEvidence.js +1 -1
  32. package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
  33. package/client/runtime/apiVersion.js +1 -1
  34. package/client/runtime/apiVersion.js.map +1 -1
  35. package/client/runtime/containerContentsRuntime.d.ts +8 -0
  36. package/client/runtime/containerContentsRuntime.js +14 -0
  37. package/client/runtime/containerContentsRuntime.js.map +1 -0
  38. package/client/runtime/database.js +1 -1
  39. package/client/runtime/database.js.map +1 -1
  40. package/client/runtime/documentsRuntime.d.ts +5 -0
  41. package/client/runtime/documentsRuntime.js +10 -0
  42. package/client/runtime/documentsRuntime.js.map +1 -0
  43. package/client/runtime/events.js +1 -1
  44. package/client/runtime/events.js.map +1 -1
  45. package/client/runtime/network.js +1 -1
  46. package/client/runtime/network.js.map +1 -1
  47. package/client/runtime/runtimeIdentityResolution.js +1 -1
  48. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  49. package/client/runtime/syncBillingGate.js +1 -1
  50. package/client/runtime/syncBillingGate.js.map +1 -1
  51. package/client/runtime/workflowRuntime.d.ts +5 -2
  52. package/client/runtime/workflowRuntime.js +6 -2
  53. package/client/runtime/workflowRuntime.js.map +1 -1
  54. package/client/securityIncidents/index.d.ts +1 -1
  55. package/client/securityIncidents/index.js +2 -2
  56. package/client/securityIncidents/index.js.map +1 -1
  57. package/client/session/index.js +1 -1
  58. package/client/session/index.js.map +1 -1
  59. package/client/session/sessionLoginRefusal.js +1 -1
  60. package/client/session/sessionLoginRefusal.js.map +1 -1
  61. package/client/session/sessionRootAuthority.js +1 -1
  62. package/client/session/sessionRootAuthority.js.map +1 -1
  63. package/data/containers/shared/authorAccess.d.ts +1 -1
  64. package/data/containers/shared/authorAccess.js.map +1 -1
  65. package/data/containers/shared/principalPolicies.js.map +1 -1
  66. package/data/containers/shared/types.d.ts +1 -1
  67. package/data/containers/shared/types.js.map +1 -1
  68. package/data/documents/shared/projection/freshProjectionRetry.js +1 -1
  69. package/data/documents/shared/projection/freshProjectionRetry.js.map +1 -1
  70. package/data/keyingProjectionVerification/checkpoints/accessManifestCheckpointEnforcement.js.map +1 -1
  71. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +1 -1
  72. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
  73. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  74. package/data/keyingProjectionVerification/checkpoints/heldContainerHeads.js.map +1 -0
  75. package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +1 -1
  76. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  77. package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js +1 -1
  78. package/data/keyingProjectionVerification/documentPurge/documentPurgePrincipalEvidence.js.map +1 -1
  79. package/data/keyingProjectionVerification/error.js +1 -57
  80. package/data/keyingProjectionVerification/error.js.map +1 -1
  81. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js +1 -1
  82. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.js.map +1 -1
  83. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +2 -2
  84. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  85. package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js +2 -2
  86. package/data/keyingProjectionVerification/principalPolicy/principalPolicySigners.js.map +1 -1
  87. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.d.ts +1 -1
  88. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +4 -4
  89. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  90. package/data/keyingProjectionVerification/types.d.ts +1 -1
  91. package/data/keyingProjectionVerification/types.js.map +1 -1
  92. package/data/persistence/container-contents/documentContainerProjectionPersistence.d.ts +6 -2
  93. package/data/persistence/container-contents/documentContainerProjectionPersistence.js +10 -1
  94. package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
  95. package/data/persistence/documents/documentDeletionPort.d.ts +28 -0
  96. package/data/persistence/documents/documentDeletionPort.js +2 -0
  97. package/data/persistence/documents/documentDeletionPort.js.map +1 -0
  98. package/data/persistence/documents/documentsPersistence.d.ts +1 -0
  99. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  100. package/data/persistence/documents/internal/documentDeletionPersistence.js +7 -7
  101. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  102. package/data/persistence/documents/types.d.ts +2 -15
  103. package/data/persistence/documents/types.js.map +1 -1
  104. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +1 -1
  105. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
  106. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +1 -1
  107. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  108. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js +1 -1
  109. package/data/persistence/keyingCheckpoints/organizationReplacementCheckpointPersistence.js.map +1 -1
  110. package/data/persistence/organizationFounderPersistence.js +1 -1
  111. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  112. package/data/persistence/principalCurrentAcknowledgementPersistence.js +1 -1
  113. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  114. package/data/persistence/principalPolicy/heldPrincipalState.js +1 -1
  115. package/data/persistence/principalPolicy/heldPrincipalState.js.map +1 -1
  116. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +1 -1
  117. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -1
  118. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
  119. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js +1 -1
  120. package/data/persistence/principalPolicy/principalPolicyReferenceCheckpoint.js.map +1 -1
  121. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js +1 -1
  122. package/data/persistence/principalPolicy/principalPolicyReferenceIndexPersistence.js.map +1 -1
  123. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js +1 -1
  124. package/data/persistence/principalPolicy/principalPolicyReferencePersistence.js.map +1 -1
  125. package/data/principals/organizationGroupRoles.js +1 -1
  126. package/data/principals/organizationGroupRoles.js.map +1 -1
  127. package/data/shared/securityIncidents.d.ts +18 -1
  128. package/data/shared/securityIncidents.js +58 -1
  129. package/data/shared/securityIncidents.js.map +1 -1
  130. package/index.d.ts +5 -5
  131. package/index.js +3 -3
  132. package/index.js.map +1 -1
  133. package/package.json +1 -1
  134. package/stores/container-contents/hydration/backgroundHydration.js +1 -1
  135. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
  136. package/stores/container-contents/operations/reportShareFailure.js +1 -1
  137. package/stores/container-contents/operations/reportShareFailure.js.map +1 -1
  138. package/stores/container-contents/operations/shareOperations.js +1 -1
  139. package/stores/container-contents/operations/shareOperations.js.map +1 -1
  140. package/stores/container-contents/systemContainers/systemContainerHydration.js +1 -1
  141. package/stores/container-contents/systemContainers/systemContainerHydration.js.map +1 -1
  142. package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js +1 -1
  143. package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js.map +1 -1
  144. package/stores/documents/documentStore/persistence.js +1 -0
  145. package/stores/documents/documentStore/persistence.js.map +1 -1
  146. package/stores/documents/documentStore/sync/index.js +1 -1
  147. package/stores/documents/documentStore/sync/index.js.map +1 -1
  148. package/stores/documents/documentStore/sync/syncRequest.js +1 -0
  149. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  150. package/workflows/blobs/hydration/hydrationResults.js +2 -1
  151. package/workflows/blobs/hydration/hydrationResults.js.map +1 -1
  152. package/workflows/blobs/verification/attachmentDecryptor.js +1 -1
  153. package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -1
  154. package/workflows/container-contents/container-state/create/createAdoption.js +1 -1
  155. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  156. package/workflows/container-contents/container-state/create/createIntentSync.js +1 -1
  157. package/workflows/container-contents/container-state/create/createIntentSync.js.map +1 -1
  158. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -1
  159. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  160. package/workflows/container-contents/container-state/organizationHost.d.ts +54 -0
  161. package/workflows/container-contents/container-state/organizationHost.js +2 -0
  162. package/workflows/container-contents/container-state/organizationHost.js.map +1 -0
  163. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -1
  164. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  165. package/workflows/container-contents/container-state/remote.js +2 -4
  166. package/workflows/container-contents/container-state/remote.js.map +1 -1
  167. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
  168. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  169. package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -2
  170. package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
  171. package/workflows/container-contents/container-state/types.js.map +1 -1
  172. package/workflows/container-contents/documentLinks/index.js +1 -1
  173. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  174. package/workflows/container-contents/documentMove/documentMoveIntentSync.js +1 -1
  175. package/workflows/container-contents/documentMove/documentMoveIntentSync.js.map +1 -1
  176. package/workflows/container-contents/index.d.ts +1 -0
  177. package/workflows/container-contents/index.js.map +1 -1
  178. package/workflows/container-contents/info/documentInfo.d.ts +1 -1
  179. package/workflows/container-contents/info/documentInfo.js +1 -1
  180. package/workflows/container-contents/info/documentInfo.js.map +1 -1
  181. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  182. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  183. package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js +1 -2
  184. package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js.map +1 -1
  185. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +3 -4
  186. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  187. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +1 -1
  188. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  189. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  190. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  191. package/workflows/container-contents/runtime.d.ts +5 -0
  192. package/workflows/container-contents/runtime.js +3 -0
  193. package/workflows/container-contents/runtime.js.map +1 -1
  194. package/workflows/container-contents/syncPause/documentRemoval.js +2 -0
  195. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
  196. package/workflows/container-contents/tombstones/documentPurge.js +5 -2
  197. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  198. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +1 -1
  199. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  200. package/workflows/containers/child/create/index.js.map +1 -1
  201. package/workflows/containers/child/move/moveRequest.js.map +1 -1
  202. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  203. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  204. package/workflows/containers/child/mutationSubmit.d.ts +1 -1
  205. package/workflows/containers/child/mutationSubmit.js +1 -1
  206. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  207. package/workflows/containers/child/recite.js +1 -1
  208. package/workflows/containers/child/recite.js.map +1 -1
  209. package/workflows/containers/child/recitePlan.js.map +1 -1
  210. package/workflows/containers/child/rekey/carriedDescendantRekeys.d.ts +1 -1
  211. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
  212. package/workflows/containers/child/rekey/index.d.ts +1 -1
  213. package/workflows/containers/child/rekey/index.js.map +1 -1
  214. package/workflows/containers/child/revoke.d.ts +1 -1
  215. package/workflows/containers/child/revoke.js.map +1 -1
  216. package/workflows/containers/child/rotation/replacementPrincipalPolicyReferences.js.map +1 -1
  217. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
  218. package/workflows/containers/child/rotation/rotationWraps.js.map +1 -1
  219. package/workflows/containers/child/share/sharePlanCore.d.ts +1 -1
  220. package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
  221. package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js +1 -1
  222. package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js.map +1 -1
  223. package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js +1 -1
  224. package/workflows/containers/rematerialization/authoredPrincipalPolicyWarmer.js.map +1 -1
  225. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  226. package/workflows/containers/rematerialization/principalContainerRematerializationTargets.js.map +1 -1
  227. package/workflows/documents/documentMutationCommit.d.ts +2 -1
  228. package/workflows/documents/documentMutationCommit.js +1 -0
  229. package/workflows/documents/documentMutationCommit.js.map +1 -1
  230. package/workflows/documents/documentPersistGuards.js +2 -1
  231. package/workflows/documents/documentPersistGuards.js.map +1 -1
  232. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  233. package/workflows/documents/purge/persistedDocumentRemoval.d.ts +2 -1
  234. package/workflows/documents/purge/persistedDocumentRemoval.js +2 -2
  235. package/workflows/documents/purge/persistedDocumentRemoval.js.map +1 -1
  236. package/workflows/documents/runtime.d.ts +5 -0
  237. package/workflows/documents/runtime.js +1 -0
  238. package/workflows/documents/runtime.js.map +1 -1
  239. package/workflows/documents/sync/syncSubmittedResult.js +1 -1
  240. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  241. package/workflows/documents/syncPlan/syncContentKeys.js +1 -1
  242. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  243. package/workflows/organizations/containerContentsHost.js +14 -0
  244. package/workflows/organizations/containerContentsHost.js.map +1 -0
  245. package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -1
  246. package/workflows/organizations/currentOrganizationAuthority.js +1 -1
  247. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  248. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js +1 -1
  249. package/workflows/organizations/groupMetadata/currentGroupMetadataAuthority.js.map +1 -1
  250. package/workflows/organizations/groupMetadata/groupMetadataBinding.js.map +1 -1
  251. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js +2 -2
  252. package/workflows/organizations/groupMetadata/groupMetadataContainerAuthority.js.map +1 -1
  253. package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js +2 -2
  254. package/workflows/organizations/groupMetadata/groupMetadataRootBinding.js.map +1 -1
  255. package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
  256. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  257. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js +2 -2
  258. package/workflows/organizations/groupNames/organizationGroupNamePolicies.js.map +1 -1
  259. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js +1 -1
  260. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  261. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +1 -1
  262. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  263. package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
  264. package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
  265. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  266. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  267. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
  268. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  269. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
  270. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  271. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  272. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  273. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  274. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  275. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +1 -1
  276. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  277. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js +1 -1
  278. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -1
  279. package/workflows/organizations/policyHistory/organizationPolicyHistoryDetails.js.map +1 -1
  280. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js +1 -1
  281. package/workflows/organizations/policyHistory/organizationPolicyHistoryVerification.js.map +1 -1
  282. package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js +1 -1
  283. package/workflows/organizations/principalMutations/acknowledgedDirectoryBindings.js.map +1 -1
  284. package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js +1 -1
  285. package/workflows/organizations/principalMutations/currentOrganizationMutationAuthority.js.map +1 -1
  286. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js +1 -1
  287. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
  288. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +1 -1
  289. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
  290. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js +1 -1
  291. package/workflows/organizations/principalPolicy/principalPolicyReceiptArtifacts.js.map +1 -1
  292. package/workflows/organizations/principalPolicy/principalPolicyRecipients.js +1 -1
  293. package/workflows/organizations/principalPolicy/principalPolicyRecipients.js.map +1 -1
  294. package/workflows/organizations/principalPolicy/principalPolicyRequest.js +1 -1
  295. package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +1 -1
  296. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js +2 -2
  297. package/workflows/principals/acknowledgements/acknowledgedPrincipalPredecessor.js.map +1 -1
  298. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  299. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  300. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js +1 -1
  301. package/workflows/principals/acknowledgements/reconcileAcknowledgedPrincipalCurrent.js.map +1 -1
  302. package/workflows/principals/externalAdminPolicy.d.ts +1 -1
  303. package/workflows/principals/externalAdminPolicy.js +2 -2
  304. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  305. package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js +1 -1
  306. package/workflows/principals/historyRecovery/principalHistoryRecoveryAuthority.js.map +1 -1
  307. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js +1 -1
  308. package/workflows/principals/historyRecovery/principalHistoryRecoveryReferences.js.map +1 -1
  309. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js +1 -1
  310. package/workflows/principals/historyRecovery/recoverPrincipalPolicyHistory.js.map +1 -1
  311. package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js +1 -1
  312. package/workflows/principals/historyRecovery/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  313. package/workflows/principals/policyCache/index.d.ts +1 -1
  314. package/workflows/principals/policyCache/index.js +3 -2
  315. package/workflows/principals/policyCache/index.js.map +1 -1
  316. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
  317. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  318. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +2 -2
  319. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  320. package/workflows/principals/policyVerification.js +1 -1
  321. package/workflows/principals/policyVerification.js.map +1 -1
  322. package/workflows/principals/principalPolicyService.js +1 -1
  323. package/workflows/principals/principalPolicyService.js.map +1 -1
  324. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js +1 -1
  325. package/workflows/principals/publicHistory/publicPrincipalHistoryAuthority.js.map +1 -1
  326. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js +1 -1
  327. package/workflows/principals/publicHistory/publicPrincipalHistoryProgress.js.map +1 -1
  328. package/workflows/principals/publicHistory/publicProjectionDirectory.js +1 -1
  329. package/workflows/principals/publicHistory/publicProjectionDirectory.js.map +1 -1
  330. package/workflows/principals/publicHistory/publicProjectionPrincipal.js +1 -1
  331. package/workflows/principals/publicHistory/publicProjectionPrincipal.js.map +1 -1
  332. package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js +1 -1
  333. package/workflows/principals/publicHistory/recoverProjectionPolicyHistory.js.map +1 -1
  334. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js +2 -2
  335. package/workflows/principals/publicHistory/recoverPublicPrincipalHistory.js.map +1 -1
  336. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js +1 -1
  337. package/workflows/principals/publicHistory/selectPublicPrincipalHistory.js.map +1 -1
  338. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.d.ts +1 -1
  339. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js +1 -1
  340. package/workflows/principals/recoveryOperation/principalRecoveryDirectory.js.map +1 -1
  341. package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js +1 -1
  342. package/workflows/principals/recoveryOperation/principalRecoveryLocalPreference.js.map +1 -1
  343. package/workflows/principals/recoveryOperation/principalRecoveryMemo.js +1 -1
  344. package/workflows/principals/recoveryOperation/principalRecoveryMemo.js.map +1 -1
  345. package/workflows/principals/runtimePolicyRecovery.d.ts +1 -1
  346. package/workflows/principals/runtimePolicyRecovery.js +1 -1
  347. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  348. package/workflows/principals/runtimeProjectionPolicyRecovery.js +1 -1
  349. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  350. package/workflows/registration/organizationProvisioning.js +2 -2
  351. package/workflows/registration/organizationProvisioning.js.map +1 -1
  352. package/workflows/registration/persistRegistrationBootstrap.js +2 -0
  353. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  354. package/workflows/registration/provisionedPrincipalHistory.js +1 -1
  355. package/workflows/registration/provisionedPrincipalHistory.js.map +1 -1
  356. package/workflows/registration/registrationAccessHeadPersistence.js +1 -1
  357. package/workflows/registration/registrationAccessHeadPersistence.js.map +1 -1
  358. package/data/containers/shared/heldContainerHeads.js.map +0 -1
  359. /package/data/{containers/shared → keyingProjectionVerification/checkpoints}/heldContainerHeads.js +0 -0
  360. /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js +0 -0
  361. /package/data/persistence/{principalKeys → principalContracts}/principalGrantRetirementPersistence.js.map +0 -0
  362. /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.d.ts +0 -0
  363. /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js +0 -0
  364. /package/data/{principals → principalContracts}/organizationAuthorityDescriptor.js.map +0 -0
  365. /package/data/{principals → principalContracts}/principalIdentityCommitments.js +0 -0
  366. /package/data/{principals → principalContracts}/principalIdentityCommitments.js.map +0 -0
  367. /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js +0 -0
  368. /package/data/{principals → principalContracts}/principalPolicyAdminSigners.js.map +0 -0
  369. /package/data/{principals → principalContracts}/principalPolicyEvidence.d.ts +0 -0
  370. /package/data/{principals → principalContracts}/principalPolicyEvidence.js +0 -0
  371. /package/data/{principals → principalContracts}/principalPolicyEvidence.js.map +0 -0
  372. /package/data/{principals → principalContracts}/principalPolicyStates.js +0 -0
  373. /package/data/{principals → principalContracts}/principalPolicyStates.js.map +0 -0
  374. /package/{client/runtime → data/shared}/listenerSet.js +0 -0
  375. /package/{client/runtime → data/shared}/listenerSet.js.map +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"syncSubmittedResult.js","sourceRoot":"","sources":["syncSubmittedResult.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAKxH,OAAO,EAEL,2CAA2C,GAC5C,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,yBAAyB,EAAE,MAAM,kDAAkD,CAAC;AAE7F,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,kCAAkC,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YAAY;oBACrC,+BAA+B,EAC7B,KAAK,CAAC,IAAI,CAAC,+BAA+B;iBAC7C,CAAC;aACL;SACF;QACH,CAAC,CAAC,KAAK,CAAC,gBAAgB,CAAC;IAC3B,yEAAyE;IACzE,6EAA6E;IAC7E,OAAO,2BAA2B,CAAC;QACjC,GAAG,KAAK;QACR,gBAAgB;QAChB,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuC;IAEvC,IAAI,CAAC;QACH,OAAO,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,iBAAiB,GACrB,yBAAyB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;QAC1E,IACE,CAAC,iBAAiB;YAClB,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,KAAK,KAAK;gBAC/B,CAAC,CAAC,KAAK,YAAY,kCAAkC,CAAC,CAAC,EACzD,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,yCAAyC,CAC9C,KAAK,EACL,KAAK,EACL,iBAAiB,CAClB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type {\n MaterializedDocumentSyncPlan,\n SyncRemoteDocumentResult,\n} from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport {\n type ProjectionUserKeyResolver,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../data/keyingProjectionVerification\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { openPrincipalPolicyBundleReader } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { DocumentRawHistoryUnavailableError } from \"../syncPlan/syncContentKeys\";\nimport {\n hasDeferredPendingUpdatesAfterSubmit,\n responseAcceptedRecoveryBaseline,\n} from \"../syncPlan/syncPlanRequestBounds\";\nimport type { RemoteDocumentSyncPass } from \"./remoteDocumentSyncPass\";\nimport { syncRemoteDocumentResultFromResponse } from \"./syncResponseResult\";\nimport { traceHealed } from \"./syncTrace\";\n\ntype SubmittedDocumentSyncResultInput = {\n materializedPlan: MaterializedDocumentSyncPlan;\n pendingUpdateIds: readonly string[];\n pullComplete: boolean;\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n response: DocumentSyncResponse;\n sync: RemoteDocumentSyncPass;\n writerProjection: DocumentWriterProjectionResponse;\n};\n\n/** @internal Applies post-verification heal effects under the sync generation. */\nexport function applyAcceptedHealSideEffects(input: {\n documentId: string;\n evictWriterProjection?: ((documentId: string) => void) | undefined;\n materializedPlan: MaterializedDocumentSyncPlan;\n onSyncTrace: RemoteDocumentSyncPass[\"onSyncTrace\"];\n response: DocumentSyncResponse;\n stillCurrent: RemoteDocumentSyncPass[\"stillCurrent\"];\n}): void {\n if (\n !input.materializedPlan.healedStaleContentKeyBundle ||\n !responseAcceptedRecoveryBaseline(input.materializedPlan, input.response) ||\n input.stillCurrent?.() === false\n ) {\n return;\n }\n input.evictWriterProjection?.(input.documentId);\n if (input.stillCurrent?.() === false) {\n return;\n }\n traceHealed(input.onSyncTrace, {\n accepted: input.response.acceptedOutgoingUpdateIds.length,\n documentId: input.materializedPlan.plan.documentId,\n epoch: input.materializedPlan.plan.contentKeyEpoch,\n });\n}\n\nasync function submittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult> {\n const result = await syncRemoteDocumentResultFromResponse({\n ...projectionVerificationOptions(input.sync),\n execSql: input.sync.execSql,\n materializedPlan: input.materializedPlan,\n onTerminalSubmitFailure: input.sync.onTerminalSubmitFailure,\n recoveryPendingUpdatesById: input.recoveryPendingUpdatesById,\n rekeyPendingUpdate: input.sync.rekeyPendingUpdate,\n resolveWriterPublicKey: input.sync.resolveWriterPublicKey,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n targetSecretKey: input.sync.targetSecretKey,\n validateIncomingUpdates: input.sync.validateIncomingUpdates,\n writerProjection: input.writerProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n });\n if (\n (input.materializedPlan.plan.request.containerRekeys?.length ?? 0) > 0 &&\n input.sync.stillCurrent?.() !== false\n ) {\n input.sync.apiClient.clearWriterProjectionCaches?.();\n }\n applyAcceptedHealSideEffects({\n documentId: input.sync.documentId,\n evictWriterProjection:\n input.sync.apiClient.evictDocumentWriterProjection?.bind(\n input.sync.apiClient,\n ),\n materializedPlan: input.materializedPlan,\n onSyncTrace: input.sync.onSyncTrace,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n });\n return {\n ...result,\n hasDeferredPendingUpdates:\n (input.materializedPlan.plan.request.pullCursor !== undefined &&\n input.pendingUpdateIds.length > 0 &&\n result.exhaustedPendingUpdateCount === 0) ||\n hasDeferredPendingUpdatesAfterSubmit({\n acceptedRecoveryBaseline: result.acceptedRecoveryBaseline,\n exhaustedPendingUpdateCount: result.exhaustedPendingUpdateCount,\n pendingUpdateIds: input.pendingUpdateIds,\n rekeyedPendingUpdateIds: result.rekeyedPendingUpdateIds,\n settledPendingUpdateIds: result.settledPendingUpdateIds,\n }),\n hasIncompletePull: !input.pullComplete,\n };\n}\n\nasync function retrySubmittedResponseWithFreshProjection(\n input: SubmittedDocumentSyncResultInput,\n unavailableError: unknown,\n refreshAuthorization: boolean,\n): Promise<SyncRemoteDocumentResult | null> {\n const writerProjection = await refreshSyncAttemptWriterProjection({\n apiClient: input.sync.apiClient,\n documentId: input.sync.documentId,\n onRemoteDocumentDeleted: input.sync.onRemoteDocumentDeleted,\n onSyncAbandoned: input.sync.onSyncAbandoned,\n onSyncTrace: input.sync.onSyncTrace,\n onTerminalFailure: input.sync.onReadOnlyProjectionFailure,\n stillCurrent: input.sync.stillCurrent,\n unavailableError,\n });\n if (!writerProjection) return null;\n const materializedPlan = refreshAuthorization\n ? {\n ...input.materializedPlan,\n plan: {\n ...input.materializedPlan.plan,\n documentWriterAuthorization:\n await verifyDocumentWriterProjectionAuthorization({\n execSql: input.sync.execSql,\n openPrincipalPolicyBundleReader,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.sync.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.sync.warmReferencedPrincipalPolicies,\n }),\n },\n }\n : input.materializedPlan;\n // Keep the submitted request, keys, and response frozen. Only refreshed,\n // verified evidence may be added; this retry never resubmits outgoing edits.\n return submittedDocumentSyncResult({\n ...input,\n materializedPlan,\n writerProjection,\n });\n}\n\nexport async function resolveSubmittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult | null> {\n try {\n return await submittedDocumentSyncResult(input);\n } catch (error) {\n const missingDependency =\n isKeyingVerificationError(error) && error.code === \"missing_dependency\";\n if (\n !missingDependency &&\n (input.sync.historyMode !== \"raw\" ||\n !(error instanceof DocumentRawHistoryUnavailableError))\n ) {\n throw error;\n }\n return retrySubmittedResponseWithFreshProjection(\n input,\n error,\n missingDependency,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"syncSubmittedResult.js","sourceRoot":"","sources":["syncSubmittedResult.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAKxH,OAAO,EAEL,2CAA2C,GAC5C,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACnF,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB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AY,EAAE,KAAK,CAAC,IAAI,CAAC,YAAY;oBACrC,+BAA+B,EAC7B,KAAK,CAAC,IAAI,CAAC,+BAA+B;iBAC7C,CAAC;aACL;SACF;QACH,CAAC,CAAC,KAAK,CAAC,gBAAgB,CAAC;IAC3B,yEAAyE;IACzE,6EAA6E;IAC7E,OAAO,2BAA2B,CAAC;QACjC,GAAG,KAAK;QACR,gBAAgB;QAChB,gBAAgB;KACjB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuC;IAEvC,IAAI,CAAC;QACH,OAAO,MAAM,2BAA2B,CAAC,KAAK,CAAC,CAAC;IAClD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,iBAAiB,GACrB,yBAAyB,CAAC,KAAK,CAAC,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;QAC1E,IACE,CAAC,iBAAiB;YAClB,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,KAAK,KAAK;gBAC/B,CAAC,CAAC,KAAK,YAAY,kCAAkC,CAAC,CAAC,EACzD,CAAC;YACD,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,yCAAyC,CAC9C,KAAK,EACL,KAAK,EACL,iBAAiB,CAClB,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type {\n MaterializedDocumentSyncPlan,\n SyncRemoteDocumentResult,\n} from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport {\n type ProjectionUserKeyResolver,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../data/keyingProjectionVerification\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { openPrincipalPolicyBundleReader } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { isKeyingVerificationError } from \"../../../data/shared/securityIncidents\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { DocumentRawHistoryUnavailableError } from \"../syncPlan/syncContentKeys\";\nimport {\n hasDeferredPendingUpdatesAfterSubmit,\n responseAcceptedRecoveryBaseline,\n} from \"../syncPlan/syncPlanRequestBounds\";\nimport type { RemoteDocumentSyncPass } from \"./remoteDocumentSyncPass\";\nimport { syncRemoteDocumentResultFromResponse } from \"./syncResponseResult\";\nimport { traceHealed } from \"./syncTrace\";\n\ntype SubmittedDocumentSyncResultInput = {\n materializedPlan: MaterializedDocumentSyncPlan;\n pendingUpdateIds: readonly string[];\n pullComplete: boolean;\n recoveryPendingUpdatesById: ReadonlyMap<string, PendingUpdateRecord>;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n response: DocumentSyncResponse;\n sync: RemoteDocumentSyncPass;\n writerProjection: DocumentWriterProjectionResponse;\n};\n\n/** @internal Applies post-verification heal effects under the sync generation. */\nexport function applyAcceptedHealSideEffects(input: {\n documentId: string;\n evictWriterProjection?: ((documentId: string) => void) | undefined;\n materializedPlan: MaterializedDocumentSyncPlan;\n onSyncTrace: RemoteDocumentSyncPass[\"onSyncTrace\"];\n response: DocumentSyncResponse;\n stillCurrent: RemoteDocumentSyncPass[\"stillCurrent\"];\n}): void {\n if (\n !input.materializedPlan.healedStaleContentKeyBundle ||\n !responseAcceptedRecoveryBaseline(input.materializedPlan, input.response) ||\n input.stillCurrent?.() === false\n ) {\n return;\n }\n input.evictWriterProjection?.(input.documentId);\n if (input.stillCurrent?.() === false) {\n return;\n }\n traceHealed(input.onSyncTrace, {\n accepted: input.response.acceptedOutgoingUpdateIds.length,\n documentId: input.materializedPlan.plan.documentId,\n epoch: input.materializedPlan.plan.contentKeyEpoch,\n });\n}\n\nasync function submittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult> {\n const result = await syncRemoteDocumentResultFromResponse({\n ...projectionVerificationOptions(input.sync),\n execSql: input.sync.execSql,\n materializedPlan: input.materializedPlan,\n onTerminalSubmitFailure: input.sync.onTerminalSubmitFailure,\n recoveryPendingUpdatesById: input.recoveryPendingUpdatesById,\n rekeyPendingUpdate: input.sync.rekeyPendingUpdate,\n resolveWriterPublicKey: input.sync.resolveWriterPublicKey,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n targetSecretKey: input.sync.targetSecretKey,\n validateIncomingUpdates: input.sync.validateIncomingUpdates,\n writerProjection: input.writerProjection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n });\n if (\n (input.materializedPlan.plan.request.containerRekeys?.length ?? 0) > 0 &&\n input.sync.stillCurrent?.() !== false\n ) {\n input.sync.apiClient.clearWriterProjectionCaches?.();\n }\n applyAcceptedHealSideEffects({\n documentId: input.sync.documentId,\n evictWriterProjection:\n input.sync.apiClient.evictDocumentWriterProjection?.bind(\n input.sync.apiClient,\n ),\n materializedPlan: input.materializedPlan,\n onSyncTrace: input.sync.onSyncTrace,\n response: input.response,\n stillCurrent: input.sync.stillCurrent,\n });\n return {\n ...result,\n hasDeferredPendingUpdates:\n (input.materializedPlan.plan.request.pullCursor !== undefined &&\n input.pendingUpdateIds.length > 0 &&\n result.exhaustedPendingUpdateCount === 0) ||\n hasDeferredPendingUpdatesAfterSubmit({\n acceptedRecoveryBaseline: result.acceptedRecoveryBaseline,\n exhaustedPendingUpdateCount: result.exhaustedPendingUpdateCount,\n pendingUpdateIds: input.pendingUpdateIds,\n rekeyedPendingUpdateIds: result.rekeyedPendingUpdateIds,\n settledPendingUpdateIds: result.settledPendingUpdateIds,\n }),\n hasIncompletePull: !input.pullComplete,\n };\n}\n\nasync function retrySubmittedResponseWithFreshProjection(\n input: SubmittedDocumentSyncResultInput,\n unavailableError: unknown,\n refreshAuthorization: boolean,\n): Promise<SyncRemoteDocumentResult | null> {\n const writerProjection = await refreshSyncAttemptWriterProjection({\n apiClient: input.sync.apiClient,\n documentId: input.sync.documentId,\n onRemoteDocumentDeleted: input.sync.onRemoteDocumentDeleted,\n onSyncAbandoned: input.sync.onSyncAbandoned,\n onSyncTrace: input.sync.onSyncTrace,\n onTerminalFailure: input.sync.onReadOnlyProjectionFailure,\n stillCurrent: input.sync.stillCurrent,\n unavailableError,\n });\n if (!writerProjection) return null;\n const materializedPlan = refreshAuthorization\n ? {\n ...input.materializedPlan,\n plan: {\n ...input.materializedPlan.plan,\n documentWriterAuthorization:\n await verifyDocumentWriterProjectionAuthorization({\n execSql: input.sync.execSql,\n openPrincipalPolicyBundleReader,\n projection: writerProjection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.sync.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.sync.warmReferencedPrincipalPolicies,\n }),\n },\n }\n : input.materializedPlan;\n // Keep the submitted request, keys, and response frozen. Only refreshed,\n // verified evidence may be added; this retry never resubmits outgoing edits.\n return submittedDocumentSyncResult({\n ...input,\n materializedPlan,\n writerProjection,\n });\n}\n\nexport async function resolveSubmittedDocumentSyncResult(\n input: SubmittedDocumentSyncResultInput,\n): Promise<SyncRemoteDocumentResult | null> {\n try {\n return await submittedDocumentSyncResult(input);\n } catch (error) {\n const missingDependency =\n isKeyingVerificationError(error) && error.code === \"missing_dependency\";\n if (\n !missingDependency &&\n (input.sync.historyMode !== \"raw\" ||\n !(error instanceof DocumentRawHistoryUnavailableError))\n ) {\n throw error;\n }\n return retrySubmittedResponseWithFreshProjection(\n input,\n error,\n missingDependency,\n );\n }\n}\n"]}
@@ -5,7 +5,7 @@ import { projectionVerificationOptions } from "../../../data/documents/shared/pr
5
5
  import { readWriteHeader } from "../../../data/documents/shared/readers.js";
6
6
  import { assertDocumentSyncUpdateEncryptedRecord } from "../../../data/documents/shared/sync/documentSyncUpdateDecryption.js";
7
7
  import { isDocumentSyncUpdateIsolationError, isolateDocumentSyncBatchError, isolateDocumentSyncUpdateError, } from "../../../data/documents/shared/sync/documentSyncUpdateIsolation.js";
8
- import { isKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
8
+ import { isKeyingVerificationError } from "../../../data/shared/securityIncidents.js";
9
9
  function isRawHistoryUnavailableCause(error) {
10
10
  return (error instanceof DocumentContentKeyUnavailableError ||
11
11
  (error instanceof DocumentHistoryUnavailableError &&
@@ -1 +1 @@
1
- {"version":3,"file":"syncContentKeys.js","sourceRoot":"","sources":["syncContentKeys.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AACrF,OAAO,EACL,mCAAmC,EACnC,mCAAmC,EACnC,kCAAkC,EAClC,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAEzE,OAAO,EAAE,uCAAuC,EAAE,MAAM,kEAAkE,CAAC;AAC3H,OAAO,EACL,kCAAkC,EAClC,6BAA6B,EAC7B,8BAA8B,GAC/B,MAAM,iEAAiE,CAAC;AACzE,OAAO,EAAE,yBAAyB,EAAE,MAAM,kDAAkD,CAAC;AAS7F,SAAS,4BAA4B,CACnC,KAAc;IAEd,OAAO,CACL,KAAK,YAAY,kCAAkC;QACnD,CAAC,KAAK,YAAY,+BAA+B;YAC/C,KAAK,CAAC,YAAY,YAAY,mCAAmC,CAAC,CACrE,CAAC;AACJ,CAAC;AAOD,6EAA6E;AAC7E,MAAM,OAAO,kCAAmC,SAAQ,KAAK;IAIhD;IAHF,IAAI,GAAG,wCAAwC,CAAC;IAEzD,YACW,eAAuB,EAChC,KAAc;QAEd,KAAK,CACH,kEAAkE,eAAe,EAAE,EACnF,EAAE,KAAK,EAAE,CACV,CAAC;QANO,oBAAe,GAAf,eAAe,CAAQ;QAOhC,IAAI,CAAC,IAAI,GAAG,oCAAoC,CAAC;IACnD,CAAC;CACF;AAED,KA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,KAAK;gBACZ,OAAO,EAAE,eAAe;aACzB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,IAAI,qBAAqB,EAAE,CAAC;QAC1B,MAAM,0BAA0B,CAAC;YAC/B,kBAAkB;YAClB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,WAAW,EAAE,qBAAqB;YAClC,QAAQ,EAAE,KAAK,CAAC,uBAAuB;SACxC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,kBAAkB,CAAC;AAC5B,CAAC","sourcesContent":["import type {\n DocumentContentKeyBundleResponse,\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { importContentKeyMaterial } from \"../../../data/documents/shared/contentRecordKeys\";\nimport { encryptDocumentPendingUpdate } from \"../../../data/documents/shared/crypto\";\nimport {\n ContainerKekHistoryUnavailableError,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { readWriteHeader } from \"../../../data/documents/shared/readers\";\nimport type { DocumentSyncPreparedUpdate } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport { assertDocumentSyncUpdateEncryptedRecord } from \"../../../data/documents/shared/sync/documentSyncUpdateDecryption\";\nimport {\n isDocumentSyncUpdateIsolationError,\n isolateDocumentSyncBatchError,\n isolateDocumentSyncUpdateError,\n} from \"../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nimport { isKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\ntype SyncResponseUpdate = DocumentSyncResponse[\"updates\"][number];\ntype RawHistoryUnavailableCause =\n | DocumentContentKeyUnavailableError\n | DocumentHistoryUnavailableError;\n\nfunction isRawHistoryUnavailableCause(\n error: unknown,\n): error is RawHistoryUnavailableCause {\n return (\n error instanceof DocumentContentKeyUnavailableError ||\n (error instanceof DocumentHistoryUnavailableError &&\n error.historyCause instanceof ContainerKekHistoryUnavailableError)\n );\n}\n\ntype RawHistoryUnavailableValidator = (input: {\n contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;\n updates: readonly SyncResponseUpdate[];\n}) => void | Promise<void>;\n\n/** A raw recovery cannot reconstruct history without this retained epoch. */\nexport class DocumentRawHistoryUnavailableError extends Error {\n readonly code = \"document_raw_history_epoch_unavailable\";\n\n constructor(\n readonly contentKeyEpoch: number,\n cause: unknown,\n ) {\n super(\n `Document raw-history recovery cannot decrypt content-key epoch ${contentKeyEpoch}`,\n { cause },\n );\n this.name = \"DocumentRawHistoryUnavailableError\";\n }\n}\n\nasync function assertResponseEncryptedRecords(\n updates: readonly SyncResponseUpdate[],\n): Promise<void> {\n const inspections = await Promise.allSettled(\n updates.map(assertDocumentSyncUpdateEncryptedRecord),\n );\n const failures = inspections.flatMap((inspection, index) =>\n inspection.status === \"rejected\"\n ? [{ index, reason: inspection.reason }]\n : [],\n );\n const firstFailure = failures[0];\n if (failures.length === 1 && firstFailure) {\n throw firstFailure.reason;\n }\n if (failures.length > 1 && firstFailure) {\n const stage =\n isDocumentSyncUpdateIsolationError(firstFailure.reason) &&\n failures.every(\n ({ reason }) =>\n isDocumentSyncUpdateIsolationError(reason) &&\n reason.stage === firstFailure.reason.stage,\n )\n ? firstFailure.reason.stage\n : \"encrypted_record\";\n throw isolateDocumentSyncBatchError({\n cause: new Error(\"Multiple document encrypted records are invalid\"),\n stage,\n updateIds: failures.map(({ index }) => updates[index]?.id ?? \"unknown\"),\n });\n }\n}\n\nasync function throwRawHistoryUnavailable(input: {\n contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;\n response: DocumentSyncResponse;\n unavailable: { cause: RawHistoryUnavailableCause; contentKeyEpoch: number };\n validate?: RawHistoryUnavailableValidator | undefined;\n}): Promise<never> {\n await assertResponseEncryptedRecords(input.response.updates);\n await input.validate?.({\n contentKeysByEpoch: input.contentKeysByEpoch,\n updates: input.response.updates.filter((update) =>\n input.contentKeysByEpoch.has(\n readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n ).contentKeyEpoch,\n ),\n ),\n });\n throw new DocumentRawHistoryUnavailableError(\n input.unavailable.contentKeyEpoch,\n input.unavailable.cause,\n );\n}\n\nexport async function prepareDocumentOutgoingUpdates(input: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n organizationId: string;\n pendingUpdates: readonly PendingUpdateRecord[];\n}): Promise<DocumentSyncPreparedUpdate[]> {\n if (input.pendingUpdates.length === 0) {\n return [];\n }\n const contentKeyMaterial = await importContentKeyMaterial(input.contentKey);\n\n return Promise.all(\n input.pendingUpdates.map(async (update) => {\n const encrypted = await encryptDocumentPendingUpdate({\n contentKeyMaterial,\n contentKeyEpoch: input.contentKeyEpoch,\n documentId: input.documentId,\n organizationId: input.organizationId,\n update,\n });\n\n return {\n contentRecordId: encrypted.contentRecordId,\n encryptedData: encrypted.encryptedData,\n id: update.id,\n partialStartVersionVector: update.partialStartVersionVector,\n partialEndVersionVector: update.partialEndVersionVector,\n metadataHash: encrypted.metadataHash,\n ciphertextHash: encrypted.ciphertextHash,\n plaintextHash: encrypted.plaintextHash,\n ...(update.sourceVersionVector\n ? {\n checkpointKind: \"rotate_baseline\" as const,\n checkpointPayloadKind: \"full_history_snapshot\" as const,\n sourceVersionVector: update.sourceVersionVector,\n }\n : {}),\n };\n }),\n );\n}\n\nfunction syncResponseContentKeyBundlesByEpoch(\n currentContentKeyBundle: DocumentContentKeyBundleResponse,\n response: DocumentSyncResponse,\n): ReadonlyMap<number, DocumentContentKeyBundleResponse> {\n const byEpoch = new Map<number, DocumentContentKeyBundleResponse>();\n\n for (const bundle of [\n currentContentKeyBundle,\n ...response.contentKeyBundles,\n ]) {\n if (byEpoch.has(bundle.contentKeyEpoch)) {\n throw new Error(\"Document sync response repeats a content-key epoch\");\n }\n byEpoch.set(bundle.contentKeyEpoch, bundle);\n }\n\n return byEpoch;\n}\n\nfunction syncResponseUpdatesByContentKeyEpoch(\n response: DocumentSyncResponse,\n): ReadonlyMap<number, readonly SyncResponseUpdate[]> {\n const updatesByEpoch = new Map<number, SyncResponseUpdate[]>();\n for (const update of response.updates) {\n let contentKeyEpoch: number;\n try {\n contentKeyEpoch = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n ).contentKeyEpoch;\n } catch (error) {\n throw isolateDocumentSyncUpdateError({\n cause: error,\n responseUpdate: update,\n stage: \"write_header\",\n updateId: update.id,\n });\n }\n const epochUpdates = updatesByEpoch.get(contentKeyEpoch);\n if (epochUpdates) epochUpdates.push(update);\n else updatesByEpoch.set(contentKeyEpoch, [update]);\n }\n return updatesByEpoch;\n}\n\nfunction assertBundleMatchesUpdateHeaders(input: {\n bundle: DocumentContentKeyBundleResponse;\n requireOriginalTargets: boolean;\n updates: readonly SyncResponseUpdate[];\n}): void {\n for (const update of input.updates) {\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n if (\n header.objectId !== input.bundle.documentId ||\n header.contentKeyEpoch !== input.bundle.contentKeyEpoch ||\n (input.requireOriginalTargets &&\n (header.accessManifestHash !== input.bundle.linkSetManifestHash ||\n header.targetHash !== input.bundle.targetHash))\n ) {\n throw new Error(\n input.requireOriginalTargets\n ? \"Document sync response content key is unavailable and its bundle differs from the original update headers\"\n : \"Document sync response content-key bundle does not match its update headers\",\n );\n }\n }\n}\n\n/**\n * Linking can rewrap a retained key at the same content epoch. Its latest bundle\n * then has newer targets than older signed updates. A usable key is validated\n * by the caller's authenticated record decryption; the update's own historical\n * manifest, targets and signature are verified independently before this step.\n *\n * If the key cannot be recovered, require the original target commitments before\n * calling that an availability failure. Substituted unavailable targets must\n * still be quarantined, never disguised as legitimate missing history.\n */\nasync function unwrapHistoricalContentKey(input: {\n bundle: DocumentContentKeyBundleResponse;\n documentId: string;\n collectedKeks: Awaited<\n ReturnType<typeof collectContainerKeksForDocumentSync>\n >;\n updates: readonly SyncResponseUpdate[];\n}): Promise<Uint8Array> {\n assertBundleMatchesUpdateHeaders({ ...input, requireOriginalTargets: false });\n try {\n return await unwrapDocumentContentKeyFromBundle(\n input.bundle,\n input.documentId,\n input.collectedKeks.keksByEpochId,\n input.collectedKeks.predecessorFailuresByEpochId,\n input.collectedKeks.unattributedPredecessorFailuresByContainerId,\n );\n } catch (error) {\n if (isRawHistoryUnavailableCause(error)) {\n assertBundleMatchesUpdateHeaders({\n ...input,\n requireOriginalTargets: true,\n });\n }\n throw error;\n }\n}\n\n/** @internal Keeps epoch-wide failures anonymous and integrity failures typed. */\nexport function throwDocumentSyncContentKeyFailure(input: {\n cause: unknown;\n updates: readonly SyncResponseUpdate[];\n}): never {\n if (isKeyingVerificationError(input.cause)) {\n throw input.cause;\n }\n if (\n input.cause instanceof DocumentHistoryUnavailableError &&\n isKeyingVerificationError(input.cause.historyCause)\n ) {\n throw input.cause.historyCause;\n }\n throw isolateDocumentSyncBatchError({\n cause: input.cause,\n stage: \"content_key\",\n updateIds: input.updates.map((update) => update.id),\n });\n}\n\nfunction requireContentKeyBundle(\n bundlesByEpoch: ReturnType<typeof syncResponseContentKeyBundlesByEpoch>,\n contentKeyEpoch: number,\n updates: readonly SyncResponseUpdate[],\n) {\n const bundle = bundlesByEpoch.get(contentKeyEpoch);\n if (!bundle) {\n throwDocumentSyncContentKeyFailure({\n cause: new Error(\"Document sync response content-key bundle missing\"),\n updates,\n });\n }\n return bundle;\n}\n\nexport async function unwrapDocumentSyncResponseContentKeys(\n input: {\n currentContentKey: Uint8Array;\n /** The bundle the sync was planned against; it wraps `currentContentKey`. */\n currentContentKeyBundle: DocumentContentKeyBundleResponse;\n execSql?: ExecSql | undefined;\n historyMode?: \"raw\" | undefined;\n /** @internal Validate every decryptable sibling before raw availability wins. */\n onRawHistoryUnavailable?: RawHistoryUnavailableValidator | undefined;\n response: DocumentSyncResponse;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<ReadonlyMap<number, Uint8Array>> {\n // A stale read-only pass can carry an empty placeholder when none of its\n // authorizing paths reaches the bundle target. Do not mark that epoch as\n // resolved: every served update must instead unwrap its bundle through the\n // verified predecessor KEK chain or fail with an honest error.\n const currentEpoch = input.currentContentKeyBundle.contentKeyEpoch;\n const contentKeysByEpoch = new Map<number, Uint8Array>(\n input.currentContentKey.byteLength > 0\n ? [[currentEpoch, input.currentContentKey]]\n : [],\n );\n const updatesByContentKeyEpoch = syncResponseUpdatesByContentKeyEpoch(\n input.response,\n );\n const missingContentKeyEpochs = [...updatesByContentKeyEpoch.keys()].filter(\n (contentKeyEpoch) => !contentKeysByEpoch.has(contentKeyEpoch),\n );\n missingContentKeyEpochs.sort((left, right) => left - right);\n if (missingContentKeyEpochs.length === 0) {\n return contentKeysByEpoch;\n }\n const missingUpdates = missingContentKeyEpochs.flatMap(\n (contentKeyEpoch) => updatesByContentKeyEpoch.get(contentKeyEpoch) ?? [],\n );\n let bundlesByEpoch: ReturnType<typeof syncResponseContentKeyBundlesByEpoch>;\n try {\n bundlesByEpoch = syncResponseContentKeyBundlesByEpoch(\n input.currentContentKeyBundle,\n input.response,\n );\n } catch (error) {\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: missingUpdates,\n });\n }\n const absentBundleEpoch = missingContentKeyEpochs.find(\n (contentKeyEpoch) => !bundlesByEpoch.has(contentKeyEpoch),\n );\n if (absentBundleEpoch !== undefined) {\n throwDocumentSyncContentKeyFailure({\n cause: new Error(\"Document sync response content-key bundle missing\"),\n updates:\n updatesByContentKeyEpoch.get(absentBundleEpoch) ?? missingUpdates,\n });\n }\n const collectedKeks = await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n let unavailableRawHistory:\n | { cause: RawHistoryUnavailableCause; contentKeyEpoch: number }\n | undefined;\n\n for (const contentKeyEpoch of missingContentKeyEpochs) {\n const responseUpdates =\n updatesByContentKeyEpoch.get(contentKeyEpoch) ?? missingUpdates;\n const bundle = requireContentKeyBundle(\n bundlesByEpoch,\n contentKeyEpoch,\n responseUpdates,\n );\n try {\n contentKeysByEpoch.set(\n bundle.contentKeyEpoch,\n await unwrapHistoricalContentKey({\n bundle,\n collectedKeks,\n documentId: input.writerProjection.documentId,\n updates: responseUpdates,\n }),\n );\n } catch (error) {\n if (input.historyMode === \"raw\" && isRawHistoryUnavailableCause(error)) {\n unavailableRawHistory ??= { cause: error, contentKeyEpoch };\n continue;\n }\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: responseUpdates,\n });\n }\n }\n\n if (unavailableRawHistory) {\n await throwRawHistoryUnavailable({\n contentKeysByEpoch,\n response: input.response,\n unavailable: unavailableRawHistory,\n validate: input.onRawHistoryUnavailable,\n });\n }\n\n return contentKeysByEpoch;\n}\n"]}
1
+ {"version":3,"file":"syncContentKeys.js","sourceRoot":"","sources":["syncContentKeys.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,wBAAwB,EAAE,MAAM,kDAAkD,CAAC;AAC5F,OAAO,EAAE,4BAA4B,EAAE,MAAM,uCAAuC,CAAC;AACrF,OAAO,EACL,mCAAmC,EACnC,mCAAmC,EACnC,kCAAkC,EAClC,+BAA+B,EAC/B,kCAAkC,GACnC,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,eAAe,EAAE,MAAM,wCAAwC,CAAC;AAEzE,OAAO,EAAE,uCAAuC,EAAE,MAAM,kEAAkE,CAAC;AAC3H,OAAO,EACL,kCAAkC,EAClC,6BAA6B,EAC7B,8BAA8B,GAC/B,MAAM,iEAAiE,CAAC;AAEzE,OAAO,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,EACd,eAAe,EACf,eAAe,CAChB,CAAC;QACF,IAAI,CAAC;YACH,kBAAkB,CAAC,GAAG,CACpB,MAAM,CAAC,eAAe,EACtB,MAAM,0BAA0B,CAAC;gBAC/B,MAAM;gBACN,aAAa;gBACb,UAAU,EAAE,KAAK,CAAC,gBAAgB,CAAC,UAAU;gBAC7C,OAAO,EAAE,eAAe;aACzB,CAAC,CACH,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,KAAK,CAAC,WAAW,KAAK,KAAK,IAAI,4BAA4B,CAAC,KAAK,CAAC,EAAE,CAAC;gBACvE,qBAAqB,KAAK,EAAE,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC;gBAC5D,SAAS;YACX,CAAC;YACD,kCAAkC,CAAC;gBACjC,KAAK,EAAE,KAAK;gBACZ,OAAO,EAAE,eAAe;aACzB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IAED,IAAI,qBAAqB,EAAE,CAAC;QAC1B,MAAM,0BAA0B,CAAC;YAC/B,kBAAkB;YAClB,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,WAAW,EAAE,qBAAqB;YAClC,QAAQ,EAAE,KAAK,CAAC,uBAAuB;SACxC,CAAC,CAAC;IACL,CAAC;IAED,OAAO,kBAAkB,CAAC;AAC5B,CAAC","sourcesContent":["import type {\n DocumentContentKeyBundleResponse,\n DocumentSyncResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { importContentKeyMaterial } from \"../../../data/documents/shared/contentRecordKeys\";\nimport { encryptDocumentPendingUpdate } from \"../../../data/documents/shared/crypto\";\nimport {\n ContainerKekHistoryUnavailableError,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n} from \"../../../data/documents/shared/projection\";\nimport type { ProjectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { readWriteHeader } from \"../../../data/documents/shared/readers\";\nimport type { DocumentSyncPreparedUpdate } from \"../../../data/documents/shared/sync/documentSyncTypes\";\nimport { assertDocumentSyncUpdateEncryptedRecord } from \"../../../data/documents/shared/sync/documentSyncUpdateDecryption\";\nimport {\n isDocumentSyncUpdateIsolationError,\n isolateDocumentSyncBatchError,\n isolateDocumentSyncUpdateError,\n} from \"../../../data/documents/shared/sync/documentSyncUpdateIsolation\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { isKeyingVerificationError } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\n\ntype SyncResponseUpdate = DocumentSyncResponse[\"updates\"][number];\ntype RawHistoryUnavailableCause =\n | DocumentContentKeyUnavailableError\n | DocumentHistoryUnavailableError;\n\nfunction isRawHistoryUnavailableCause(\n error: unknown,\n): error is RawHistoryUnavailableCause {\n return (\n error instanceof DocumentContentKeyUnavailableError ||\n (error instanceof DocumentHistoryUnavailableError &&\n error.historyCause instanceof ContainerKekHistoryUnavailableError)\n );\n}\n\ntype RawHistoryUnavailableValidator = (input: {\n contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;\n updates: readonly SyncResponseUpdate[];\n}) => void | Promise<void>;\n\n/** A raw recovery cannot reconstruct history without this retained epoch. */\nexport class DocumentRawHistoryUnavailableError extends Error {\n readonly code = \"document_raw_history_epoch_unavailable\";\n\n constructor(\n readonly contentKeyEpoch: number,\n cause: unknown,\n ) {\n super(\n `Document raw-history recovery cannot decrypt content-key epoch ${contentKeyEpoch}`,\n { cause },\n );\n this.name = \"DocumentRawHistoryUnavailableError\";\n }\n}\n\nasync function assertResponseEncryptedRecords(\n updates: readonly SyncResponseUpdate[],\n): Promise<void> {\n const inspections = await Promise.allSettled(\n updates.map(assertDocumentSyncUpdateEncryptedRecord),\n );\n const failures = inspections.flatMap((inspection, index) =>\n inspection.status === \"rejected\"\n ? [{ index, reason: inspection.reason }]\n : [],\n );\n const firstFailure = failures[0];\n if (failures.length === 1 && firstFailure) {\n throw firstFailure.reason;\n }\n if (failures.length > 1 && firstFailure) {\n const stage =\n isDocumentSyncUpdateIsolationError(firstFailure.reason) &&\n failures.every(\n ({ reason }) =>\n isDocumentSyncUpdateIsolationError(reason) &&\n reason.stage === firstFailure.reason.stage,\n )\n ? firstFailure.reason.stage\n : \"encrypted_record\";\n throw isolateDocumentSyncBatchError({\n cause: new Error(\"Multiple document encrypted records are invalid\"),\n stage,\n updateIds: failures.map(({ index }) => updates[index]?.id ?? \"unknown\"),\n });\n }\n}\n\nasync function throwRawHistoryUnavailable(input: {\n contentKeysByEpoch: ReadonlyMap<number, Uint8Array>;\n response: DocumentSyncResponse;\n unavailable: { cause: RawHistoryUnavailableCause; contentKeyEpoch: number };\n validate?: RawHistoryUnavailableValidator | undefined;\n}): Promise<never> {\n await assertResponseEncryptedRecords(input.response.updates);\n await input.validate?.({\n contentKeysByEpoch: input.contentKeysByEpoch,\n updates: input.response.updates.filter((update) =>\n input.contentKeysByEpoch.has(\n readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n ).contentKeyEpoch,\n ),\n ),\n });\n throw new DocumentRawHistoryUnavailableError(\n input.unavailable.contentKeyEpoch,\n input.unavailable.cause,\n );\n}\n\nexport async function prepareDocumentOutgoingUpdates(input: {\n contentKey: Uint8Array;\n contentKeyEpoch: number;\n documentId: string;\n organizationId: string;\n pendingUpdates: readonly PendingUpdateRecord[];\n}): Promise<DocumentSyncPreparedUpdate[]> {\n if (input.pendingUpdates.length === 0) {\n return [];\n }\n const contentKeyMaterial = await importContentKeyMaterial(input.contentKey);\n\n return Promise.all(\n input.pendingUpdates.map(async (update) => {\n const encrypted = await encryptDocumentPendingUpdate({\n contentKeyMaterial,\n contentKeyEpoch: input.contentKeyEpoch,\n documentId: input.documentId,\n organizationId: input.organizationId,\n update,\n });\n\n return {\n contentRecordId: encrypted.contentRecordId,\n encryptedData: encrypted.encryptedData,\n id: update.id,\n partialStartVersionVector: update.partialStartVersionVector,\n partialEndVersionVector: update.partialEndVersionVector,\n metadataHash: encrypted.metadataHash,\n ciphertextHash: encrypted.ciphertextHash,\n plaintextHash: encrypted.plaintextHash,\n ...(update.sourceVersionVector\n ? {\n checkpointKind: \"rotate_baseline\" as const,\n checkpointPayloadKind: \"full_history_snapshot\" as const,\n sourceVersionVector: update.sourceVersionVector,\n }\n : {}),\n };\n }),\n );\n}\n\nfunction syncResponseContentKeyBundlesByEpoch(\n currentContentKeyBundle: DocumentContentKeyBundleResponse,\n response: DocumentSyncResponse,\n): ReadonlyMap<number, DocumentContentKeyBundleResponse> {\n const byEpoch = new Map<number, DocumentContentKeyBundleResponse>();\n\n for (const bundle of [\n currentContentKeyBundle,\n ...response.contentKeyBundles,\n ]) {\n if (byEpoch.has(bundle.contentKeyEpoch)) {\n throw new Error(\"Document sync response repeats a content-key epoch\");\n }\n byEpoch.set(bundle.contentKeyEpoch, bundle);\n }\n\n return byEpoch;\n}\n\nfunction syncResponseUpdatesByContentKeyEpoch(\n response: DocumentSyncResponse,\n): ReadonlyMap<number, readonly SyncResponseUpdate[]> {\n const updatesByEpoch = new Map<number, SyncResponseUpdate[]>();\n for (const update of response.updates) {\n let contentKeyEpoch: number;\n try {\n contentKeyEpoch = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n ).contentKeyEpoch;\n } catch (error) {\n throw isolateDocumentSyncUpdateError({\n cause: error,\n responseUpdate: update,\n stage: \"write_header\",\n updateId: update.id,\n });\n }\n const epochUpdates = updatesByEpoch.get(contentKeyEpoch);\n if (epochUpdates) epochUpdates.push(update);\n else updatesByEpoch.set(contentKeyEpoch, [update]);\n }\n return updatesByEpoch;\n}\n\nfunction assertBundleMatchesUpdateHeaders(input: {\n bundle: DocumentContentKeyBundleResponse;\n requireOriginalTargets: boolean;\n updates: readonly SyncResponseUpdate[];\n}): void {\n for (const update of input.updates) {\n const header = readWriteHeader(\n update.writeHeader,\n \"Document sync response write header\",\n );\n if (\n header.objectId !== input.bundle.documentId ||\n header.contentKeyEpoch !== input.bundle.contentKeyEpoch ||\n (input.requireOriginalTargets &&\n (header.accessManifestHash !== input.bundle.linkSetManifestHash ||\n header.targetHash !== input.bundle.targetHash))\n ) {\n throw new Error(\n input.requireOriginalTargets\n ? \"Document sync response content key is unavailable and its bundle differs from the original update headers\"\n : \"Document sync response content-key bundle does not match its update headers\",\n );\n }\n }\n}\n\n/**\n * Linking can rewrap a retained key at the same content epoch. Its latest bundle\n * then has newer targets than older signed updates. A usable key is validated\n * by the caller's authenticated record decryption; the update's own historical\n * manifest, targets and signature are verified independently before this step.\n *\n * If the key cannot be recovered, require the original target commitments before\n * calling that an availability failure. Substituted unavailable targets must\n * still be quarantined, never disguised as legitimate missing history.\n */\nasync function unwrapHistoricalContentKey(input: {\n bundle: DocumentContentKeyBundleResponse;\n documentId: string;\n collectedKeks: Awaited<\n ReturnType<typeof collectContainerKeksForDocumentSync>\n >;\n updates: readonly SyncResponseUpdate[];\n}): Promise<Uint8Array> {\n assertBundleMatchesUpdateHeaders({ ...input, requireOriginalTargets: false });\n try {\n return await unwrapDocumentContentKeyFromBundle(\n input.bundle,\n input.documentId,\n input.collectedKeks.keksByEpochId,\n input.collectedKeks.predecessorFailuresByEpochId,\n input.collectedKeks.unattributedPredecessorFailuresByContainerId,\n );\n } catch (error) {\n if (isRawHistoryUnavailableCause(error)) {\n assertBundleMatchesUpdateHeaders({\n ...input,\n requireOriginalTargets: true,\n });\n }\n throw error;\n }\n}\n\n/** @internal Keeps epoch-wide failures anonymous and integrity failures typed. */\nexport function throwDocumentSyncContentKeyFailure(input: {\n cause: unknown;\n updates: readonly SyncResponseUpdate[];\n}): never {\n if (isKeyingVerificationError(input.cause)) {\n throw input.cause;\n }\n if (\n input.cause instanceof DocumentHistoryUnavailableError &&\n isKeyingVerificationError(input.cause.historyCause)\n ) {\n throw input.cause.historyCause;\n }\n throw isolateDocumentSyncBatchError({\n cause: input.cause,\n stage: \"content_key\",\n updateIds: input.updates.map((update) => update.id),\n });\n}\n\nfunction requireContentKeyBundle(\n bundlesByEpoch: ReturnType<typeof syncResponseContentKeyBundlesByEpoch>,\n contentKeyEpoch: number,\n updates: readonly SyncResponseUpdate[],\n) {\n const bundle = bundlesByEpoch.get(contentKeyEpoch);\n if (!bundle) {\n throwDocumentSyncContentKeyFailure({\n cause: new Error(\"Document sync response content-key bundle missing\"),\n updates,\n });\n }\n return bundle;\n}\n\nexport async function unwrapDocumentSyncResponseContentKeys(\n input: {\n currentContentKey: Uint8Array;\n /** The bundle the sync was planned against; it wraps `currentContentKey`. */\n currentContentKeyBundle: DocumentContentKeyBundleResponse;\n execSql?: ExecSql | undefined;\n historyMode?: \"raw\" | undefined;\n /** @internal Validate every decryptable sibling before raw availability wins. */\n onRawHistoryUnavailable?: RawHistoryUnavailableValidator | undefined;\n response: DocumentSyncResponse;\n targetSecretKey: Uint8Array;\n writerProjection: DocumentWriterProjectionResponse;\n } & ProjectionVerificationOptions,\n): Promise<ReadonlyMap<number, Uint8Array>> {\n // A stale read-only pass can carry an empty placeholder when none of its\n // authorizing paths reaches the bundle target. Do not mark that epoch as\n // resolved: every served update must instead unwrap its bundle through the\n // verified predecessor KEK chain or fail with an honest error.\n const currentEpoch = input.currentContentKeyBundle.contentKeyEpoch;\n const contentKeysByEpoch = new Map<number, Uint8Array>(\n input.currentContentKey.byteLength > 0\n ? [[currentEpoch, input.currentContentKey]]\n : [],\n );\n const updatesByContentKeyEpoch = syncResponseUpdatesByContentKeyEpoch(\n input.response,\n );\n const missingContentKeyEpochs = [...updatesByContentKeyEpoch.keys()].filter(\n (contentKeyEpoch) => !contentKeysByEpoch.has(contentKeyEpoch),\n );\n missingContentKeyEpochs.sort((left, right) => left - right);\n if (missingContentKeyEpochs.length === 0) {\n return contentKeysByEpoch;\n }\n const missingUpdates = missingContentKeyEpochs.flatMap(\n (contentKeyEpoch) => updatesByContentKeyEpoch.get(contentKeyEpoch) ?? [],\n );\n let bundlesByEpoch: ReturnType<typeof syncResponseContentKeyBundlesByEpoch>;\n try {\n bundlesByEpoch = syncResponseContentKeyBundlesByEpoch(\n input.currentContentKeyBundle,\n input.response,\n );\n } catch (error) {\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: missingUpdates,\n });\n }\n const absentBundleEpoch = missingContentKeyEpochs.find(\n (contentKeyEpoch) => !bundlesByEpoch.has(contentKeyEpoch),\n );\n if (absentBundleEpoch !== undefined) {\n throwDocumentSyncContentKeyFailure({\n cause: new Error(\"Document sync response content-key bundle missing\"),\n updates:\n updatesByContentKeyEpoch.get(absentBundleEpoch) ?? missingUpdates,\n });\n }\n const collectedKeks = await collectContainerKeksForDocumentSync({\n execSql: input.execSql,\n secretKey: input.targetSecretKey,\n writerProjection: input.writerProjection,\n ...projectionVerificationOptions(input),\n });\n let unavailableRawHistory:\n | { cause: RawHistoryUnavailableCause; contentKeyEpoch: number }\n | undefined;\n\n for (const contentKeyEpoch of missingContentKeyEpochs) {\n const responseUpdates =\n updatesByContentKeyEpoch.get(contentKeyEpoch) ?? missingUpdates;\n const bundle = requireContentKeyBundle(\n bundlesByEpoch,\n contentKeyEpoch,\n responseUpdates,\n );\n try {\n contentKeysByEpoch.set(\n bundle.contentKeyEpoch,\n await unwrapHistoricalContentKey({\n bundle,\n collectedKeks,\n documentId: input.writerProjection.documentId,\n updates: responseUpdates,\n }),\n );\n } catch (error) {\n if (input.historyMode === \"raw\" && isRawHistoryUnavailableCause(error)) {\n unavailableRawHistory ??= { cause: error, contentKeyEpoch };\n continue;\n }\n throwDocumentSyncContentKeyFailure({\n cause: error,\n updates: responseUpdates,\n });\n }\n }\n\n if (unavailableRawHistory) {\n await throwRawHistoryUnavailable({\n contentKeysByEpoch,\n response: input.response,\n unavailable: unavailableRawHistory,\n validate: input.onRawHistoryUnavailable,\n });\n }\n\n return contentKeysByEpoch;\n}\n"]}
@@ -0,0 +1,14 @@
1
+ import { withMetadataRootReload } from "./groupMetadata/groupMetadataErrors.js";
2
+ import { createRuntimeGroupMetadataAccess } from "./groupMetadata/groupMetadataRuntime.js";
3
+ import { verifyRuntimeGroupMetadataAuthority } from "./groupMetadata/runtimeGroupMetadataAuthority.js";
4
+ import { createRuntimeCurrentGroupShare, createRuntimeCurrentSharePrincipalPolicy, } from "./groupShare/index.js";
5
+ /** The organization operations the composition root hands container contents. */
6
+ export const containerContentsOrganizationHost = {
7
+ createCurrentGroupShare: createRuntimeCurrentGroupShare,
8
+ createCurrentGroupPolicyReader: createRuntimeCurrentSharePrincipalPolicy,
9
+ groupMetadataNameReader: (runtime, organizationId, stillCurrent) => createRuntimeGroupMetadataAccess(runtime, organizationId, stillCurrent)
10
+ .readName,
11
+ verifyGroupMetadataAuthority: verifyRuntimeGroupMetadataAuthority,
12
+ withMetadataRootReload,
13
+ };
14
+ //# sourceMappingURL=containerContentsHost.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"containerContentsHost.js","sourceRoot":"","sources":["containerContentsHost.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,sBAAsB,EAAE,MAAM,qCAAqC,CAAC;AAC7E,OAAO,EAAE,gCAAgC,EAAE,MAAM,sCAAsC,CAAC;AACxF,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,8BAA8B,EAC9B,wCAAwC,GACzC,MAAM,cAAc,CAAC;AAEtB,iFAAiF;AACjF,MAAM,CAAC,MAAM,iCAAiC,GAC5C;IACE,uBAAuB,EAAE,8BAA8B;IACvD,8BAA8B,EAAE,wCAAwC;IACxE,uBAAuB,EAAE,CAAC,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,EAAE,CACjE,gCAAgC,CAAC,OAAO,EAAE,cAAc,EAAE,YAAY,CAAC;SACpE,QAAQ;IACb,4BAA4B,EAAE,mCAAmC;IACjE,sBAAsB;CACvB,CAAC","sourcesContent":["import type { ContainerContentsOrganizationHost } from \"../container-contents\";\nimport { withMetadataRootReload } from \"./groupMetadata/groupMetadataErrors\";\nimport { createRuntimeGroupMetadataAccess } from \"./groupMetadata/groupMetadataRuntime\";\nimport { verifyRuntimeGroupMetadataAuthority } from \"./groupMetadata/runtimeGroupMetadataAuthority\";\nimport {\n createRuntimeCurrentGroupShare,\n createRuntimeCurrentSharePrincipalPolicy,\n} from \"./groupShare\";\n\n/** The organization operations the composition root hands container contents. */\nexport const containerContentsOrganizationHost: ContainerContentsOrganizationHost =\n {\n createCurrentGroupShare: createRuntimeCurrentGroupShare,\n createCurrentGroupPolicyReader: createRuntimeCurrentSharePrincipalPolicy,\n groupMetadataNameReader: (runtime, organizationId, stillCurrent) =>\n createRuntimeGroupMetadataAccess(runtime, organizationId, stillCurrent)\n .readName,\n verifyGroupMetadataAuthority: verifyRuntimeGroupMetadataAuthority,\n withMetadataRootReload,\n };\n"]}
@@ -12,7 +12,7 @@ interface CurrentOrganizationAuthorityInput {
12
12
  /** One directory view with bounded, authenticated current artifacts for its groups. */
13
13
  export declare function loadCurrentOrganizationAuthority(input: CurrentOrganizationAuthorityInput): Promise<{
14
14
  admins: ResolvedPrincipalPolicyCurrent;
15
- descriptor: import("../../data/principals/organizationAuthorityDescriptor.js").OrganizationAuthorityDescriptor;
15
+ descriptor: import("../../data/principalContracts/organizationAuthorityDescriptor.js").OrganizationAuthorityDescriptor;
16
16
  directory: ResolvedPrincipalPolicyCurrent;
17
17
  stillCurrent: () => boolean;
18
18
  readGroup(groupId: string, reference?: ReferencedPrincipalHead): Promise<ResolvedPrincipalPolicyCurrent>;
@@ -2,7 +2,7 @@ import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
3
3
  import { KeyingCheckpointRepository } from "../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
4
  import { assertCurrentMatchesVerifiedPolicy } from "../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent.js";
5
- import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../data/principals/organizationAuthorityDescriptor.js";
5
+ import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../data/principalContracts/organizationAuthorityDescriptor.js";
6
6
  import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
7
7
  /** One directory view with bounded, authenticated current artifacts for its groups. */
8
8
  export async function loadCurrentOrganizationAuthority(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAgB/F,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAwC;IAExC,IAAI,KAAK,CAAC,qBAAqB;QAC7B,oBAAoB,CAClB,KAAK,CAAC,qBAAqB,EAC3B,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,IAAI,EAAE,CAAC;IAChD,MAAM,OAAO,GAAG,CAAC,SAA0C,EAAE,EAAE,CAC7D,KAAK,CAAC,oBAAoB,CAAC;QACzB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,SAAS,IAAI,SAAS;QACjC,kBAAkB,EAAE,IAAI;QACxB,aAAa;QACb,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CA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AAC;IACxD,MAAM,kCAAkC,CAAC,KAAK,CAAC,CAAC;IAChD,IAAI,CAAC,6BAA6B,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC;QAC9D,MAAM,IAAI,oCAAoC,CAC5C,iEAAiE,CAClE,CAAC;IACJ,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAqC,EACrC,SAAyC;IAEzC,MAAM,UAAU,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACxC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,cAAc;QACvC,MAAM,CAAC,WAAW,KAAK,SAAS,CAAC,MAAM,CAAC,WAAW,CACtD,CAAC;IACF,IACE,CAAC,UAAU;QACX,CAAC,6BAA6B,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC;QAExE,MAAM,IAAI,oCAAoC,CAC5C,4DAA4D,CAC7D,CAAC;AACN,CAAC;AAED,SAAS,sBAAsB,CAC7B,KAAqC,EACrC,QAAiC;IAEjC,MAAM,SAAS,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACvC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,OAAO;QAChC,MAAM,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,SAAS,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n PrincipalPolicyCurrentResolver as CurrentPolicyResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
1
+ {"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,+DAA+D,CAAC;AACvE,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAgB/F,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAwC;IAExC,IAAI,KAAK,CAAC,qBAAqB;QAC7B,oBAAoB,CAClB,KAAK,CAAC,qBAAqB,EAC3B,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,IAAI,EAAE,CAAC;IAChD,MAAM,OAAO,GAAG,CAAC,SAA0C,EAAE,EAAE,CAC7D,KAAK,CAAC,oBAAoB,CAAC;QACzB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,SAAS,IAAI,S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AK,UAAU,kBAAkB,CAC/B,KAAqC,EACrC,QAAiC;IAEjC,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,kCAAkC,CAAC,KAAK,CAAC,CAAC;IAChD,IAAI,CAAC,6BAA6B,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC;QAC9D,MAAM,IAAI,oCAAoC,CAC5C,iEAAiE,CAClE,CAAC;IACJ,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAqC,EACrC,SAAyC;IAEzC,MAAM,UAAU,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACxC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,cAAc;QACvC,MAAM,CAAC,WAAW,KAAK,SAAS,CAAC,MAAM,CAAC,WAAW,CACtD,CAAC;IACF,IACE,CAAC,UAAU;QACX,CAAC,6BAA6B,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC;QAExE,MAAM,IAAI,oCAAoC,CAC5C,4DAA4D,CAC7D,CAAC;AACN,CAAC;AAED,SAAS,sBAAsB,CAC7B,KAAqC,EACrC,QAAiC;IAEjC,MAAM,SAAS,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACvC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,OAAO;QAChC,MAAM,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,SAAS,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n PrincipalPolicyCurrentResolver as CurrentPolicyResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.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 { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
6
6
  import { assertMetadataRootBinding } from "./groupMetadataRootBinding.js";
@@ -1 +1 @@
1
- {"version":3,"file":"currentGroupMetadataAuthority.js","sourceRoot":"","sources":["currentGroupMetadataAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAClG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,C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;QAC7D,MAAM,QAAQ,GAAG,CAAC,OAAe,EAAE,EAAE,CACnC,KAAK,CAAC,wBAAwB,CAAC,IAAI,CACjC,CAAC,IAAI,EAAE,EAAE,CACP,IAAI,CAAC,aAAa,KAAK,OAAO,IAAI,IAAI,CAAC,WAAW,KAAK,OAAO,CACjE,CAAC;QACJ,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,SAAS,CACtC,YAAY,EACZ,QAAQ,CAAC,YAAY,CAAC,CACvB,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,SAAS,CAAC,SAAS,CACvC,aAAa,EACb,QAAQ,CAAC,aAAa,CAAC,CACxB,CAAC;QACF,yBAAyB,CAAC;YACxB,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,SAAS,EAAE;gBACT,UAAU,EAAE,SAAS,CAAC,UAAU;gBAChC,YAAY;gBACZ,aAAa;gBACb,WAAW,EAAE,MAAM,CAAC,MAAM;aAC3B;YACD,OAAO;YACP,KAAK;SACN,CAAC,CAAC;QACH,mCAAmC,CACjC,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,MAAM,CAAC,YAAY,EAAE,IAAI,OAAO,CAAC,YAAY,EAAE,CACxE,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\n/** Authenticate metadata-root grants with current policies and only its cited predecessors. */\nexport function createCurrentGroupMetadataContainerVerifier(\n input: Omit<\n Parameters<typeof loadCurrentOrganizationAuthority>[0],\n \"organizationReference\"\n >,\n) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const authority = await loadCurrentOrganizationAuthority({\n ...input,\n organizationReference,\n });\n await createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n })(state, organizationReference);\n };\n}\n\n/** Reuse one mutation's verified authority without broadening its lease or scope. */\nexport function createSelectedCurrentGroupMetadataContainerVerifier(input: {\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n const { authority } = input;\n const stillCurrent = () => input.stillCurrent() && authority.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n if (organizationReference) {\n if (\n organizationReference.principalType !== \"organization\" ||\n organizationReference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n if (\n !principalHeadMatchesReference(\n authority.directory.policy.state,\n organizationReference,\n )\n )\n throw new ProjectionDependencyUnavailableError(\n \"Metadata root belongs to a changed organization directory\",\n );\n }\n const { adminGroupId, memberGroupId } = authority.descriptor;\n const citation = (groupId: string) =>\n state.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === groupId,\n );\n const admins = await authority.readGroup(\n adminGroupId,\n citation(adminGroupId),\n );\n const members = await authority.readGroup(\n memberGroupId,\n citation(memberGroupId),\n );\n assertMetadataRootBinding({\n organizationId: input.organizationId,\n authority: {\n descriptor: authority.descriptor,\n adminGroupId,\n memberGroupId,\n adminPolicy: admins.policy,\n },\n members,\n state,\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && admins.stillCurrent() && members.stillCurrent(),\n );\n };\n}\n"]}
1
+ {"version":3,"file":"currentGroup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AAK,KAAK,CAAC,cAAc;gBAE1D,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,+CAA+C,CAChD,CAAC;YACJ,IACE,CAAC,6BAA6B,CAC5B,SAAS,CAAC,SAAS,CAAC,MAAM,CAAC,KAAK,EAChC,qBAAqB,CACtB;gBAED,MAAM,IAAI,oCAAoC,CAC5C,2DAA2D,CAC5D,CAAC;QACN,CAAC;QACD,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,GAAG,SAAS,CAAC,UAAU,CAAC;QAC7D,MAAM,QAAQ,GAAG,CAAC,OAAe,EAAE,EAAE,CACnC,KAAK,CAAC,wBAAwB,CAAC,IAAI,CACjC,CAAC,IAAI,EAAE,EAAE,CACP,IAAI,CAAC,aAAa,KAAK,OAAO,IAAI,IAAI,CAAC,WAAW,KAAK,OAAO,CACjE,CAAC;QACJ,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,SAAS,CACtC,YAAY,EACZ,QAAQ,CAAC,YAAY,CAAC,CACvB,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,SAAS,CAAC,SAAS,CACvC,aAAa,EACb,QAAQ,CAAC,aAAa,CAAC,CACxB,CAAC;QACF,yBAAyB,CAAC;YACxB,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,SAAS,EAAE;gBACT,UAAU,EAAE,SAAS,CAAC,UAAU;gBAChC,YAAY;gBACZ,aAAa;gBACb,WAAW,EAAE,MAAM,CAAC,MAAM;aAC3B;YACD,OAAO;YACP,KAAK;SACN,CAAC,CAAC;QACH,mCAAmC,CACjC,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,MAAM,CAAC,YAAY,EAAE,IAAI,OAAO,CAAC,YAAY,EAAE,CACxE,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\n/** Authenticate metadata-root grants with current policies and only its cited predecessors. */\nexport function createCurrentGroupMetadataContainerVerifier(\n input: Omit<\n Parameters<typeof loadCurrentOrganizationAuthority>[0],\n \"organizationReference\"\n >,\n) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const authority = await loadCurrentOrganizationAuthority({\n ...input,\n organizationReference,\n });\n await createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n })(state, organizationReference);\n };\n}\n\n/** Reuse one mutation's verified authority without broadening its lease or scope. */\nexport function createSelectedCurrentGroupMetadataContainerVerifier(input: {\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly organizationId: string;\n readonly stillCurrent: () => boolean;\n}) {\n return async (\n state: ContainerAccessManifestState,\n organizationReference?: ReferencedPrincipalHead,\n ): Promise<void> => {\n const { authority } = input;\n const stillCurrent = () => input.stillCurrent() && authority.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n if (organizationReference) {\n if (\n organizationReference.principalType !== \"organization\" ||\n organizationReference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n if (\n !principalHeadMatchesReference(\n authority.directory.policy.state,\n organizationReference,\n )\n )\n throw new ProjectionDependencyUnavailableError(\n \"Metadata root belongs to a changed organization directory\",\n );\n }\n const { adminGroupId, memberGroupId } = authority.descriptor;\n const citation = (groupId: string) =>\n state.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === groupId,\n );\n const admins = await authority.readGroup(\n adminGroupId,\n citation(adminGroupId),\n );\n const members = await authority.readGroup(\n memberGroupId,\n citation(memberGroupId),\n );\n assertMetadataRootBinding({\n organizationId: input.organizationId,\n authority: {\n descriptor: authority.descriptor,\n adminGroupId,\n memberGroupId,\n adminPolicy: admins.policy,\n },\n members,\n state,\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && admins.stillCurrent() && members.stillCurrent(),\n );\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"groupMetadataBinding.js","sourceRoot":"","sources":["groupMetadataBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAItD,gFAAgF;AAChF,MAAM,UAAU,0BAA0B,CACxC,MAGC,EACD,UAA2C;IAE3C,MAAM,OAAO,GAAG,MAAM,CAAC,YAAY,CAAC,WAAW,CAAC;IAChD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;IACrE,MAAM,YAAY,GAChB,OAAO,KAAK,UAAU,CAAC,YAAY;QACjC,CAAC,CAAC,QAAQ;QACV,CAAC,CAAC,OAAO,KAAK,UAAU,CAAC,aAAa;YACpC,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,IAAI,CAAC;IACb,IACE,MAAM,IAAI,QAAQ;QAChB,CAAC,CAAC,QAAQ,CAAC,IAAI,KAAK,YAAY;QAChC,CAAC,CAAC,YAAY,KAAK,IAAI;YACrB,QAAQ,CAAC,cAAc,KAAK,UAAU,CAAC,cAAc;YACrD,QAAQ,CAAC,OAAO,KAAK,OAAO,EAChC,CAAC;QACD,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { readGroupMetadata } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { OrganizationAuthorityDescriptor } from \"../../../data/principals/organizationAuthorityDescriptor\";\n\n/** Built-in labels derive from the role assigned by the signed organization. */\nexport function assertGroupMetadataBinding(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentPayload\"\n >,\n descriptor: OrganizationAuthorityDescriptor,\n): void {\n const groupId = bundle.currentState.principalId;\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n const expectedRole =\n groupId === descriptor.adminGroupId\n ? \"admins\"\n : groupId === descriptor.memberGroupId\n ? \"members\"\n : null;\n if (\n \"role\" in metadata\n ? metadata.role !== expectedRole\n : expectedRole !== null ||\n metadata.organizationId !== descriptor.organizationId ||\n metadata.groupId !== groupId\n ) {\n throw new Error(\n \"Group metadata does not match the signed organization directory\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"groupMetadataBinding.js","sourceRoot":"","sources":["groupMetadataBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAItD,gFAAgF;AAChF,MAAM,UAAU,0BAA0B,CACxC,MAGC,EACD,UAA2C;IAE3C,MAAM,OAAO,GAAG,MAAM,CAAC,YAAY,CAAC,WAAW,CAAC;IAChD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,CAAC;IACrE,MAAM,YAAY,GAChB,OAAO,KAAK,UAAU,CAAC,YAAY;QACjC,CAAC,CAAC,QAAQ;QACV,CAAC,CAAC,OAAO,KAAK,UAAU,CAAC,aAAa;YACpC,CAAC,CAAC,SAAS;YACX,CAAC,CAAC,IAAI,CAAC;IACb,IACE,MAAM,IAAI,QAAQ;QAChB,CAAC,CAAC,QAAQ,CAAC,IAAI,KAAK,YAAY;QAChC,CAAC,CAAC,YAAY,KAAK,IAAI;YACrB,QAAQ,CAAC,cAAc,KAAK,UAAU,CAAC,cAAc;YACrD,QAAQ,CAAC,OAAO,KAAK,OAAO,EAChC,CAAC;QACD,MAAM,IAAI,KAAK,CACb,iEAAiE,CAClE,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { readGroupMetadata } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { OrganizationAuthorityDescriptor } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\n\n/** Built-in labels derive from the role assigned by the signed organization. */\nexport function assertGroupMetadataBinding(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentPayload\"\n >,\n descriptor: OrganizationAuthorityDescriptor,\n): void {\n const groupId = bundle.currentState.principalId;\n const metadata = readGroupMetadata(bundle.currentPayload.ciphertext);\n const expectedRole =\n groupId === descriptor.adminGroupId\n ? \"admins\"\n : groupId === descriptor.memberGroupId\n ? \"members\"\n : null;\n if (\n \"role\" in metadata\n ? metadata.role !== expectedRole\n : expectedRole !== null ||\n metadata.organizationId !== descriptor.organizationId ||\n metadata.groupId !== groupId\n ) {\n throw new Error(\n \"Group metadata does not match the signed organization directory\",\n );\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
2
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
3
- import { principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../../data/principals/organizationAuthorityDescriptor.js";
4
- import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
3
+ import { principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
4
+ import { principalPolicyReferenceFromBundle } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
5
5
  import { verifyDirectoryGroup } from "../groupNames/groupNameUniqueness.js";
6
6
  import { loadGroupNameDirectoryAuthority } from "../groupNames/organizationGroupNamePolicies.js";
7
7
  import { assertMetadataRootBinding } from "./groupMetadataRootBinding.js";
@@ -1 +1 @@
1
- {"version":3,"file":"group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C;QACD,IAAI,CAAC,SAAS;YACZ,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACpE,MAAM,UAAU,GAAG,4BAA4B,CAC7C,SAAS,CAAC,UAAU,EACpB,SAAS,CAAC,aAAa,CACxB,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,oBAAoB,CACxC;YACE,GAAG,KAAK;YACR,UAAU,EAAE,SAAS,CAAC,UAAU;YAChC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;SAC/C,EACD,UAAU,CACX,CAAC;QACF,yBAAyB,CAAC;YACxB,SAAS;YACT,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,KAAK;SACN,CAAC,CAAC;QACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAC1D,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerAccessManifestState } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport { verifyDirectoryGroup } from \"../groupNames/groupNameUniqueness\";\nimport { loadGroupNameDirectoryAuthority } from \"../groupNames/organizationGroupNamePolicies\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\ntype Input = Omit<\n Parameters<typeof loadGroupNameDirectoryAuthority>[0],\n \"organizationPolicyReference\"\n> & { readonly reportSecurityIncident: SecurityIncidentReporter };\n\n/** A public system slot alone cannot bind a self-authorized root to an organization. */\nexport function createGroupMetadataContainerVerifier(input: Input) {\n return async (state: ContainerAccessManifestState): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const cached = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n let authority = await loadGroupNameDirectoryAuthority({\n ...input,\n organizationPolicyReference: cached\n ? principalPolicyReferenceFromBundle(cached)\n : null,\n });\n if (\n cached &&\n authority &&\n state.referencedPrincipalHeads.some(\n (head) =>\n !authority?.descriptor.groupHeads.some((known) =>\n principalHeadMatchesReference(head, known),\n ),\n )\n ) {\n authority = await loadGroupNameDirectoryAuthority(input);\n }\n if (!authority)\n throw new Error(\"Organization metadata authority is unavailable\");\n const memberHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.memberGroupId,\n );\n const members = await verifyDirectoryGroup(\n {\n ...input,\n descriptor: authority.descriptor,\n externalAuthority: authority.externalAuthority,\n },\n memberHead,\n );\n assertMetadataRootBinding({\n authority,\n members,\n organizationId: input.organizationId,\n state,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n };\n}\n"]}
1
+ {"version":3,"file":"groupMetadataContainerAuthority.js","sourceRoot":"","sources":["groupMetadataContainerAuthority.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAElH,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AACzE,OAAO,EAAE,+BAA+B,EAAE,MAAM,6CAA6C,CAAC;AAC9F,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AAOvE,wFAAwF;AACxF,MAAM,UAAU,oCAAoC,CAAC,KAAY;IAC/D,OAAO,KAAK,EAAE,KAAmC,EAAiB,EAAE;QAClE,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,MAAM,GAAG,MAAM,IAAI,+BAA+B,CACtD,KAAK,CAAC,OAAO,CACd,CAAC,yBAAyB,CAAC,cAAc,EAAE,KAAK,CAAC,cAAc,CAAC,CAAC;QAClE,IAAI,SAAS,GAAG,MAAM,+BAA+B,CAAC;YACpD,GAAG,KAAK;YACR,2BAA2B,EAAE,MAAM;gBACjC,CAAC,CAAC,kCAAkC,CAAC,MAAM,CAAC;gBAC5C,CAAC,CAAC,IAAI;SACT,CAAC,CAAC;QACH,IACE,MAAM;YACN,SAAS;YACT,KAAK,CAAC,wBAAwB,CAAC,IAAI,CACjC,CAAC,IAAI,EAAE,EAAE,CACP,CAAC,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAC/C,6BAA6B,CAAC,IAAI,EAAE,KAAK,CAAC,CAC3C,CACJ,EACD,CAAC;YACD,SAAS,GAAG,MAAM,+BAA+B,CAAC,KAAK,CAAC,CAAC;QAC3D,CAAC;QACD,IAAI,CAAC,SAAS;YACZ,MAAM,IAAI,KAAK,CAAC,gDAAgD,CAAC,CAAC;QACpE,MAAM,UAAU,GAAG,4BAA4B,CAC7C,SAAS,CAAC,UAAU,EACpB,SAAS,CAAC,aAAa,CACxB,CAAC;QACF,MAAM,OAAO,GAAG,MAAM,oBAAoB,CACxC;YACE,GAAG,KAAK;YACR,UAAU,EAAE,SAAS,CAAC,UAAU;YAChC,iBAAiB,EAAE,SAAS,CAAC,iBAAiB;SAC/C,EACD,UAAU,CACX,CAAC;QACF,yBAAyB,CAAC;YACxB,SAAS;YACT,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,KAAK;SACN,CAAC,CAAC;QACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IAC1D,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { ContainerAccessManifestState } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport { verifyDirectoryGroup } from \"../groupNames/groupNameUniqueness\";\nimport { loadGroupNameDirectoryAuthority } from \"../groupNames/organizationGroupNamePolicies\";\nimport { assertMetadataRootBinding } from \"./groupMetadataRootBinding\";\n\ntype Input = Omit<\n Parameters<typeof loadGroupNameDirectoryAuthority>[0],\n \"organizationPolicyReference\"\n> & { readonly reportSecurityIncident: SecurityIncidentReporter };\n\n/** A public system slot alone cannot bind a self-authorized root to an organization. */\nexport function createGroupMetadataContainerVerifier(input: Input) {\n return async (state: ContainerAccessManifestState): Promise<void> => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const cached = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n let authority = await loadGroupNameDirectoryAuthority({\n ...input,\n organizationPolicyReference: cached\n ? principalPolicyReferenceFromBundle(cached)\n : null,\n });\n if (\n cached &&\n authority &&\n state.referencedPrincipalHeads.some(\n (head) =>\n !authority?.descriptor.groupHeads.some((known) =>\n principalHeadMatchesReference(head, known),\n ),\n )\n ) {\n authority = await loadGroupNameDirectoryAuthority(input);\n }\n if (!authority)\n throw new Error(\"Organization metadata authority is unavailable\");\n const memberHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.memberGroupId,\n );\n const members = await verifyDirectoryGroup(\n {\n ...input,\n descriptor: authority.descriptor,\n externalAuthority: authority.externalAuthority,\n },\n memberHead,\n );\n assertMetadataRootBinding({\n authority,\n members,\n organizationId: input.organizationId,\n state,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
- import { principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../../data/principals/organizationAuthorityDescriptor.js";
3
- import { principalPolicyEvidenceEntries } from "../../../data/principals/principalPolicyEvidence.js";
2
+ import { principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
3
+ import { principalPolicyEvidenceEntries } from "../../../data/principalContracts/principalPolicyEvidence.js";
4
4
  import { MetadataRootBehindDirectoryError } from "./groupMetadataErrors.js";
5
5
  /** Root bindings consume verified current grants and explicitly retained predecessor citations. */
6
6
  export function assertMetadataRootBinding(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"groupMetadataRootBinding.js","sourceRoot":"","sources":["groupMetadataRootBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAEL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,8BAA8B,EAAE,MAAM,kDAAkD,CAAC;AAClG,OAAO,EAAE,gCAAgC,EAAE,MAAM,uBAAuB,CAAC;AAEzE,mGAAmG;AACnG,MAAM,UAAU,yBAAyB,CAAC,KAUzC;IACC,MAAM,EAAE,SAAS,EAAE,KAAK,EAAE,GAAG,KAAK,CAAC;IACnC,MAAM,QAAQ,GAAG;QACf;YACE,MAAM,EAAE,SAAS,CAAC,WAAW;YAC7B,EAAE,EAAE,SAAS,CAAC,YAAY;YAC1B,KAAK,EAAE,OAAO;YACd,MAAM,EAAE,SAAS,CAAC,WAAW,CAAC,MAAM;SACrC;QACD;YACE,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM;YAC5B,EAAE,EAAE,SAAS,CAAC,aAAa;YAC3B,KAAK,EAAE,MAAM;YACb,MAAM,EAAE,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM;SACpC;KAC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CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;QAC5B,OAAO,IAAI;YACT,CAAC,6BAA6B,CAC5B,IAAI,EACJ,4BAA4B,CAAC,SAAS,CAAC,UAAU,EAAE,IAAI,CAAC,EAAE,CAAC,CAC5D;YACD,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC;YACjC,CAAC,CAAC,EAAE,CAAC;IACT,CAAC,CAAC,CAAC;IACH,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IACpC,0EAA0E;IAC1E,iEAAiE;IACjE,IACE,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,EAAE,EAAE,CACpC,8BAA8B,CAAC,MAAM,CAAC,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CACxD,6BAA6B,CAAC,KAAK,EAAE,IAAI,CAAC,CAC3C,CACF;QAED,MAAM,IAAI,gCAAgC,EAAE,CAAC;IAC/C,MAAM,OAAO,CAAC;AAChB,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n} from \"@tearleads/crypto\";\nimport {\n type OrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { principalPolicyEvidenceEntries } from \"../../../data/principals/principalPolicyEvidence\";\nimport { MetadataRootBehindDirectoryError } from \"./groupMetadataErrors\";\n\n/** Root bindings consume verified current grants and explicitly retained predecessor citations. */\nexport function assertMetadataRootBinding(input: {\n readonly authority: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n readonly adminPolicy: PrincipalPolicyAuthorization;\n };\n readonly members: { readonly policy: PrincipalPolicyAuthorization };\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n}): void {\n const { authority, state } = input;\n const expected = [\n {\n policy: authority.adminPolicy,\n id: authority.adminGroupId,\n level: \"admin\",\n grants: authority.adminPolicy.grants,\n },\n {\n policy: input.members.policy,\n id: authority.memberGroupId,\n level: \"read\",\n grants: input.members.policy.grants,\n },\n ];\n const cited = (groupId: string) =>\n state.referencedPrincipalHeads.find(\n (head) => head.principalType === \"group\" && head.principalId === groupId,\n );\n const unbound = new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization metadata root is not bound to the reserved group grants\",\n );\n if (\n state.organizationId !== input.organizationId ||\n state.parentContainerId !== null ||\n state.directGrants.length !== 2 ||\n state.referencedPrincipalHeads.length !== 2 ||\n expected.some(\n (role) =>\n !principalHeadMatchesReference(\n role.policy.state,\n requireOrganizationGroupHead(authority.descriptor, role.id),\n ) ||\n !role.grants.some(\n (grant) =>\n grant.containerId === state.containerId &&\n grant.accessLevel === role.level,\n ) ||\n !state.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === role.id &&\n grant.accessLevel === role.level,\n ) ||\n !cited(role.id),\n )\n )\n throw unbound;\n const superseded = expected.flatMap((role) => {\n const head = cited(role.id);\n return head &&\n !principalHeadMatchesReference(\n head,\n requireOrganizationGroupHead(authority.descriptor, role.id),\n )\n ? [{ policy: role.policy, head }]\n : [];\n });\n if (superseded.length === 0) return;\n // A root read before a reserved-group commit cites a verified predecessor\n // of the directory's head; any other head is not an honest race.\n if (\n superseded.every(({ policy, head }) =>\n principalPolicyEvidenceEntries(policy).some(({ state }) =>\n principalHeadMatchesReference(state, head),\n ),\n )\n )\n throw new MetadataRootBehindDirectoryError();\n throw unbound;\n}\n"]}
1
+ {"version":3,"file":"groupMetadataRootBinding.js","sourceRoot":"","sources":["groupMetadataRootBinding.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAEL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,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AAO,CAAC;AAChB,CAAC","sourcesContent":["import {\n type ContainerAccessManifestState,\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n} from \"@tearleads/crypto\";\nimport {\n type OrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { principalPolicyEvidenceEntries } from \"../../../data/principalContracts/principalPolicyEvidence\";\nimport { MetadataRootBehindDirectoryError } from \"./groupMetadataErrors\";\n\n/** Root bindings consume verified current grants and explicitly retained predecessor citations. */\nexport function assertMetadataRootBinding(input: {\n readonly authority: {\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n readonly adminPolicy: PrincipalPolicyAuthorization;\n };\n readonly members: { readonly policy: PrincipalPolicyAuthorization };\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n}): void {\n const { authority, state } = input;\n const expected = [\n {\n policy: authority.adminPolicy,\n id: authority.adminGroupId,\n level: \"admin\",\n grants: authority.adminPolicy.grants,\n },\n {\n policy: input.members.policy,\n id: authority.memberGroupId,\n level: \"read\",\n grants: input.members.policy.grants,\n },\n ];\n const cited = (groupId: string) =>\n state.referencedPrincipalHeads.find(\n (head) => head.principalType === \"group\" && head.principalId === groupId,\n );\n const unbound = new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization metadata root is not bound to the reserved group grants\",\n );\n if (\n state.organizationId !== input.organizationId ||\n state.parentContainerId !== null ||\n state.directGrants.length !== 2 ||\n state.referencedPrincipalHeads.length !== 2 ||\n expected.some(\n (role) =>\n !principalHeadMatchesReference(\n role.policy.state,\n requireOrganizationGroupHead(authority.descriptor, role.id),\n ) ||\n !role.grants.some(\n (grant) =>\n grant.containerId === state.containerId &&\n grant.accessLevel === role.level,\n ) ||\n !state.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === role.id &&\n grant.accessLevel === role.level,\n ) ||\n !cited(role.id),\n )\n )\n throw unbound;\n const superseded = expected.flatMap((role) => {\n const head = cited(role.id);\n return head &&\n !principalHeadMatchesReference(\n head,\n requireOrganizationGroupHead(authority.descriptor, role.id),\n )\n ? [{ policy: role.policy, head }]\n : [];\n });\n if (superseded.length === 0) return;\n // A root read before a reserved-group commit cites a verified predecessor\n // of the directory's head; any other head is not an honest race.\n if (\n superseded.every(({ policy, head }) =>\n principalPolicyEvidenceEntries(policy).some(({ state }) =>\n principalHeadMatchesReference(state, head),\n ),\n )\n )\n throw new MetadataRootBehindDirectoryError();\n throw unbound;\n}\n"]}
@@ -2,8 +2,8 @@ import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { throwKeyingVerificationErrorWithContext } from "../../../data/keyingProjectionVerification/error.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
4
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
5
- import { principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
6
- import { principalPolicyReferenceFromBundle, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../../data/principals/principalPolicyAdminSigners.js";
5
+ import { principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
6
+ import { principalPolicyReferenceFromBundle, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
7
7
  import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../../principals/policyVerification.js";
8
8
  import { GroupMetadataUnreadableError } from "../groupMetadata/groupMetadataAccess.js";
9
9
  import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
@@ -1 +1 @@
1
- {"version":3,"file":"groupNameUniqueness.js","sourceRoot":"","sources":["groupNameUniqueness.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CA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E;IAC5E,2EAA2E;IAC3E,+CAA+C;IAC/C,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,OAAO,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../../principals/policyVerification\";\nimport { GroupMetadataUnreadableError } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport {\n canonicalGroupNameKey,\n type GroupPolicyNameReader,\n readGroupPolicyPayloadName,\n} from \"../principalPolicy/principalPolicyRequest\";\n\nexport interface DirectoryGroupWalkInput {\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly apiClient: CurrentPrincipalPolicyReader;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The walk's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\ntype DirectoryGroupHead = OrganizationAuthorityDescriptor[\"groupHeads\"][number];\n\ninterface VerifiedDirectoryGroup {\n readonly bundle: PrincipalPolicyBundleResponse;\n /** Null when the signed name does not decrypt for any member. */\n readonly name: string | null;\n readonly nameKey: string | null;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\n/**\n * Loads one directory group at its committed head: from the local retained\n * bundles when they already hold that head, and from the API otherwise.\n */\nasync function loadDirectoryGroupBundle(\n input: DirectoryGroupWalkInput,\n head: DirectoryGroupHead,\n) {\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", head.principalId);\n const cached = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundleForReference(head, localCheckpoint);\n const bundle =\n cached ??\n (await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n head.principalId,\n ));\n if (!bundle) {\n throw new Error(\n `Organization directory group ${head.principalId} could not be loaded`,\n );\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n head,\n )\n ) {\n // Head drift is reachable by a concurrent admin mutation, so it is a\n // plain error to retry on, not an incident (as in the share path). The\n // typed errors stay for signature and projection failures.\n throw new Error(\n \"Organization directory group policy does not match the signed organization directory\",\n );\n }\n return { bundle, localCheckpoint };\n}\n\n/**\n * A bundle served from local retention was verified when it was retained, and\n * is verified again here on purpose: the re-check costs local CPU only, and it\n * keeps the name a group vouches for independent of what any earlier caller\n * trusted at retention time.\n */\nexport async function verifyDirectoryGroup(\n input: DirectoryGroupWalkInput,\n head: DirectoryGroupHead,\n): Promise<VerifiedDirectoryGroup> {\n const { bundle, localCheckpoint } = await loadDirectoryGroupBundle(\n input,\n head,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(\n `Organization directory group signer key could not be loaded (${signerPublicKeys.error})`,\n );\n }\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: head,\n loadExternalAuthority: async () => input.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Organization directory group verification failed\",\n );\n }\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n assertGroupMetadataBinding(bundle, input.descriptor);\n const name = await readDirectoryGroupName(input, bundle);\n return {\n bundle,\n name,\n nameKey: name === null ? null : canonicalGroupNameKey(name),\n policy: verified.value,\n };\n}\n\n/**\n * A verified group whose name no member can open has no name to select by. The\n * walk isolates it rather than failing every name in the organization, but it\n * still records the incident: only a dishonest admin signs such a name.\n */\nexport async function readDirectoryGroupName(\n input: Pick<\n DirectoryGroupWalkInput,\n \"readEncryptedName\" | \"reportSecurityIncident\" | \"organizationId\"\n >,\n bundle: Parameters<typeof readGroupPolicyPayloadName>[0],\n): Promise<string | null> {\n try {\n return await readGroupPolicyPayloadName(bundle, input.readEncryptedName);\n } catch (error) {\n if (!(error instanceof GroupMetadataUnreadableError)) throw error;\n await input.reportSecurityIncident(\n new KeyingVerificationError(\n \"invalid_shape\",\n \"Signed group name does not open under the cited metadata key\",\n ),\n {\n evidenceHashes: { stateHash: bundle.currentState.stateHash },\n objectId: bundle.currentState.principalId,\n objectKind: \"principal\",\n operation: \"organization.groupName\",\n organizationId: input.organizationId,\n },\n );\n return null;\n }\n}\n\n/**\n * Signed group names are the only authenticated label a member can choose a\n * group by, and the API does not make them unique within an organization. So\n * uniqueness is enforced here, where a name enters: before an admin signs a\n * new group, every group committed in the signed organization directory\n * (the reserved Admins and Members groups included) is loaded, verified\n * against its directory head, and its committed name compared by canonical\n * key. A share then needs only the target's verified name. A compromised\n * server cannot mint a signed group, so it cannot create the duplicate this\n * check refuses.\n *\n * The walk is fail-closed: one group that cannot be loaded or verified blocks\n * the creation, since an unverifiable group could carry any name. A verified\n * group whose name does not decrypt is skipped: no member can open that name,\n * so it cannot collide with one. It runs the\n * loads in parallel and retains every verified bundle, so a later creation\n * finds unchanged groups locally and fetches only those whose head moved.\n */\nconst DIRECTORY_WALK_CONCURRENCY = 4;\n\n/** Runs `work` over `items` with at most `limit` in flight, keeping order. */\nasync function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n limit: number,\n work: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = [];\n let next = 0;\n const worker = async () => {\n for (;;) {\n const index = next++;\n const item = items[index];\n if (index >= items.length || item === undefined) return;\n results[index] = await work(item);\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(limit, items.length) }, worker),\n );\n return results;\n}\n\nexport async function assertGroupNameUniqueInDirectory(\n input: DirectoryGroupWalkInput & { readonly name: string },\n): Promise<void> {\n const nameKey = canonicalGroupNameKey(input.name);\n // Each verified bundle is retained as soon as it verifies, so a failure\n // later in the walk (or a taken name) still leaves the cache warm for the\n // retry. Retention runs in a transaction on the shared connection, so the\n // writes are chained one after another while the loads stay concurrent.\n const retainedAt = new Date().toISOString();\n let retention: Promise<void> = Promise.resolve();\n const verifyAndRetain = async (\n head: DirectoryGroupHead,\n ): Promise<VerifiedDirectoryGroup> => {\n const group = await verifyDirectoryGroup(input, head);\n retention = retention.then(() =>\n new PrincipalPolicyBundleRepository(\n input.execSql,\n ).retainVerifiedPrincipalPolicyBundle({\n bundle: group.bundle,\n organizationId: input.organizationId,\n policy: group.policy,\n updatedAt: retainedAt,\n }),\n );\n await retention;\n return group;\n };\n const groups = await mapWithConcurrency(\n input.descriptor.groupHeads,\n DIRECTORY_WALK_CONCURRENCY,\n verifyAndRetain,\n );\n // A taken name is user input to correct, not evidence of tampering, so this\n // is a plain error: group creation runs under security-incident reporting,\n // which records every KeyingVerificationError.\n if (groups.some((group) => group.nameKey === nameKey)) {\n throw new Error(\n \"Another signed group in this organization already carries this name\",\n );\n }\n}\n"]}
1
+ {"version":3,"file":"groupNameUniqueness.js","sourceRoot":"","sources":["groupNameUniqueness.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EACL,kCAAkC,EAClC,yDAAyD,GAC1D,MAAM,8DAA8D,CAAC;AAKtE,OAAO,EACL,sCAAsC,EACtC,8BAA8B,GAC/B,MAAM,qCAAqC,CAAC;AAC7C,OAAO,EAAE,4BAA4B,EAAE,MAAM,sCAAsC,CAAC;AACpF,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EACL,qBAAqB,EAErB,0BAA0B,GAC3B,MAAM,2CAA2C,CAAC;AAyBnD;;;GAGG;AACH,KAAK,UAAU,wBAAwB,CACrC,KAA8B,EAC9B,IAAwB;IAExB,MAAM,eAAe,GAAG,MAAM,IAAI,0BAA0B,CAC1D,KAAK,CAAC,OAAO,CACd,CAAC,6BAA6B,CAAC,OAAO,EAAE,IAAI,CAAC,WAAW,CAAC,CAAC;IAC3D,MAAM,MAAM,GAAG,MAAM,IAAI,+BAA+B,CACtD,KAAK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AAI,CAAC,GAAG,EAAE,CAC9B,IAAI,+BAA+B,CACjC,KAAK,CAAC,OAAO,CACd,CAAC,mCAAmC,CAAC;YACpC,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,MAAM,EAAE,KAAK,CAAC,MAAM;YACpB,SAAS,EAAE,UAAU;SACtB,CAAC,CACH,CAAC;QACF,MAAM,SAAS,CAAC;QAChB,OAAO,KAAK,CAAC;IACf,CAAC,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,kBAAkB,CACrC,KAAK,CAAC,UAAU,CAAC,UAAU,EAC3B,0BAA0B,EAC1B,eAAe,CAChB,CAAC;IACF,4EAA4E;IAC5E,2EAA2E;IAC3E,+CAA+C;IAC/C,IAAI,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,OAAO,CAAC,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../../principals/policyVerification\";\nimport { GroupMetadataUnreadableError } from \"../groupMetadata/groupMetadataAccess\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport {\n canonicalGroupNameKey,\n type GroupPolicyNameReader,\n readGroupPolicyPayloadName,\n} from \"../principalPolicy/principalPolicyRequest\";\n\nexport interface DirectoryGroupWalkInput {\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly apiClient: CurrentPrincipalPolicyReader;\n readonly descriptor: OrganizationAuthorityDescriptor;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The walk's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\ntype DirectoryGroupHead = OrganizationAuthorityDescriptor[\"groupHeads\"][number];\n\ninterface VerifiedDirectoryGroup {\n readonly bundle: PrincipalPolicyBundleResponse;\n /** Null when the signed name does not decrypt for any member. */\n readonly name: string | null;\n readonly nameKey: string | null;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\n/**\n * Loads one directory group at its committed head: from the local retained\n * bundles when they already hold that head, and from the API otherwise.\n */\nasync function loadDirectoryGroupBundle(\n input: DirectoryGroupWalkInput,\n head: DirectoryGroupHead,\n) {\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", head.principalId);\n const cached = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundleForReference(head, localCheckpoint);\n const bundle =\n cached ??\n (await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n head.principalId,\n ));\n if (!bundle) {\n throw new Error(\n `Organization directory group ${head.principalId} could not be loaded`,\n );\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n head,\n )\n ) {\n // Head drift is reachable by a concurrent admin mutation, so it is a\n // plain error to retry on, not an incident (as in the share path). The\n // typed errors stay for signature and projection failures.\n throw new Error(\n \"Organization directory group policy does not match the signed organization directory\",\n );\n }\n return { bundle, localCheckpoint };\n}\n\n/**\n * A bundle served from local retention was verified when it was retained, and\n * is verified again here on purpose: the re-check costs local CPU only, and it\n * keeps the name a group vouches for independent of what any earlier caller\n * trusted at retention time.\n */\nexport async function verifyDirectoryGroup(\n input: DirectoryGroupWalkInput,\n head: DirectoryGroupHead,\n): Promise<VerifiedDirectoryGroup> {\n const { bundle, localCheckpoint } = await loadDirectoryGroupBundle(\n input,\n head,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(\n `Organization directory group signer key could not be loaded (${signerPublicKeys.error})`,\n );\n }\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: head,\n loadExternalAuthority: async () => input.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Organization directory group verification failed\",\n );\n }\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n assertGroupMetadataBinding(bundle, input.descriptor);\n const name = await readDirectoryGroupName(input, bundle);\n return {\n bundle,\n name,\n nameKey: name === null ? null : canonicalGroupNameKey(name),\n policy: verified.value,\n };\n}\n\n/**\n * A verified group whose name no member can open has no name to select by. The\n * walk isolates it rather than failing every name in the organization, but it\n * still records the incident: only a dishonest admin signs such a name.\n */\nexport async function readDirectoryGroupName(\n input: Pick<\n DirectoryGroupWalkInput,\n \"readEncryptedName\" | \"reportSecurityIncident\" | \"organizationId\"\n >,\n bundle: Parameters<typeof readGroupPolicyPayloadName>[0],\n): Promise<string | null> {\n try {\n return await readGroupPolicyPayloadName(bundle, input.readEncryptedName);\n } catch (error) {\n if (!(error instanceof GroupMetadataUnreadableError)) throw error;\n await input.reportSecurityIncident(\n new KeyingVerificationError(\n \"invalid_shape\",\n \"Signed group name does not open under the cited metadata key\",\n ),\n {\n evidenceHashes: { stateHash: bundle.currentState.stateHash },\n objectId: bundle.currentState.principalId,\n objectKind: \"principal\",\n operation: \"organization.groupName\",\n organizationId: input.organizationId,\n },\n );\n return null;\n }\n}\n\n/**\n * Signed group names are the only authenticated label a member can choose a\n * group by, and the API does not make them unique within an organization. So\n * uniqueness is enforced here, where a name enters: before an admin signs a\n * new group, every group committed in the signed organization directory\n * (the reserved Admins and Members groups included) is loaded, verified\n * against its directory head, and its committed name compared by canonical\n * key. A share then needs only the target's verified name. A compromised\n * server cannot mint a signed group, so it cannot create the duplicate this\n * check refuses.\n *\n * The walk is fail-closed: one group that cannot be loaded or verified blocks\n * the creation, since an unverifiable group could carry any name. A verified\n * group whose name does not decrypt is skipped: no member can open that name,\n * so it cannot collide with one. It runs the\n * loads in parallel and retains every verified bundle, so a later creation\n * finds unchanged groups locally and fetches only those whose head moved.\n */\nconst DIRECTORY_WALK_CONCURRENCY = 4;\n\n/** Runs `work` over `items` with at most `limit` in flight, keeping order. */\nasync function mapWithConcurrency<T, R>(\n items: ReadonlyArray<T>,\n limit: number,\n work: (item: T) => Promise<R>,\n): Promise<R[]> {\n const results: R[] = [];\n let next = 0;\n const worker = async () => {\n for (;;) {\n const index = next++;\n const item = items[index];\n if (index >= items.length || item === undefined) return;\n results[index] = await work(item);\n }\n };\n await Promise.all(\n Array.from({ length: Math.min(limit, items.length) }, worker),\n );\n return results;\n}\n\nexport async function assertGroupNameUniqueInDirectory(\n input: DirectoryGroupWalkInput & { readonly name: string },\n): Promise<void> {\n const nameKey = canonicalGroupNameKey(input.name);\n // Each verified bundle is retained as soon as it verifies, so a failure\n // later in the walk (or a taken name) still leaves the cache warm for the\n // retry. Retention runs in a transaction on the shared connection, so the\n // writes are chained one after another while the loads stay concurrent.\n const retainedAt = new Date().toISOString();\n let retention: Promise<void> = Promise.resolve();\n const verifyAndRetain = async (\n head: DirectoryGroupHead,\n ): Promise<VerifiedDirectoryGroup> => {\n const group = await verifyDirectoryGroup(input, head);\n retention = retention.then(() =>\n new PrincipalPolicyBundleRepository(\n input.execSql,\n ).retainVerifiedPrincipalPolicyBundle({\n bundle: group.bundle,\n organizationId: input.organizationId,\n policy: group.policy,\n updatedAt: retainedAt,\n }),\n );\n await retention;\n return group;\n };\n const groups = await mapWithConcurrency(\n input.descriptor.groupHeads,\n DIRECTORY_WALK_CONCURRENCY,\n verifyAndRetain,\n );\n // A taken name is user input to correct, not evidence of tampering, so this\n // is a plain error: group creation runs under security-incident reporting,\n // which records every KeyingVerificationError.\n if (groups.some((group) => group.nameKey === nameKey)) {\n throw new Error(\n \"Another signed group in this organization already carries this name\",\n );\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
2
2
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
3
- import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
4
- import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
3
+ import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
4
+ import { principalPolicyReferenceFromBundle } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
5
5
  import { loadOrganizationExternalAdminPolicy } from "../../principals/externalAdminPolicy.js";
6
6
  /** Cached directory policies are reusable only at the exact projected head. */
7
7
  export async function loadGroupNameDirectoryAuthority(input) {
@@ -1 +1 @@
1
- {"version":3,"file":"organizationGroupNamePolicies.js","sourceRoot":"","sources":["organizationGroupNamePolicies.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAE1G,OAAO,EAAE,mCAAmC,EAAE,MAAM,sCAAsC,CAAC;AAW3F,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAAY;IAChE,MAAM,IAAI,GAAG,KAAK,EAAE,SAAkC,EAAE,EAAE;QACxD,MAAM,UAAU,GAAG,MAAM,IAAI,0BAA0B,CACrD,KAAK,CAAC,OAAO,CACd,CAAC,6BAA6B,CAC7B,SAAS,CAAC,aAAa,EACvB,SAAS,CAAC,WAAW,CACtB,CAAC;QACF,MAAM,MAAM,GACV,CAAC,MAAM,IAAI,+BAA+B,CACxC,KAAK,CAAC,OAAO,CACd,CAAC,qCAAqC,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;YAC/D,CAAC,MAAM,KAAK,CAAC,SAAS,CAAC,yBAAyB,CAC9C,SAAS,CAAC,aAAa,EACvB,SAAS,CAAC,WAAW,CACtB,CAAC,CAAC;QACL,IACE,MAAM;YACN,CAAC,6BAA6B,CAC5B,kCAAkC,CAAC,MAAM,CAAC,EAC1C,SAAS,CACV;YAED,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;QACJ,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;IACF,MAAM,YAAY,GAAG,KAAK,CAAC,2BAA2B;QACpD,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,2BAA2B,CAAC;QAC/C,CAAC,CAAC,MAAM,KAAK,CAAC,SAAS,CAAC,yBAAyB,CAC7C,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;IACN,IAAI,CAAC,YAAY;QAAE,OAAO,IAAI,CAAC;IAC/B,OAAO,mCAAmC,CAAC;QACzC,GAAG,KAAK;QACR,mBAAmB,EAAE,2BAA2B,CAAC;YAC/C,IAAI;YACJ,YAAY;YACZ,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC;KACH,CAAC,CAAC;AACL,CAAC;AAED;;;;GAIG;AACH,SAAS,2BAA2B,CAAC,KAMpC;IACC,OAAO;QACL,yBAAyB,EAAE,KAAK,EAAE,IAAI,EAAE,EAAE,EAAE,EAAE;YAC5C,IAAI,IAAI,KAAK,cAAc;gBACzB,OAAO,EAAE,KAAK,KAAK,CAAC,cAAc,CAAC,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC;YACjE,kEAAkE;YAClE,MAAM,UAAU,GAAG,oCAAoC,CACrD,KAAK,CAAC,YAAY,CAAC,cAAc,CAAC,UAAU,CAC7C,CAAC;YACF,MAAM,IAAI,GAAG,UAAU,CAAC,UAAU,CAAC,IAAI,CACrC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,EAAE,CAClC,CAAC;YACF,OAAO,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QACxC,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport type { DirectoryGroupWalkInput } from \"./groupNameUniqueness\";\n\ntype Input = Pick<\n DirectoryGroupWalkInput,\n \"apiClient\" | \"execSql\" | \"organizationId\" | \"resolveTrustedUserIdentity\"\n> & {\n readonly organizationPolicyReference?: ReferencedPrincipalHead | null;\n readonly stillCurrent: () => boolean;\n};\n\n/** Cached directory policies are reusable only at the exact projected head. */\nexport async function loadGroupNameDirectoryAuthority(input: Input) {\n const load = async (reference: ReferencedPrincipalHead) => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const bundle =\n (await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundleForReference(reference, checkpoint)) ??\n (await input.apiClient.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (\n bundle &&\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n reference,\n )\n )\n throw new Error(\n \"Group name authority does not match the projected directory head\",\n );\n return bundle;\n };\n const organization = input.organizationPolicyReference\n ? await load(input.organizationPolicyReference)\n : await input.apiClient.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!organization) return null;\n return loadOrganizationExternalAdminPolicy({\n ...input,\n currentPolicyReader: directoryPinnedPolicyReader({\n load,\n organization,\n organizationId: input.organizationId,\n }),\n });\n}\n\n/**\n * Serves the organization bundle already read and each directory group at the\n * head that organization's directory pins, so the authority check reads the\n * heads the projection cited rather than whatever the server holds now.\n */\nfunction directoryPinnedPolicyReader(input: {\n readonly load: (\n reference: ReferencedPrincipalHead,\n ) => Promise<PrincipalPolicyBundleResponse | null>;\n readonly organization: PrincipalPolicyBundleResponse;\n readonly organizationId: string;\n}): CurrentPrincipalPolicyReader {\n return {\n getCurrentPrincipalPolicy: async (type, id) => {\n if (type === \"organization\")\n return id === input.organizationId ? input.organization : null;\n // Reached only after the organization signature and scope checks.\n const descriptor = parseOrganizationAuthorityDescriptor(\n input.organization.currentPayload.ciphertext,\n );\n const head = descriptor.groupHeads.find(\n (head) => head.principalId === id,\n );\n return head ? input.load(head) : null;\n },\n };\n}\n"]}
1
+ {"version":3,"file":"organizationGroupNamePolicies.js","sourceRoot":"","sources":["organizationGroupNamePolicies.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAElH,OAAO,EAAE,mCAAmC,EAAE,MAAM,sCAAsC,CAAC;AAW3F,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,+BAA+B,CAAC,KAAY;IAChE,MAAM,IAAI,GAAG,KAAK,EAAE,SAAkC,EAAE,EAAE;QACxD,MAAM,UAAU,GAAG,MAAM,IAAI,0BAA0B,CACrD,KAAK,CAAC,OAAO,CACd,CAAC,6BAA6B,CAC7B,SAAS,CAAC,aAAa,EACvB,SAAS,CAAC,WAAW,CACtB,CAAC;QACF,MAAM,MAAM,GACV,CAAC,MAAM,IAAI,+BAA+B,CACxC,KAAK,CAAC,OAAO,CACd,CAAC,qCAAqC,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;YAC/D,CAAC,MAAM,KAAK,CAAC,SAAS,CAAC,yBAAyB,CAC9C,SAAS,CAAC,aAAa,EACvB,SAAS,CAAC,WAAW,CACtB,CAAC,CAAC;QACL,IACE,MAAM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AAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport { loadOrganizationExternalAdminPolicy } from \"../../principals/externalAdminPolicy\";\nimport type { DirectoryGroupWalkInput } from \"./groupNameUniqueness\";\n\ntype Input = Pick<\n DirectoryGroupWalkInput,\n \"apiClient\" | \"execSql\" | \"organizationId\" | \"resolveTrustedUserIdentity\"\n> & {\n readonly organizationPolicyReference?: ReferencedPrincipalHead | null;\n readonly stillCurrent: () => boolean;\n};\n\n/** Cached directory policies are reusable only at the exact projected head. */\nexport async function loadGroupNameDirectoryAuthority(input: Input) {\n const load = async (reference: ReferencedPrincipalHead) => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const bundle =\n (await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundleForReference(reference, checkpoint)) ??\n (await input.apiClient.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (\n bundle &&\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n reference,\n )\n )\n throw new Error(\n \"Group name authority does not match the projected directory head\",\n );\n return bundle;\n };\n const organization = input.organizationPolicyReference\n ? await load(input.organizationPolicyReference)\n : await input.apiClient.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!organization) return null;\n return loadOrganizationExternalAdminPolicy({\n ...input,\n currentPolicyReader: directoryPinnedPolicyReader({\n load,\n organization,\n organizationId: input.organizationId,\n }),\n });\n}\n\n/**\n * Serves the organization bundle already read and each directory group at the\n * head that organization's directory pins, so the authority check reads the\n * heads the projection cited rather than whatever the server holds now.\n */\nfunction directoryPinnedPolicyReader(input: {\n readonly load: (\n reference: ReferencedPrincipalHead,\n ) => Promise<PrincipalPolicyBundleResponse | null>;\n readonly organization: PrincipalPolicyBundleResponse;\n readonly organizationId: string;\n}): CurrentPrincipalPolicyReader {\n return {\n getCurrentPrincipalPolicy: async (type, id) => {\n if (type === \"organization\")\n return id === input.organizationId ? input.organization : null;\n // Reached only after the organization signature and scope checks.\n const descriptor = parseOrganizationAuthorityDescriptor(\n input.organization.currentPayload.ciphertext,\n );\n const head = descriptor.groupHeads.find(\n (head) => head.principalId === id,\n );\n return head ? input.load(head) : null;\n },\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { serializeKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
- import { requireOrganizationGroupHead } from "../../../data/principals/organizationAuthorityDescriptor.js";
4
+ import { requireOrganizationGroupHead } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
5
5
  import { createSelectedCurrentGroupMetadataContainerVerifier } from "../groupMetadata/currentGroupMetadataAuthority.js";
6
6
  import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
7
7
  import { loadCurrentOrganizationMutationAuthority } from "../principalMutations/currentOrganizationMutationAuthority.js";