@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":"recoverScopedPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverScopedPrincipalPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AACpG,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,kCAAkC,EAAE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MAAM,UAAU,mCAAmC,CACjD,OAAmD;IAEnD,OAAO,0CAA0C,CAAC,OAAO,CAAC,CAAC;AAC7D,CAAC;AAED,oEAAoE;AACpE,MAAM,CAAC,MAAM,yCAAyC,GACpD,CAAC,OAAO,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,CAAC,CAAC;AAEnE,KAAK,UAAU,oBAAoB,CACjC,KAAiD,EACjD,OAA6C;IAE7C,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO,EAAE,CAAC;IAClC,OAAO;QACL,WAAW,EAAE,MAAM,2BAA2B,CAC5C,OAAO,EACP,KAAK,CAAC,WAAW,CAAC,aAAa,IAAI,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAC/D;KACF,CAAC;AACJ,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,uCAAuC,CACrD,OAA8B;IAC5B,WAAW,EAAE,IAAI,GAAG,EAAE;IACtB,MAAM,EAAE,IAAI,GAAG,EAAE;CAClB;IAED,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport {\n directoryHistoryProtection,\n scopedGroupHistoryProtection,\n} from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport {\n type PrincipalRecoveryContext,\n PrincipalRecoveryDirectoryAdvanced,\n type RecoveredPolicyDirectory,\n} from \"../recoveryOperation/principalRecoveryDirectory\";\nimport {\n createPrincipalRecoveryReader,\n type PrincipalRecoveryMemo,\n} from \"../recoveryOperation/principalRecoveryMemo\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport { recoverPrincipalHistoryPage } from \"./recoverPrincipalHistoryPage\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\nexport interface RecoverScopedPrincipalPolicyHistoryOptions\n extends PrincipalRecoveryContext {\n readonly reference: ReferencedPrincipalHead;\n /** Optional bounded display history ending before this exclusive version. */\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\nexport interface RecoveredScopedPrincipalPolicyHistory\n extends RecoveredPrincipalPolicyHistory {\n /** Submit these with policy when atomically admitting its organization scope. */\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\n/** Internal result: valid only while every evidence producer behind it is. */\nexport interface ScopedPrincipalPolicyRecovery\n extends RecoveredScopedPrincipalPolicyHistory {\n readonly stillCurrent: () => boolean;\n}\n\nexport type ScopedPrincipalPolicyRecoveryBatch = (\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n) => Promise<ScopedPrincipalPolicyRecovery>;\n\nfunction groupHead(directory: RecoveredPolicyDirectory, principalId: string) {\n const head = directory.descriptor.groupHeads.find(\n (entry) => entry.principalId === principalId,\n );\n if (!head)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Group is absent from the signed organization directory\",\n );\n return head;\n}\n\nfunction authorityHead(state: ReferencedPrincipalHead) {\n return {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\nasync function recoverScopedPolicy(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<ScopedPrincipalPolicyRecovery> {\n if (\n input.reference.principalType === \"organization\" &&\n input.reference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested organization policy is outside its scope\",\n );\n const read = createPrincipalRecoveryReader(input, memo);\n // Reused or derived evidence keeps its producers' lifetimes to its use.\n const stillCurrent = () =>\n !input.signal?.aborted && input.stillCurrent() && read.stillCurrent();\n const directory = await read.directory(\n input.reference.principalType === \"organization\" ? [input.reference] : [],\n );\n if (input.reference.principalType === \"organization\")\n return {\n current: directory.current,\n policy: directory.policy,\n dependencies: [],\n stillCurrent,\n ...(await selectDisplayHistory(input, {\n ...input,\n expectedHead: principalPolicyReferenceFromBundle(directory.current),\n protection: directoryHistoryProtection(input.protection),\n })),\n };\n const expectedHead = groupHead(directory, input.reference.principalId);\n if (input.reference.version > expectedHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n const adminHead = groupHead(directory, directory.descriptor.adminGroupId);\n const isAdmins = expectedHead.principalId === adminHead.principalId;\n let admins: VerifiedPrincipalPolicyCurrent | null = null;\n if (!isAdmins) {\n admins = (await read.admins(adminHead)).policy;\n }\n const loadExternalAuthority = async (\n citations: readonly ReferencedPrincipalHead[],\n ): Promise<PrincipalPolicyExternalAuthority | undefined> => {\n const references = new Map<string, ReferencedPrincipalHead>();\n for (const citation of citations) {\n if (citation.principalId !== adminHead.principalId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Group cites another organization's Admins authority\",\n );\n if (citation.version > adminHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n references.set(`${citation.version}:${citation.stateHash}`, citation);\n }\n if (!references.size) return undefined;\n const recovered = await read.admins(adminHead, [...references.values()]);\n return {\n currentHead: adminHead,\n states: recovered.policy.retainedHistory.map(({ state, projection }) => ({\n head: authorityHead(state),\n projection,\n })),\n };\n };\n const recoveryOptions: RecoverPrincipalPolicyHistoryOptions = {\n ...input,\n expectedHead,\n retainedReferences: [input.reference],\n historyVerification: isAdmins ? \"direct-admins\" : \"standard\",\n ...(isAdmins\n ? {}\n : {\n protection: scopedGroupHistoryProtection(\n input.protection,\n input.organizationId,\n adminHead.principalId,\n ),\n }),\n ...(isAdmins ? {} : { loadExternalAuthority }),\n };\n const recovered = isAdmins\n ? await read.admins(expectedHead, [input.reference])\n : await recoverPrincipalPolicyHistory(recoveryOptions);\n return {\n ...recovered,\n dependencies: admins ? [directory.policy, admins] : [directory.policy],\n stillCurrent,\n ...(await selectDisplayHistory(input, recoveryOptions)),\n };\n}\n\n/** Recover signed directory and strict Admins dependencies without full histories. */\nasync function recoverScopedPrincipalPolicyHistoryInBatch(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<ScopedPrincipalPolicyRecovery> {\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (!options.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal recovery requires an organization scope\",\n );\n const input = {\n historyReader: options.historyReader,\n execSql: options.execSql,\n organizationId: options.organizationId,\n offline: options.offline,\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n signal: options.signal,\n stillCurrent: options.stillCurrent,\n reference: structuredClone(options.reference),\n historyPage: options.historyPage ? { ...options.historyPage } : undefined,\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n // Reject malformed exact citations before any discovery or disposable writes.\n createPrincipalPolicyHistoryVerifier({\n principalId: input.reference.principalId,\n principalType: input.reference.principalType,\n retainedReferences: [input.reference],\n });\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n const recovered = await recoverScopedPolicy(input, memo);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n return recovered;\n } catch (error) {\n if (!(error instanceof PrincipalRecoveryDirectoryAdvanced)) throw error;\n memo?.directories.clear();\n memo?.admins.clear();\n if (input.offline)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested principal evidence is newer than the offline directory\",\n );\n }\n }\n throw new PrincipalHistoryRecoveryRaceError(\n \"Organization directory remains behind the requested policy evidence\",\n );\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n\nexport function recoverScopedPrincipalPolicyHistory(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n return recoverScopedPrincipalPolicyHistoryInBatch(options);\n}\n\n/** Internal unbatched recovery that keeps its result's lifetime. */\nexport const recoverLeasedScopedPrincipalPolicyHistory: ScopedPrincipalPolicyRecoveryBatch =\n (options) => recoverScopedPrincipalPolicyHistoryInBatch(options);\n\nasync function selectDisplayHistory(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n options: RecoverPrincipalPolicyHistoryOptions,\n) {\n if (!input.historyPage) return {};\n return {\n historyPage: await recoverPrincipalHistoryPage(\n options,\n input.historyPage.beforeVersion ?? input.reference.version + 1,\n ),\n };\n}\n\n/** Internal runtime batch: shared results never outlive its operation or caller. */\nexport function createScopedPrincipalPolicyHistoryBatch(\n memo: PrincipalRecoveryMemo = {\n directories: new Map(),\n admins: new Map(),\n },\n): ScopedPrincipalPolicyRecoveryBatch {\n return (options) => recoverScopedPrincipalPolicyHistoryInBatch(options, memo);\n}\n"]}
1
+ {"version":3,"file":"recoverScopedPrincipalPolicyHistory.js","sourceRoot":"","sources":["recoverScopedPrincipalPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AACpG,OAAO,EACL,0BAA0B,EAC1B,4BAA4B,GAC7B,MAAM,0DAA0D,CAAC;AAClE,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AmD;IAEnD,OAAO,0CAA0C,CAAC,OAAO,CAAC,CAAC;AAC7D,CAAC;AAED,oEAAoE;AACpE,MAAM,CAAC,MAAM,yCAAyC,GACpD,CAAC,OAAO,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,CAAC,CAAC;AAEnE,KAAK,UAAU,oBAAoB,CACjC,KAAiD,EACjD,OAA6C;IAE7C,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO,EAAE,CAAC;IAClC,OAAO;QACL,WAAW,EAAE,MAAM,2BAA2B,CAC5C,OAAO,EACP,KAAK,CAAC,WAAW,CAAC,aAAa,IAAI,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAC/D;KACF,CAAC;AACJ,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,uCAAuC,CACrD,OAA8B;IAC5B,WAAW,EAAE,IAAI,GAAG,EAAE;IACtB,MAAM,EAAE,IAAI,GAAG,EAAE;CAClB;IAED,OAAO,CAAC,OAAO,EAAE,EAAE,CAAC,0CAA0C,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAChF,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport {\n directoryHistoryProtection,\n scopedGroupHistoryProtection,\n} from \"../../../data/principals/principalHistoryScopeProtection\";\nimport {\n type PrincipalRecoveryContext,\n PrincipalRecoveryDirectoryAdvanced,\n type RecoveredPolicyDirectory,\n} from \"../recoveryOperation/principalRecoveryDirectory\";\nimport {\n createPrincipalRecoveryReader,\n type PrincipalRecoveryMemo,\n} from \"../recoveryOperation/principalRecoveryMemo\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nimport { recoverPrincipalHistoryPage } from \"./recoverPrincipalHistoryPage\";\nimport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\n\nexport interface RecoverScopedPrincipalPolicyHistoryOptions\n extends PrincipalRecoveryContext {\n readonly reference: ReferencedPrincipalHead;\n /** Optional bounded display history ending before this exclusive version. */\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\nexport interface RecoveredScopedPrincipalPolicyHistory\n extends RecoveredPrincipalPolicyHistory {\n /** Submit these with policy when atomically admitting its organization scope. */\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\n/** Internal result: valid only while every evidence producer behind it is. */\nexport interface ScopedPrincipalPolicyRecovery\n extends RecoveredScopedPrincipalPolicyHistory {\n readonly stillCurrent: () => boolean;\n}\n\nexport type ScopedPrincipalPolicyRecoveryBatch = (\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n) => Promise<ScopedPrincipalPolicyRecovery>;\n\nfunction groupHead(directory: RecoveredPolicyDirectory, principalId: string) {\n const head = directory.descriptor.groupHeads.find(\n (entry) => entry.principalId === principalId,\n );\n if (!head)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Group is absent from the signed organization directory\",\n );\n return head;\n}\n\nfunction authorityHead(state: ReferencedPrincipalHead) {\n return {\n principalType: \"group\" as const,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\nasync function recoverScopedPolicy(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<ScopedPrincipalPolicyRecovery> {\n if (\n input.reference.principalType === \"organization\" &&\n input.reference.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Requested organization policy is outside its scope\",\n );\n const read = createPrincipalRecoveryReader(input, memo);\n // Reused or derived evidence keeps its producers' lifetimes to its use.\n const stillCurrent = () =>\n !input.signal?.aborted && input.stillCurrent() && read.stillCurrent();\n const directory = await read.directory(\n input.reference.principalType === \"organization\" ? [input.reference] : [],\n );\n if (input.reference.principalType === \"organization\")\n return {\n current: directory.current,\n policy: directory.policy,\n dependencies: [],\n stillCurrent,\n ...(await selectDisplayHistory(input, {\n ...input,\n expectedHead: principalPolicyReferenceFromBundle(directory.current),\n protection: directoryHistoryProtection(input.protection),\n })),\n };\n const expectedHead = groupHead(directory, input.reference.principalId);\n if (input.reference.version > expectedHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n const adminHead = groupHead(directory, directory.descriptor.adminGroupId);\n const isAdmins = expectedHead.principalId === adminHead.principalId;\n let admins: VerifiedPrincipalPolicyCurrent | null = null;\n if (!isAdmins) {\n admins = (await read.admins(adminHead)).policy;\n }\n const loadExternalAuthority = async (\n citations: readonly ReferencedPrincipalHead[],\n ): Promise<PrincipalPolicyExternalAuthority | undefined> => {\n const references = new Map<string, ReferencedPrincipalHead>();\n for (const citation of citations) {\n if (citation.principalId !== adminHead.principalId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Group cites another organization's Admins authority\",\n );\n if (citation.version > adminHead.version)\n throw new PrincipalRecoveryDirectoryAdvanced();\n references.set(`${citation.version}:${citation.stateHash}`, citation);\n }\n if (!references.size) return undefined;\n const recovered = await read.admins(adminHead, [...references.values()]);\n return {\n currentHead: adminHead,\n states: recovered.policy.retainedHistory.map(({ state, projection }) => ({\n head: authorityHead(state),\n projection,\n })),\n };\n };\n const recoveryOptions: RecoverPrincipalPolicyHistoryOptions = {\n ...input,\n expectedHead,\n retainedReferences: [input.reference],\n historyVerification: isAdmins ? \"direct-admins\" : \"standard\",\n ...(isAdmins\n ? {}\n : {\n protection: scopedGroupHistoryProtection(\n input.protection,\n input.organizationId,\n adminHead.principalId,\n ),\n }),\n ...(isAdmins ? {} : { loadExternalAuthority }),\n };\n const recovered = isAdmins\n ? await read.admins(expectedHead, [input.reference])\n : await recoverPrincipalPolicyHistory(recoveryOptions);\n return {\n ...recovered,\n dependencies: admins ? [directory.policy, admins] : [directory.policy],\n stillCurrent,\n ...(await selectDisplayHistory(input, recoveryOptions)),\n };\n}\n\n/** Recover signed directory and strict Admins dependencies without full histories. */\nasync function recoverScopedPrincipalPolicyHistoryInBatch(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n memo?: PrincipalRecoveryMemo,\n): Promise<ScopedPrincipalPolicyRecovery> {\n if (options.offline !== undefined && typeof options.offline !== \"boolean\")\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid principal history transport mode\",\n );\n if (!options.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Principal recovery requires an organization scope\",\n );\n const input = {\n historyReader: options.historyReader,\n execSql: options.execSql,\n organizationId: options.organizationId,\n offline: options.offline,\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n signal: options.signal,\n stillCurrent: options.stillCurrent,\n reference: structuredClone(options.reference),\n historyPage: options.historyPage ? { ...options.historyPage } : undefined,\n protection: ownPrincipalHistoryProtection(options.protection),\n };\n try {\n // Reject malformed exact citations before any discovery or disposable writes.\n createPrincipalPolicyHistoryVerifier({\n principalId: input.reference.principalId,\n principalType: input.reference.principalType,\n retainedReferences: [input.reference],\n });\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n const recovered = await recoverScopedPolicy(input, memo);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n return recovered;\n } catch (error) {\n if (!(error instanceof PrincipalRecoveryDirectoryAdvanced)) throw error;\n memo?.directories.clear();\n memo?.admins.clear();\n if (input.offline)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Requested principal evidence is newer than the offline directory\",\n );\n }\n }\n throw new PrincipalHistoryRecoveryRaceError(\n \"Organization directory remains behind the requested policy evidence\",\n );\n } finally {\n input.protection.localKey.fill(0);\n }\n}\n\nexport function recoverScopedPrincipalPolicyHistory(\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n): Promise<RecoveredScopedPrincipalPolicyHistory> {\n return recoverScopedPrincipalPolicyHistoryInBatch(options);\n}\n\n/** Internal unbatched recovery that keeps its result's lifetime. */\nexport const recoverLeasedScopedPrincipalPolicyHistory: ScopedPrincipalPolicyRecoveryBatch =\n (options) => recoverScopedPrincipalPolicyHistoryInBatch(options);\n\nasync function selectDisplayHistory(\n input: RecoverScopedPrincipalPolicyHistoryOptions,\n options: RecoverPrincipalPolicyHistoryOptions,\n) {\n if (!input.historyPage) return {};\n return {\n historyPage: await recoverPrincipalHistoryPage(\n options,\n input.historyPage.beforeVersion ?? input.reference.version + 1,\n ),\n };\n}\n\n/** Internal runtime batch: shared results never outlive its operation or caller. */\nexport function createScopedPrincipalPolicyHistoryBatch(\n memo: PrincipalRecoveryMemo = {\n directories: new Map(),\n admins: new Map(),\n },\n): ScopedPrincipalPolicyRecoveryBatch {\n return (options) => recoverScopedPrincipalPolicyHistoryInBatch(options, memo);\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { PrincipalPolicyBundleResponse, ReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
2
- import type { SecurityIncidentReporter } from "../../../data/shared/securityIncidents.js";
2
+ import { type SecurityIncidentReporter } from "../../../data/shared/securityIncidents.js";
3
3
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
4
4
  import type { TrustedUserIdentityResolver } from "../../../data/trustedUserIdentity/index.js";
5
5
  import type { CurrentPrincipalPolicyReader } from "../currentPrincipalPolicyReader.js";
@@ -1,10 +1,11 @@
1
1
  import { isProjectionVerificationCancelledError } from "../../../data/keyingProjectionVerification/index.js";
2
- import { reportAndRethrowKeyingVerificationError, rethrowKeyingVerificationError, } from "../../../data/keyingProjectionVerification/error.js";
2
+ import { rethrowKeyingVerificationError } from "../../../data/keyingProjectionVerification/error.js";
3
3
  import { dedupeReferencedPrincipalStates } from "../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js";
4
4
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
5
5
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
6
- import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
6
+ import { principalPolicyReferenceFromBundle } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
7
7
  import { errorMessage } from "../../../data/shared/errorMessage.js";
8
+ import { reportAndRethrowKeyingVerificationError, } from "../../../data/shared/securityIncidents.js";
8
9
  import { externalAdminPolicyPersistenceEntries, loadOrganizationExternalAdminPolicy, } from "../externalAdminPolicy.js";
9
10
  import { publishVerifiedPrincipalPolicy } from "../policyVerification.js";
10
11
  import { persistPrincipalPolicyCacheEntries, retryPrincipalPolicyCacheAdvance, } from "./principalPolicyCacheAdvance.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sCAAsC,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EACL,uCAAuC,EACvC,8BAA8B,GAC/B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,+BAA+B,EAAE,MAAM,iFAAiF,CAAC;AAClI,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AAKjE,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,MAAM,wBAA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AAG,EACH,cAAc,EACd,sBAAsB,EACtB,0BAA0B,EAC1B,YAAY,GACuB;IACnC,MAAM,uBAAuB,CAAC;QAC5B,SAAS,EAAE,CAAC,MAAM,EAAE,uBAAuB,EAAE,aAAa,EAAE,EAAE,CAC5D,0BAA0B,CAAC;YACzB,MAAM;YACN,OAAO;YACP,uBAAuB;YACvB,aAAa;YACb,GAAG;YACH,cAAc;YACd,0BAA0B;YAC1B,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isProjectionVerificationCancelledError } from \"../../../data/keyingProjectionVerification\";\nimport {\n reportAndRethrowKeyingVerificationError,\n rethrowKeyingVerificationError,\n} from \"../../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../externalAdminPolicy\";\nimport { publishVerifiedPrincipalPolicy } from \"../policyVerification\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\n/**\n * Pin and persist a policy the signed directory scopes to this organization,\n * with its external Admins evidence and the directory that scopes it.\n */\nasync function persistScopedPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly directory: VerifiedPolicyDirectory | null;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: (() => boolean) | undefined;\n readonly validation: {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly policy: VerifiedPrincipalPolicy;\n };\n}): Promise<VerifiedPrincipalPolicy[]> {\n const { directory, validation } = input;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await publishVerifiedPrincipalPolicy({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(reference, localCheckpoint);\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n return persistScopedPolicy({\n bundle,\n directory,\n execSql,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n validation,\n });\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n return persistScopedPolicy({\n bundle: input.bundle,\n directory,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n validation,\n });\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).ensurePrincipalPolicyTables();\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () => {\n reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input);\n return reloadedAuthority;\n }\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sCAAsC,EAAE,MAAM,4CAA4C,CAAC;AACpG,OAAO,EAAE,8BAA8B,EAAE,MAAM,kDAAkD,CAAC;AAClG,OAAO,EAAE,+BAA+B,EAAE,MAAM,iFAAiF,CAAC;AACl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AyB;QAClC,KAAK,EAAE,UAAU;QACjB,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAA8C;IAE9C,MAAM,+BAA+B,CAAC,KAAK,CAAC,CAAC;AAC/C,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,EAChD,OAAO,EACP,mBAAmB,EACnB,OAAO,EACP,GAAG,EACH,cAAc,EACd,sBAAsB,EACtB,0BAA0B,EAC1B,YAAY,GACuB;IACnC,MAAM,uBAAuB,CAAC;QAC5B,SAAS,EAAE,CAAC,MAAM,EAAE,uBAAuB,EAAE,aAAa,EAAE,EAAE,CAC5D,0BAA0B,CAAC;YACzB,MAAM;YACN,OAAO;YACP,uBAAuB;YACvB,aAAa;YACb,GAAG;YACH,cAAc;YACd,0BAA0B;YAC1B,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isProjectionVerificationCancelledError } from \"../../../data/keyingProjectionVerification\";\nimport { rethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport {\n reportAndRethrowKeyingVerificationError,\n type SecurityIncidentReporter,\n} from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../externalAdminPolicy\";\nimport { publishVerifiedPrincipalPolicy } from \"../policyVerification\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\n/**\n * Pin and persist a policy the signed directory scopes to this organization,\n * with its external Admins evidence and the directory that scopes it.\n */\nasync function persistScopedPolicy(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly directory: VerifiedPolicyDirectory | null;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent: (() => boolean) | undefined;\n readonly validation: {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly policy: VerifiedPrincipalPolicy;\n };\n}): Promise<VerifiedPrincipalPolicy[]> {\n const { directory, validation } = input;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await publishVerifiedPrincipalPolicy({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(reference, localCheckpoint);\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n stillCurrent,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n return persistScopedPolicy({\n bundle,\n directory,\n execSql,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n validation,\n });\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n return persistScopedPolicy({\n bundle: input.bundle,\n directory,\n execSql: input.execSql,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n validation,\n });\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).ensurePrincipalPolicyTables();\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () => {\n reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input);\n return reloadedAuthority;\n }\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
- import { externalAuthorityCouldAuthorize, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../../data/principals/principalPolicyAdminSigners.js";
2
+ import { externalAuthorityCouldAuthorize, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
3
3
  import { ProjectionDependencyUnavailableError } from "../../../data/shared/dependencyUnavailable.js";
4
4
  import { collectPrincipalPolicySignerPublicKeys, principalPolicyStates, } from "../policyVerification.js";
5
5
  function getBundleReferenceFailure(reference, bundle) {
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,sDAAsD,CAAC;AAC9D,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAGlG,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAO/B,SAAS,yBAAyB,CAChC,SAA2C,EAC3C,MAAqC;IAErC,MAAM,MAAM,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,sBAAsB,GAAG,MAAM,CAAC,IAAI,CACxC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,s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MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,EAC/B,yDAAyD,GAC1D,MAAM,8DAA8D,CAAC;AACtE,OAAO,EAAE,oCAAoC,EAAE,MAAM,4CAA4C,CAAC;AAGlG,OAAO,EACL,sCAAsC,EAEtC,qBAAqB,GACtB,MAAM,uBAAuB,CAAC;AAO/B,SAAS,yBAAyB,CAChC,SAA2C,EAC3C,MAAqC;IAErC,MAAM,MAAM,GAAG,qBAAqB,CAAC,MAAM,CAAC,CAAC;IAC7C,MAAM,sBAAsB,GAAG,MAAM,CAAC,IAAI,CACxC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,SAAS,CAAC,aAAa;QAC/C,KAAK,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,sBAAsB,EAAE,CAAC;QAC5B,OAAO;YACL,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,sDAAsD;SAChE,CAAC;IACJ,CAAC;IACD,IACE,CAAC,MAAM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AC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
@@ -2,8 +2,8 @@ import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { principalPolicyHeadMeetsCheckpoint } from "../../../data/keyingProjectionVerification/index.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
4
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
5
- import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
6
- import { verifyOrganizationAdminPolicy } from "../../../data/principals/principalPolicyAdminSigners.js";
5
+ import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
6
+ import { verifyOrganizationAdminPolicy } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
7
7
  import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../policyVerification.js";
8
8
  export function directoryBindsGroupReference(directory, policy, reference) {
9
9
  const head = directory?.descriptor.groupHeads.find((head) => head.principalId === reference.principalId);
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MA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ACH,IAAI,CAAC,QAAQ,CAAC,EAAE;YAAE,MAAM,QAAQ,CAAC,KAAK,CAAC;QACvC,MAAM,8BAA8B,CAAC;YACnC,MAAM;YACN,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;YAC5D,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC;QACH,IAAI,UAA2C,CAAC;QAChD,IAAI,CAAC;YACH,UAAU,GAAG,oCAAoC,CAC/C,MAAM,CAAC,cAAc,CAAC,UAAU,CACjC,CAAC;QACJ,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;QACJ,CAAC;QACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;YACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;QACJ,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC,CAAC;IACF,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../policyVerification\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = PrincipalPolicyBundleResponse | null;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,8DAA8D,CAAC;AAI7G,OAAO,EACL,sCAAsC,EACtC,8BAA8B,GAC/B,MAAM,uBAAuB,CAAC;AAY/B,MAAM,UAAU,4BAA4B,CAC1C,SAAyC,EACzC,MAA+B,EAC/B,SAAkC;IAElC,MAAM,IAAI,GAAG,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,IAAI,CAChD,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CACrD,CAAC;IACF,sEAAsE;IACtE,2EAA2E;IAC3E,OAAO,CACL,CAAC,CAAC,IAAI;QACN,IAAI,CAAC,OAAO,IAAI,SAAS,CAAC,OAAO;QACjC,IAAI,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;QAC/B,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CACxE,CAAC,KAAK,EAAE,EAAE,CAAC,6BAA6B,CAAC,KAAK,EAAE,IAAI,CAAC,CAC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yCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../policyVerification\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = PrincipalPolicyBundleResponse | null;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { computeUserIdentityBundleFingerprint, } from "../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
3
- import { publishVerifiedPolicyBundle, withUnauthenticatedPolicyIdentities, } from "../../data/principals/principalIdentityCommitments.js";
3
+ import { publishVerifiedPolicyBundle, withUnauthenticatedPolicyIdentities, } from "../../data/principalContracts/principalIdentityCommitments.js";
4
4
  import { requireTrustedUserIdentityResolver, } from "../../data/trustedUserIdentity/index.js";
5
5
  export function principalPolicyStates(bundle) {
6
6
  return [
@@ -1 +1 @@
1
- {"version":3,"file":"policyVerification.js","sourceRoot":"","sources":["policyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,GAGrC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,GACpC,MAAM,oDAAoD,CAAC;AAC5D,OAAO,EACL,kCAAkC,GAGnC,MAAM,gCAAgC,CAAC;AAMxC,MAAM,UAAU,qBAAqB,CACnC,MAGC;IAED,OAAO;QACL,GAAG,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC;QACpD,MAAM,CAAC,YAAY;KACpB,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,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AK,CAAC,aAAa;QACjB,CAAC,YAAY;YACX,CAAC,CAAC,GAAG,EAAE,CAAC,mCAAmC,CAAC,YAAY,CAAC;YACzD,CAAC,CAAC,SAAS,CAAC,CACjB,CAAC;AACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,sBAAsB,CACpC,OAA6E,EAC7E,OAGC,EACD,YAA2B;IAE3B,OAAO,8BAA8B,CAAC;QACpC,MAAM,EAAE,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE;QAC1C,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;QAC9D,aAAa,EAAE,GAAG,EAAE,CAAC,mCAAmC,CAAC,YAAY,CAAC;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computeUserIdentityBundleFingerprint,\n type PrincipalPolicySignerPublicKey,\n type PrincipalProjectionMember,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n publishVerifiedPolicyBundle,\n withUnauthenticatedPolicyIdentities,\n} from \"../../data/principals/principalIdentityCommitments\";\nimport {\n requireTrustedUserIdentityResolver,\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\n\nexport type PrincipalPolicySignerPublicKeyLoadErrorCode =\n | \"fingerprint-mismatch\"\n | \"not-found\";\n\nexport function principalPolicyStates(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\"\n >,\n): PrincipalPolicyBundleResponse[\"currentState\"][] {\n return [\n ...bundle.previousStates.map((entry) => entry.state),\n bundle.currentState,\n ];\n}\n\nfunction signerCacheKey(input: {\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n}): string {\n return `${input.signerUserId}:${input.signingFingerprint}`;\n}\n\n/** A signer refusal ends collection before any commitment is compared. */\nclass SignerLoadRefusal {\n constructor(readonly code: PrincipalPolicySignerPublicKeyLoadErrorCode) {}\n}\n\ninterface TrustedSigner {\n readonly identity: NonNullable<\n Awaited<ReturnType<StagedUserIdentityResolver>>\n >;\n readonly publicKey: PrincipalPolicySignerPublicKey;\n bundleFingerprint?: Promise<string>;\n}\n\nasync function loadTrustedSigner(input: {\n readonly resolve: StagedUserIdentityResolver;\n readonly state: PrincipalPolicyBundleResponse[\"currentState\"];\n}): Promise<TrustedSigner> {\n const signerKey = await input.resolve(input.state.signerUserId);\n\n if (!signerKey) {\n throw new SignerLoadRefusal(\"not-found\");\n }\n\n if (\n signerKey.signingKeyFingerprint !== input.state.signerUserKeyFingerprint\n ) {\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n\n return {\n identity: signerKey,\n publicKey: {\n userId: input.state.signerUserId,\n signingKeyFingerprint: input.state.signerUserKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n },\n };\n}\n\ntype SignedProjection = {\n readonly version: number;\n readonly stateHash: string;\n readonly projection: readonly PrincipalProjectionMember[];\n};\n\n/**\n * The signer's identity as its predecessor's signed projection committed it,\n * when the state links to that predecessor: an unlinked entry is left for the\n * chain verifier to refuse as disconnected.\n */\nfunction committedSignerBundle(\n state: PrincipalPolicyBundleResponse[\"currentState\"],\n predecessors: ReadonlyMap<number, SignedProjection>,\n): string | undefined {\n const predecessor = predecessors.get(state.version - 1);\n if (!predecessor || predecessor.stateHash !== state.prevStateHash)\n return undefined;\n return predecessor.projection.find(\n (member) => member.userId === state.signerUserId,\n )?.identityBundleFingerprint;\n}\n\nexport async function collectPrincipalPolicySignerPublicKeys(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /**\n * A paged history's last accepted state, which authorizes the page's first\n * signer by user ID: that signer must be the identity it committed.\n */\n readonly predecessor?: SignedProjection | null;\n}): Promise<\n | { readonly signerPublicKeys: PrincipalPolicySignerPublicKey[] }\n | { readonly error: PrincipalPolicySignerPublicKeyLoadErrorCode }\n> {\n const states = principalPolicyStates(input.bundle);\n const predecessors = new Map<number, SignedProjection>(\n [\n ...(input.predecessor ? [input.predecessor] : []),\n ...input.bundle.previousStates.map((entry) => ({\n version: entry.state.version,\n stateHash: entry.state.stateHash,\n projection: entry.projection,\n })),\n ].map((entry) => [entry.version, entry]),\n );\n try {\n // Signatures are checked after collection: first-sight signers and\n // members are compared, but only a verified selection pins them.\n return await withUnauthenticatedPolicyIdentities(\n {\n signerUserIds: states.map((state) => state.signerUserId),\n projections: [\n ...input.bundle.previousStates.map((entry) => entry.projection),\n input.bundle.currentProjection,\n ],\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n },\n async (resolve) => {\n const signers = new Map<string, TrustedSigner>();\n for (const state of states) {\n const cacheKey = signerCacheKey({\n signerUserId: state.signerUserId,\n signingFingerprint: state.signerUserKeyFingerprint,\n });\n let signer = signers.get(cacheKey);\n if (!signer) {\n signer = await loadTrustedSigner({ resolve, state });\n signers.set(cacheKey, signer);\n }\n const committed = committedSignerBundle(state, predecessors);\n if (committed === undefined) continue;\n signer.bundleFingerprint ??= computeUserIdentityBundleFingerprint(\n signer.identity,\n );\n if ((await signer.bundleFingerprint) !== committed)\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n return {\n signerPublicKeys: Array.from(\n signers.values(),\n (signer) => signer.publicKey,\n ),\n };\n },\n );\n } catch (error) {\n if (error instanceof SignerLoadRefusal) return { error: error.code };\n throw error;\n }\n}\n\n/**\n * Pin the signers and members of a bundle the caller has just verified, so\n * the first sights signer collection staged become durable only now. Call it\n * after every successful verification of a collected bundle.\n */\nexport function publishVerifiedPrincipalPolicy(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly assertCurrent?: (() => void) | undefined;\n /** The operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n const { stillCurrent } = input;\n return publishVerifiedPolicyBundle(\n input.bundle,\n requireTrustedUserIdentityResolver(input.resolveTrustedUserIdentity),\n input.assertCurrent ??\n (stillCurrent\n ? () => assertProjectionVerificationCurrent(stillCurrent)\n : undefined),\n );\n}\n\n/** Pin one recovery's just-verified current state, within its lifetime. */\nexport function publishVerifiedCurrent(\n options: { readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver },\n current: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n stillCurrent: () => boolean,\n): Promise<void> {\n return publishVerifiedPrincipalPolicy({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n assertCurrent: () => assertProjectionVerificationCurrent(stillCurrent),\n });\n}\n"]}
1
+ {"version":3,"file":"policyVerification.js","sourceRoot":"","sources":["policyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,GAGrC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,2BAA2B,EAC3B,mCAAmC,GACpC,MAAM,4DAA4D,CAAC;AACpE,OAAO,EACL,kCAAkC,GAGnC,MAAM,gCAAgC,CAAC;AAMxC,MAAM,UAAU,qBAAqB,CACnC,MAGC;IAED,OAAO;QACL,GAAG,MAAM,CAAC,cAAc,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC;QACpD,MAAM,CAAC,YAAY;KACpB,CAAC;AACJ,CAAC;AAED,SAAS,cAAc,CAAC,KAGvB;IACC,OAAO,GAAG,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC;AAC7D,CAAC;AAED,0EAA0E;AAC1E,MAAM,iBAAiB;IACA;IAArB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ACJ,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,sBAAsB,CACpC,OAA6E,EAC7E,OAGC,EACD,YAA2B;IAE3B,OAAO,8BAA8B,CAAC;QACpC,MAAM,EAAE,EAAE,GAAG,OAAO,EAAE,cAAc,EAAE,EAAE,EAAE;QAC1C,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;QAC9D,aAAa,EAAE,GAAG,EAAE,CAAC,mCAAmC,CAAC,YAAY,CAAC;KACvE,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n computeUserIdentityBundleFingerprint,\n type PrincipalPolicySignerPublicKey,\n type PrincipalProjectionMember,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n publishVerifiedPolicyBundle,\n withUnauthenticatedPolicyIdentities,\n} from \"../../data/principalContracts/principalIdentityCommitments\";\nimport {\n requireTrustedUserIdentityResolver,\n type StagedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\n\nexport type PrincipalPolicySignerPublicKeyLoadErrorCode =\n | \"fingerprint-mismatch\"\n | \"not-found\";\n\nexport function principalPolicyStates(\n bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\"\n >,\n): PrincipalPolicyBundleResponse[\"currentState\"][] {\n return [\n ...bundle.previousStates.map((entry) => entry.state),\n bundle.currentState,\n ];\n}\n\nfunction signerCacheKey(input: {\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n}): string {\n return `${input.signerUserId}:${input.signingFingerprint}`;\n}\n\n/** A signer refusal ends collection before any commitment is compared. */\nclass SignerLoadRefusal {\n constructor(readonly code: PrincipalPolicySignerPublicKeyLoadErrorCode) {}\n}\n\ninterface TrustedSigner {\n readonly identity: NonNullable<\n Awaited<ReturnType<StagedUserIdentityResolver>>\n >;\n readonly publicKey: PrincipalPolicySignerPublicKey;\n bundleFingerprint?: Promise<string>;\n}\n\nasync function loadTrustedSigner(input: {\n readonly resolve: StagedUserIdentityResolver;\n readonly state: PrincipalPolicyBundleResponse[\"currentState\"];\n}): Promise<TrustedSigner> {\n const signerKey = await input.resolve(input.state.signerUserId);\n\n if (!signerKey) {\n throw new SignerLoadRefusal(\"not-found\");\n }\n\n if (\n signerKey.signingKeyFingerprint !== input.state.signerUserKeyFingerprint\n ) {\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n\n return {\n identity: signerKey,\n publicKey: {\n userId: input.state.signerUserId,\n signingKeyFingerprint: input.state.signerUserKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n },\n };\n}\n\ntype SignedProjection = {\n readonly version: number;\n readonly stateHash: string;\n readonly projection: readonly PrincipalProjectionMember[];\n};\n\n/**\n * The signer's identity as its predecessor's signed projection committed it,\n * when the state links to that predecessor: an unlinked entry is left for the\n * chain verifier to refuse as disconnected.\n */\nfunction committedSignerBundle(\n state: PrincipalPolicyBundleResponse[\"currentState\"],\n predecessors: ReadonlyMap<number, SignedProjection>,\n): string | undefined {\n const predecessor = predecessors.get(state.version - 1);\n if (!predecessor || predecessor.stateHash !== state.prevStateHash)\n return undefined;\n return predecessor.projection.find(\n (member) => member.userId === state.signerUserId,\n )?.identityBundleFingerprint;\n}\n\nexport async function collectPrincipalPolicySignerPublicKeys(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /**\n * A paged history's last accepted state, which authorizes the page's first\n * signer by user ID: that signer must be the identity it committed.\n */\n readonly predecessor?: SignedProjection | null;\n}): Promise<\n | { readonly signerPublicKeys: PrincipalPolicySignerPublicKey[] }\n | { readonly error: PrincipalPolicySignerPublicKeyLoadErrorCode }\n> {\n const states = principalPolicyStates(input.bundle);\n const predecessors = new Map<number, SignedProjection>(\n [\n ...(input.predecessor ? [input.predecessor] : []),\n ...input.bundle.previousStates.map((entry) => ({\n version: entry.state.version,\n stateHash: entry.state.stateHash,\n projection: entry.projection,\n })),\n ].map((entry) => [entry.version, entry]),\n );\n try {\n // Signatures are checked after collection: first-sight signers and\n // members are compared, but only a verified selection pins them.\n return await withUnauthenticatedPolicyIdentities(\n {\n signerUserIds: states.map((state) => state.signerUserId),\n projections: [\n ...input.bundle.previousStates.map((entry) => entry.projection),\n input.bundle.currentProjection,\n ],\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n },\n async (resolve) => {\n const signers = new Map<string, TrustedSigner>();\n for (const state of states) {\n const cacheKey = signerCacheKey({\n signerUserId: state.signerUserId,\n signingFingerprint: state.signerUserKeyFingerprint,\n });\n let signer = signers.get(cacheKey);\n if (!signer) {\n signer = await loadTrustedSigner({ resolve, state });\n signers.set(cacheKey, signer);\n }\n const committed = committedSignerBundle(state, predecessors);\n if (committed === undefined) continue;\n signer.bundleFingerprint ??= computeUserIdentityBundleFingerprint(\n signer.identity,\n );\n if ((await signer.bundleFingerprint) !== committed)\n throw new SignerLoadRefusal(\"fingerprint-mismatch\");\n }\n return {\n signerPublicKeys: Array.from(\n signers.values(),\n (signer) => signer.publicKey,\n ),\n };\n },\n );\n } catch (error) {\n if (error instanceof SignerLoadRefusal) return { error: error.code };\n throw error;\n }\n}\n\n/**\n * Pin the signers and members of a bundle the caller has just verified, so\n * the first sights signer collection staged become durable only now. Call it\n * after every successful verification of a collected bundle.\n */\nexport function publishVerifiedPrincipalPolicy(input: {\n readonly bundle: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"previousStates\" | \"currentProjection\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly assertCurrent?: (() => void) | undefined;\n /** The operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n const { stillCurrent } = input;\n return publishVerifiedPolicyBundle(\n input.bundle,\n requireTrustedUserIdentityResolver(input.resolveTrustedUserIdentity),\n input.assertCurrent ??\n (stillCurrent\n ? () => assertProjectionVerificationCurrent(stillCurrent)\n : undefined),\n );\n}\n\n/** Pin one recovery's just-verified current state, within its lifetime. */\nexport function publishVerifiedCurrent(\n options: { readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver },\n current: Pick<\n PrincipalPolicyBundleResponse,\n \"currentState\" | \"currentProjection\"\n >,\n stillCurrent: () => boolean,\n): Promise<void> {\n return publishVerifiedPrincipalPolicy({\n bundle: { ...current, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n assertCurrent: () => assertProjectionVerificationCurrent(stillCurrent),\n });\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { rethrowKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
2
2
  import { assertProjectionVerificationCurrent, isProjectionVerificationCancelledError, } from "../../data/keyingProjectionVerification/types.js";
3
+ import { principalPolicyReferenceFromBundle } from "../../data/principalContracts/principalPolicyAdminSigners.js";
3
4
  import { directoryHistoryProtection } from "../../data/principals/principalHistoryScopeProtection.js";
4
- import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
5
5
  import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
6
6
  import { errorMessage } from "../../data/shared/errorMessage.js";
7
7
  import { apiPrincipalPolicyPageReader, } from "./principalPolicyHistoryReader.js";
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyService.js","sourceRoot":"","sources":["principalPolicyService.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GAEvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,oCAAo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,IAAI,CAAC,oBAAoB,IAAI,CAAC,aAAa;QAAE,OAAO,SAAS,CAAC;IACxE,OAAO,KAAK,EACV,aAA4B,EAC5B,IAAmE,EACvD,EAAE,CACd,KAAK,CAAC,KAAK,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,EAAE,EAAE;QACzD,IAAI,MAAM,GAAG,IAAI,CAAC;QAClB,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,MAAM,IAAI,YAAY,EAAE,IAAI,aAAa,EAAE,CAAC;QACvE,IAAI,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACxB,UAAU;gBACV,YAAY;gBACZ,oBAAoB;gBACpB,aAAa;gBACb,iBAAiB,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;oBAC/B,aAAa;oBACb,YAAY,EAAE,kCAAkC,CAAC,OAAO,CAAC;oBACzD,UAAU,EAAE,0BAA0B,CAAC,UAAU,CAAC;oBAClD,0BAA0B,EAAE,QAAQ,CAAC,0BAA0B;iBAChE,CAAC;aACH,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n isProjectionVerificationCancelledError,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalCurrentInput } from \"./acknowledgements/acknowledgedPrincipalCurrents\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyPageReader,\n} from \"./principalPolicyHistoryReader\";\nimport {\n createPrincipalPolicyCurrentResolver,\n type PrincipalPolicyCollaborators,\n type PrincipalPolicyCurrentResolver,\n} from \"./runtimePolicyRecovery\";\nimport { createProjectionPolicyHistoryResolver } from \"./runtimeProjectionPolicyRecovery\";\n\ntype PolicyResolver = NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveReference\"]\n>;\n\n/**\n * The token of one reconciliation pass or user workflow. Every warmer created\n * with it shares one authenticated directory view, discovered once; the view\n * dies with the token, an organization hint, a durable pin past it, or the end\n * of its producing lease. Mint one at the pass or workflow root.\n */\nexport type PrincipalPolicyOperation = object;\n\nexport function createPrincipalPolicyOperation(): PrincipalPolicyOperation {\n return {};\n}\n\nexport interface PrincipalPolicyWarmerOptions {\n readonly preferLocalCurrent?: boolean;\n readonly operation?: PrincipalPolicyOperation | undefined;\n}\n\n/** A runtime snapshot carrying the policy service its producer bound, and its executor. */\nexport interface PrincipalPolicyRuntime {\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nlet collaboratorsOf: (\n service: PrincipalPolicyService,\n) => PrincipalPolicyCollaborators;\n\n/**\n * Principal Policy: recovers, verifies, and prefetches the principal policy\n * evidence that projections cite. One instance binds one runtime snapshot's\n * API client, executor, online state, reporter, logger, trusted-identity\n * resolver, and the history-protection lease that snapshot bound; every view\n * derived from the snapshot shares it. The collaborators sit in a private\n * field, so a public runtime view carrying the service exposes no custody.\n */\nexport class PrincipalPolicyService {\n readonly #policies: PrincipalPolicyCollaborators;\n\n static {\n collaboratorsOf = (service) => service.#policies;\n }\n\n constructor(collaborators: PrincipalPolicyCollaborators) {\n this.#policies = collaborators;\n }\n\n /** Undefined without history custody or a paged history reader. */\n createCurrentPolicyResolver(): PrincipalPolicyCurrentResolver | undefined {\n return createPrincipalPolicyCurrentResolver(this.#policies);\n }\n\n /** Undefined without history custody or a projection history reader. */\n createProjectionHistoryResolver(): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n return createProjectionPolicyHistoryResolver(this.#policies);\n }\n\n /**\n * One warmer serves one workflow operation: either the `operation` its root\n * minted, or a fresh one of its own. Its projection collections share one\n * authenticated directory view per operation. Prefetch is best-effort; exact\n * resolution still rejects unavailable evidence.\n */\n createWarmer(\n options: PrincipalPolicyWarmerOptions = {},\n ): ReferencedPrincipalPolicyWarmer {\n const resolve = this.createCurrentPolicyResolver();\n const operation = options.operation ?? createPrincipalPolicyOperation();\n const resolveReference: PolicyResolver = async (input) => {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Principal policies require private paged recovery\",\n );\n return resolve({\n ...input,\n recoveryBatch: input.recoveryBatch ?? operation,\n preferLocalCurrent: options.preferLocalCurrent,\n });\n };\n const policies = this.#policies;\n return Object.assign(\n (input: Parameters<ReferencedPrincipalPolicyWarmer>[0]) =>\n prefetchReferences(policies, resolveReference, input),\n {\n resolveReference,\n resolveProjectionHistory: this.createProjectionHistoryResolver(),\n },\n );\n }\n}\n\nasync function prefetchReferences(\n policies: PrincipalPolicyCollaborators,\n resolve: PolicyResolver,\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n): Promise<void> {\n for (const reference of input.references) {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await resolve({ ...input, reference });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return;\n // Recovery already reports signature/authority failures. Keep them fatal.\n rethrowKeyingVerificationError(error);\n policies.util.log?.(\n `Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`,\n );\n }\n }\n}\n\nexport interface CurrentPrincipalMutationLeaseContext {\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly stillCurrent: () => boolean;\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly directoryRecovery: (\n current: PrincipalPolicyPageCurrent,\n ) => AcknowledgedPrincipalCurrentInput[\"recovery\"];\n}\n\nexport type CurrentPrincipalMutationLease = <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n) => Promise<T>;\n\n/**\n * One lifetime fence and private custody boundary for every current-policy\n * mutation. It hands the snapshot's private history protection to `work`, so\n * it stays off the class and out of the package root: a public runtime view\n * carrying the service cannot reach it.\n */\nexport function createCurrentPrincipalMutationLease(\n service: PrincipalPolicyService,\n): CurrentPrincipalMutationLease | undefined {\n const policies = collaboratorsOf(service);\n const lease = policies.withPrincipalHistoryProtection;\n const resolveCurrentPolicy = createPrincipalPolicyCurrentResolver(policies);\n const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);\n if (!lease || !resolveCurrentPolicy || !historyReader) return undefined;\n return async <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n ): Promise<T> =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n let active = true;\n const stillCurrent = () => active && leaseCurrent() && callerCurrent();\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery: (current) => ({\n historyReader,\n expectedHead: principalPolicyReferenceFromBundle(current),\n protection: directoryHistoryProtection(protection),\n resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,\n }),\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n active = false;\n }\n });\n}\n"]}
1
+ {"version":3,"file":"principalPolicyService.js","sourceRoot":"","sources":["principalPolicyService.ts"],"names":[],"mappings":"AAEA,OAAO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AAG,eAAe,CAAC,OAAO,CAAC,CAAC;IAC1C,MAAM,KAAK,GAAG,QAAQ,CAAC,8BAA8B,CAAC;IACtD,MAAM,oBAAoB,GAAG,oCAAoC,CAAC,QAAQ,CAAC,CAAC;IAC5E,MAAM,aAAa,GAAG,4BAA4B,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IACvE,IAAI,CAAC,KAAK,IAAI,CAAC,oBAAoB,IAAI,CAAC,aAAa;QAAE,OAAO,SAAS,CAAC;IACxE,OAAO,KAAK,EACV,aAA4B,EAC5B,IAAmE,EACvD,EAAE,CACd,KAAK,CAAC,KAAK,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,EAAE,EAAE;QACzD,IAAI,MAAM,GAAG,IAAI,CAAC;QAClB,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,MAAM,IAAI,YAAY,EAAE,IAAI,aAAa,EAAE,CAAC;QACvE,IAAI,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACxB,UAAU;gBACV,YAAY;gBACZ,oBAAoB;gBACpB,aAAa;gBACb,iBAAiB,EAAE,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;oBAC/B,aAAa;oBACb,YAAY,EAAE,kCAAkC,CAAC,OAAO,CAAC;oBACzD,UAAU,EAAE,0BAA0B,CAAC,UAAU,CAAC;oBAClD,0BAA0B,EAAE,QAAQ,CAAC,0BAA0B;iBAChE,CAAC;aACH,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,OAAO,MAAM,CAAC;QAChB,CAAC;gBAAS,CAAC;YACT,MAAM,GAAG,KAAK,CAAC;QACjB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n isProjectionVerificationCancelledError,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principalContracts/principalPolicyAdminSigners\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalCurrentInput } from \"./acknowledgements/acknowledgedPrincipalCurrents\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyPageReader,\n} from \"./principalPolicyHistoryReader\";\nimport {\n createPrincipalPolicyCurrentResolver,\n type PrincipalPolicyCollaborators,\n type PrincipalPolicyCurrentResolver,\n} from \"./runtimePolicyRecovery\";\nimport { createProjectionPolicyHistoryResolver } from \"./runtimeProjectionPolicyRecovery\";\n\ntype PolicyResolver = NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveReference\"]\n>;\n\n/**\n * The token of one reconciliation pass or user workflow. Every warmer created\n * with it shares one authenticated directory view, discovered once; the view\n * dies with the token, an organization hint, a durable pin past it, or the end\n * of its producing lease. Mint one at the pass or workflow root.\n */\nexport type PrincipalPolicyOperation = object;\n\nexport function createPrincipalPolicyOperation(): PrincipalPolicyOperation {\n return {};\n}\n\nexport interface PrincipalPolicyWarmerOptions {\n readonly preferLocalCurrent?: boolean;\n readonly operation?: PrincipalPolicyOperation | undefined;\n}\n\n/** A runtime snapshot carrying the policy service its producer bound, and its executor. */\nexport interface PrincipalPolicyRuntime {\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nlet collaboratorsOf: (\n service: PrincipalPolicyService,\n) => PrincipalPolicyCollaborators;\n\n/**\n * Principal Policy: recovers, verifies, and prefetches the principal policy\n * evidence that projections cite. One instance binds one runtime snapshot's\n * API client, executor, online state, reporter, logger, trusted-identity\n * resolver, and the history-protection lease that snapshot bound; every view\n * derived from the snapshot shares it. The collaborators sit in a private\n * field, so a public runtime view carrying the service exposes no custody.\n */\nexport class PrincipalPolicyService {\n readonly #policies: PrincipalPolicyCollaborators;\n\n static {\n collaboratorsOf = (service) => service.#policies;\n }\n\n constructor(collaborators: PrincipalPolicyCollaborators) {\n this.#policies = collaborators;\n }\n\n /** Undefined without history custody or a paged history reader. */\n createCurrentPolicyResolver(): PrincipalPolicyCurrentResolver | undefined {\n return createPrincipalPolicyCurrentResolver(this.#policies);\n }\n\n /** Undefined without history custody or a projection history reader. */\n createProjectionHistoryResolver(): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n return createProjectionPolicyHistoryResolver(this.#policies);\n }\n\n /**\n * One warmer serves one workflow operation: either the `operation` its root\n * minted, or a fresh one of its own. Its projection collections share one\n * authenticated directory view per operation. Prefetch is best-effort; exact\n * resolution still rejects unavailable evidence.\n */\n createWarmer(\n options: PrincipalPolicyWarmerOptions = {},\n ): ReferencedPrincipalPolicyWarmer {\n const resolve = this.createCurrentPolicyResolver();\n const operation = options.operation ?? createPrincipalPolicyOperation();\n const resolveReference: PolicyResolver = async (input) => {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Principal policies require private paged recovery\",\n );\n return resolve({\n ...input,\n recoveryBatch: input.recoveryBatch ?? operation,\n preferLocalCurrent: options.preferLocalCurrent,\n });\n };\n const policies = this.#policies;\n return Object.assign(\n (input: Parameters<ReferencedPrincipalPolicyWarmer>[0]) =>\n prefetchReferences(policies, resolveReference, input),\n {\n resolveReference,\n resolveProjectionHistory: this.createProjectionHistoryResolver(),\n },\n );\n }\n}\n\nasync function prefetchReferences(\n policies: PrincipalPolicyCollaborators,\n resolve: PolicyResolver,\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n): Promise<void> {\n for (const reference of input.references) {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await resolve({ ...input, reference });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return;\n // Recovery already reports signature/authority failures. Keep them fatal.\n rethrowKeyingVerificationError(error);\n policies.util.log?.(\n `Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`,\n );\n }\n }\n}\n\nexport interface CurrentPrincipalMutationLeaseContext {\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly stillCurrent: () => boolean;\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly directoryRecovery: (\n current: PrincipalPolicyPageCurrent,\n ) => AcknowledgedPrincipalCurrentInput[\"recovery\"];\n}\n\nexport type CurrentPrincipalMutationLease = <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n) => Promise<T>;\n\n/**\n * One lifetime fence and private custody boundary for every current-policy\n * mutation. It hands the snapshot's private history protection to `work`, so\n * it stays off the class and out of the package root: a public runtime view\n * carrying the service cannot reach it.\n */\nexport function createCurrentPrincipalMutationLease(\n service: PrincipalPolicyService,\n): CurrentPrincipalMutationLease | undefined {\n const policies = collaboratorsOf(service);\n const lease = policies.withPrincipalHistoryProtection;\n const resolveCurrentPolicy = createPrincipalPolicyCurrentResolver(policies);\n const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);\n if (!lease || !resolveCurrentPolicy || !historyReader) return undefined;\n return async <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n ): Promise<T> =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n let active = true;\n const stillCurrent = () => active && leaseCurrent() && callerCurrent();\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery: (current) => ({\n historyReader,\n expectedHead: principalPolicyReferenceFromBundle(current),\n protection: directoryHistoryProtection(protection),\n resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,\n }),\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n active = false;\n }\n });\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, serializeKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
2
2
  import { isReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
3
- import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
3
+ import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
4
4
  /** The greatest cited Admins head commits to the lineage of every earlier citation. */
5
5
  export function publicHistoryAuthorityReference(previous, references) {
6
6
  return references.reduce((head, reference) => !head || reference.version > head.version ? reference : head, previous);
@@ -1 +1 @@
1
- {"version":3,"file":"publicPrincipalHistoryAuthority.js","sourceRoot":"","sources":["publicPrincipalHistoryAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AAEpF,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AAGzG,uFAAuF;AACvF,MAAM,UAAU,+BAA+B,CAC7C,QAAwC,EACxC,UAA8C;IAE9C,OAAO,UAAU,CAAC,MAAM,CACtB,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,CAClB,CAAC,IAAI,IAAI,SAAS,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,EAC9D,QAAQ,CACT,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,SAAyC;IAEzC,OAAO,4BAA4B,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,CAAC,CAAC,CAAC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mBAAmB,EACnB,mEAAmE,CACpE,CAAC;IACJ,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAClD,KAAoC,EACpC,SAAyC,EACzC,iBAAgD,IAAI;IAEpD,IAAI,CAAC;QACH,IAAI,SAAS;YAAE,MAAM,0BAA0B,CAAC,KAAK,EAAE,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC,CAAC;IAC5E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,uBAAuB;YAC1C,MAAM,IAAI,sCAAsC,CAAC,KAAK,EAAE,cAAc,CAAC,CAAC;QAC1E,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC;AAED,+EAA+E;AAC/E,MAAM,OAAO,sCAAuC,SAAQ,KAAK;IAEpD;IACA;IAFX,YACW,iBAA0C,EAC1C,cAA6C;QAEtD,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAHxB,sBAAiB,GAAjB,iBAAiB,CAAyB;QAC1C,mBAAc,GAAd,cAAc,CAA+B;QAGtD,IAAI,CAAC,IAAI,GAAG,wCAAwC,CAAC;IACvD,CAAC;CACF","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { PublicPrincipalHistoryOptions } from \"./publicPrincipalHistoryTypes\";\n\n/** The greatest cited Admins head commits to the lineage of every earlier citation. */\nexport function publicHistoryAuthorityReference(\n previous: ReferencedPrincipalHead | null,\n references: readonly ReferencedPrincipalHead[],\n) {\n return references.reduce<ReferencedPrincipalHead | null>(\n (head, reference) =>\n !head || reference.version > head.version ? reference : head,\n previous,\n );\n}\n\nexport function publicHistoryAuthorityJson(\n reference: ReferencedPrincipalHead | null,\n) {\n return serializeKeyingCanonicalJson(reference ? { ...reference } : null);\n}\n\nexport function parsePublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n json: string,\n): ReferencedPrincipalHead | null | undefined {\n try {\n const value: unknown = JSON.parse(json);\n if (value === null) return null;\n if (\n isReferencedPrincipalStateResponse(value) &&\n value.principalType === \"group\" &&\n value.principalId === input.authorityGroupId\n )\n return value;\n } catch {\n /* Invalid disposable metadata cannot restore verified progress. */\n }\n return undefined;\n}\n\nexport async function loadPublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix = false,\n) {\n if (!references.length) return undefined;\n const authority = await input.loadExternalAuthority?.(\n references,\n cachedPrefix,\n );\n if (\n authority &&\n (authority.currentHead.principalId !== input.authorityGroupId ||\n authority.states.some(\n ({ head }) => head.principalId !== input.authorityGroupId,\n ))\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Authority callback differs from the directory binding\",\n );\n if (\n references.some(\n (reference) =>\n !authority?.states.some(({ head }) =>\n principalHeadMatchesReference(head, reference),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Public history authority differs from its verified Admins lineage\",\n );\n return authority;\n}\n\nexport async function validatePublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n reference: ReferencedPrincipalHead | null,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<void> {\n try {\n if (reference) await loadPublicHistoryAuthority(input, [reference], true);\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PublicHistoryAuthorityUnavailableError(error, rejectedPrefix);\n throw error;\n }\n}\n\n/** Only cache restoration can request a replay after an authority mismatch. */\nexport class PublicHistoryAuthorityUnavailableError extends Error {\n constructor(\n readonly verificationError: KeyingVerificationError,\n readonly rejectedPrefix: PrincipalHistoryPrefix | null,\n ) {\n super(verificationError.message);\n this.name = \"PublicHistoryAuthorityUnavailableError\";\n }\n}\n"]}
1
+ {"version":3,"file":"publicPrincipalHistoryAuthority.js","sourceRoot":"","sources":["publicPrincipalHistoryAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AAEpF,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAGjH,uFAAuF;AACvF,MAAM,UAAU,+BAA+B,CAC7C,QAAwC,EACxC,UAA8C;IAE9C,OAAO,UAAU,CAAC,MAAM,CACtB,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,CAClB,CAAC,IAAI,IAAI,SAAS,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,EAC9D,QAAQ,CACT,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,0BAA0B,CACxC,SAAyC;IAEzC,OAAO,4BAA4B,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,GAAG,SAAS,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;AAC3E,CAAC;AAED,MAAM,UAAU,2BAA2B,CACzC,KAAoC,EACpC,IAAY;IAEZ,IAAI,CAAC;QACH,MAAM,KAAK,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACxC,IAAI,KAAK,KAAK,IAAI;YAAE,OAAO,IAAI,CAAC;QAChC,IACE,kCAAkC,CAAC,KAAK,CAAC;YACzC,KAAK,CAAC,aAAa,KAAK,OAAO;YAC/B,KAAK,CAAC,WAAW,KAAK,KAAK,CAAC,gBAAgB;YAE5C,OAAO,KAAK,CAAC;IACjB,CAAC;IAAC,MAAM,CAAC;QACP,mEAAmE;IACrE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,0BAA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C,SAAQ,KAAK;IAEpD;IACA;IAFX,YACW,iBAA0C,EAC1C,cAA6C;QAEtD,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QAHxB,sBAAiB,GAAjB,iBAAiB,CAAyB;QAC1C,mBAAc,GAAd,cAAc,CAA+B;QAGtD,IAAI,CAAC,IAAI,GAAG,wCAAwC,CAAC;IACvD,CAAC;CACF","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { PublicPrincipalHistoryOptions } from \"./publicPrincipalHistoryTypes\";\n\n/** The greatest cited Admins head commits to the lineage of every earlier citation. */\nexport function publicHistoryAuthorityReference(\n previous: ReferencedPrincipalHead | null,\n references: readonly ReferencedPrincipalHead[],\n) {\n return references.reduce<ReferencedPrincipalHead | null>(\n (head, reference) =>\n !head || reference.version > head.version ? reference : head,\n previous,\n );\n}\n\nexport function publicHistoryAuthorityJson(\n reference: ReferencedPrincipalHead | null,\n) {\n return serializeKeyingCanonicalJson(reference ? { ...reference } : null);\n}\n\nexport function parsePublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n json: string,\n): ReferencedPrincipalHead | null | undefined {\n try {\n const value: unknown = JSON.parse(json);\n if (value === null) return null;\n if (\n isReferencedPrincipalStateResponse(value) &&\n value.principalType === \"group\" &&\n value.principalId === input.authorityGroupId\n )\n return value;\n } catch {\n /* Invalid disposable metadata cannot restore verified progress. */\n }\n return undefined;\n}\n\nexport async function loadPublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix = false,\n) {\n if (!references.length) return undefined;\n const authority = await input.loadExternalAuthority?.(\n references,\n cachedPrefix,\n );\n if (\n authority &&\n (authority.currentHead.principalId !== input.authorityGroupId ||\n authority.states.some(\n ({ head }) => head.principalId !== input.authorityGroupId,\n ))\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Authority callback differs from the directory binding\",\n );\n if (\n references.some(\n (reference) =>\n !authority?.states.some(({ head }) =>\n principalHeadMatchesReference(head, reference),\n ),\n )\n )\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Public history authority differs from its verified Admins lineage\",\n );\n return authority;\n}\n\nexport async function validatePublicHistoryAuthority(\n input: PublicPrincipalHistoryOptions,\n reference: ReferencedPrincipalHead | null,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n): Promise<void> {\n try {\n if (reference) await loadPublicHistoryAuthority(input, [reference], true);\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PublicHistoryAuthorityUnavailableError(error, rejectedPrefix);\n throw error;\n }\n}\n\n/** Only cache restoration can request a replay after an authority mismatch. */\nexport class PublicHistoryAuthorityUnavailableError extends Error {\n constructor(\n readonly verificationError: KeyingVerificationError,\n readonly rejectedPrefix: PrincipalHistoryPrefix | null,\n ) {\n super(verificationError.message);\n this.name = \"PublicHistoryAuthorityUnavailableError\";\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { createPrincipalPolicyHistoryVerifier, KeyingVerificationError, restorePrincipalPolicyHistoryVerifier, serializeKeyingCanonicalJson, verifyPrincipalPolicyHistoryReferences, } from "../../../internal/crypto/index.js";
2
2
  import { isReferencedPrincipalStateResponse } from "../../../internal/validators/response/index.js";
3
3
  import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
4
- import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
4
+ import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
5
5
  import { principalHistoryEvidenceScopeId, principalHistoryPrefixProtection, } from "../../../data/principals/principalHistoryPrefixProtection.js";
6
6
  import { principalHistoryStageId, principalHistoryStageProtection, } from "../../../data/principals/principalHistoryStageProtection.js";
7
7
  import { PublicHistoryAuthorityUnavailableError, parsePublicHistoryAuthority, publicHistoryAuthorityJson, validatePublicHistoryAuthority, } from "./publicPrincipalHistoryAuthority.js";