@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":"publicPrincipalHistoryProgress.js","sourceRoot":"","sources":["publicPrincipalHistoryProgress.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,qCAAqC,EACrC,4BAA4B,EAE5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,gCAAgC,CAAC;AAEpF,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,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EAAE,QAAQ;KACzB,CAAC,CAAC;IACH,IAAI,QAAQ,CAAC,KAAK;QAChB,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,4BAA4B,CAAC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyHistory,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport {\n principalHistoryStageId,\n principalHistoryStageProtection,\n} from \"../../../data/principals/principalHistoryStageProtection\";\nimport {\n PublicHistoryAuthorityUnavailableError,\n parsePublicHistoryAuthority,\n publicHistoryAuthorityJson,\n validatePublicHistoryAuthority,\n} from \"./publicPrincipalHistoryAuthority\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryTypes\";\n\nfunction parsedJsonOrNull(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\nasync function restorePublicPrefix(\n input: PublicPrincipalHistoryOptions,\n scopeId: string,\n id: string,\n prefix: PrincipalHistoryPrefix | null,\n): Promise<PublicPrincipalHistoryProgress | null> {\n const head = input.source.head;\n const historyInput = {\n principalType: head.principalType,\n principalId: head.principalId,\n };\n const current = () => !input.signal?.aborted && input.stillCurrent();\n if (prefix) {\n const authorityReference = parsePublicHistoryAuthority(\n input,\n prefix.currentJson,\n );\n const prefixHead = parsedJsonOrNull(prefix.headJson);\n if (\n prefix.organizationId === input.organizationId &&\n authorityReference !== undefined &&\n isReferencedPrincipalStateResponse(prefixHead) &&\n prefixHead.principalId === head.principalId &&\n prefixHead.principalType === head.principalType &&\n prefixHead.version === prefix.version\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n prefix.progress,\n await principalHistoryPrefixProtection(input.protection, prefix),\n );\n if (restored.ok && restored.value.finish(prefixHead).ok) {\n await validatePublicHistoryAuthority(input, authorityReference, prefix);\n return {\n id,\n scopeId,\n verifier: restored.value,\n completedHead: prefixHead.version >= head.version ? prefixHead : null,\n afterVersion: Math.min(prefixHead.version, head.version - 1),\n saved: null,\n cachedPrefix: prefix,\n authorityReference,\n };\n }\n }\n if (!input.offline)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryPrefix({\n prefix,\n stillCurrent: current,\n });\n }\n return null;\n}\n\ntype RestoredVerifier = Awaited<\n ReturnType<typeof restorePrincipalPolicyHistoryVerifier>\n>;\n\n/** A restored verifier is reusable when a completed stage still finishes. */\nfunction finishesSavedHistory(\n restored: RestoredVerifier,\n complete: boolean,\n head: PublicPrincipalHistoryOptions[\"source\"][\"head\"],\n): restored is Extract<RestoredVerifier, { ok: true }> {\n return restored.ok && (!complete || restored.value.finish(head).ok);\n}\n\nexport async function restorePublicPrincipalHistoryProgress(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n): Promise<PublicPrincipalHistoryProgress> {\n const head = input.source.head;\n const historyInput = {\n principalType: head.principalType,\n principalId: head.principalId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head,\n protection: input.protection,\n });\n const id = await principalHistoryStageId(\n input.organizationId,\n head,\n input.protection.context,\n );\n const current = () => !input.signal?.aborted && input.stillCurrent();\n const saved = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryStage(id);\n if (saved) {\n const authorityReference = parsePublicHistoryAuthority(\n input,\n saved.currentJson,\n );\n if (\n allowReuse &&\n saved.organizationId === input.organizationId &&\n authorityReference !== undefined\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n saved.progress,\n await principalHistoryStageProtection(input.protection, head, saved),\n );\n if (finishesSavedHistory(restored, saved.complete, head)) {\n await validatePublicHistoryAuthority(input, authorityReference);\n return {\n id,\n scopeId,\n verifier: restored.value,\n completedHead: saved.complete ? head : null,\n afterVersion: saved.afterVersion,\n saved,\n cachedPrefix: null,\n authorityReference,\n };\n }\n }\n if (!input.offline)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryStage(saved, current);\n }\n const prefix = allowReuse\n ? await restorePublicPrefix(\n input,\n scopeId,\n id,\n await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryPrefix(scopeId),\n )\n : null;\n if (prefix) return prefix;\n return {\n id,\n scopeId,\n verifier: createPrincipalPolicyHistoryVerifier(historyInput),\n completedHead: null,\n afterVersion: 0,\n saved: null,\n cachedPrefix: null,\n authorityReference: null,\n };\n}\n\n/** A resumed stage may finish after the reader that rejected the prefix exits. */\nasync function rejectedCompletedPrefix(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n history: VerifiedPrincipalPolicyHistory,\n): Promise<PrincipalHistoryPrefix | null> {\n const candidate = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryPrefix(progress.scopeId);\n if (!candidate || candidate.version <= history.currentEntry.state.version)\n return null;\n try {\n const cached = await restorePublicPrefix(\n input,\n progress.scopeId,\n progress.id,\n candidate,\n );\n if (!cached?.completedHead) return null;\n const finished = cached.verifier.finish(cached.completedHead);\n if (!finished.ok) throw finished.error;\n const proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history: finished.value,\n version: input.source.head.version,\n });\n const verified = await verifyPrincipalPolicyHistoryReferences({\n history: finished.value,\n references: [proof],\n });\n if (!verified.ok) throw verified.error;\n return principalHeadMatchesReference(proof.entry.state, input.source.head)\n ? null\n : candidate;\n } catch (error) {\n if (\n error instanceof KeyingVerificationError ||\n error instanceof PublicHistoryAuthorityUnavailableError\n )\n return candidate;\n throw error;\n }\n}\n\nexport async function publishPublicPrincipalHistoryPrefix(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n history: VerifiedPrincipalPolicyHistory,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n): Promise<void> {\n const state = history.currentEntry.state;\n const head = {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n const prefix = {\n scopeId: progress.scopeId,\n organizationId: input.organizationId,\n version: head.version,\n headJson: serializeKeyingCanonicalJson(head),\n currentJson: publicHistoryAuthorityJson(progress.authorityReference),\n };\n const sealed = await progress.verifier.exportProgress(\n await principalHistoryPrefixProtection(input.protection, prefix),\n );\n if (!sealed.ok) throw sealed.error;\n const rejected =\n rejectedPrefix ??\n (progress.cachedPrefix\n ? null\n : await rejectedCompletedPrefix(input, progress, history));\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n await new PrincipalHistoryRepository(\n input.execSql,\n ).savePrincipalHistoryPrefix({\n indexRootHash: history.indexRootHash,\n prefix: { ...prefix, progress: sealed.value },\n stillCurrent,\n rejectedPrefix: rejected,\n });\n if (progress.saved)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryStage(progress.saved, stillCurrent);\n}\n"]}
1
+ {"version":3,"file":"publicPrincipalHistoryProgress.js","sourceRoot":"","sources":["publicPrincipalHistoryProgress.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,qCAAqC,EACrC,4BAA4B,EAE5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;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OAAO,CACd,CAAC,0BAA0B,CAAC;QAC3B,aAAa,EAAE,OAAO,CAAC,aAAa;QACpC,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,QAAQ,EAAE,MAAM,CAAC,KAAK,EAAE;QAC7C,YAAY;QACZ,cAAc,EAAE,QAAQ;KACzB,CAAC,CAAC;IACH,IAAI,QAAQ,CAAC,KAAK;QAChB,MAAM,IAAI,0BAA0B,CAClC,KAAK,CAAC,OAAO,CACd,CAAC,4BAA4B,CAAC,QAAQ,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AACjE,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyHistory,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { isReferencedPrincipalStateResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport {\n principalHistoryStageId,\n principalHistoryStageProtection,\n} from \"../../../data/principals/principalHistoryStageProtection\";\nimport {\n PublicHistoryAuthorityUnavailableError,\n parsePublicHistoryAuthority,\n publicHistoryAuthorityJson,\n validatePublicHistoryAuthority,\n} from \"./publicPrincipalHistoryAuthority\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryTypes\";\n\nfunction parsedJsonOrNull(json: string): unknown {\n try {\n return JSON.parse(json);\n } catch {\n return null;\n }\n}\n\nasync function restorePublicPrefix(\n input: PublicPrincipalHistoryOptions,\n scopeId: string,\n id: string,\n prefix: PrincipalHistoryPrefix | null,\n): Promise<PublicPrincipalHistoryProgress | null> {\n const head = input.source.head;\n const historyInput = {\n principalType: head.principalType,\n principalId: head.principalId,\n };\n const current = () => !input.signal?.aborted && input.stillCurrent();\n if (prefix) {\n const authorityReference = parsePublicHistoryAuthority(\n input,\n prefix.currentJson,\n );\n const prefixHead = parsedJsonOrNull(prefix.headJson);\n if (\n prefix.organizationId === input.organizationId &&\n authorityReference !== undefined &&\n isReferencedPrincipalStateResponse(prefixHead) &&\n prefixHead.principalId === head.principalId &&\n prefixHead.principalType === head.principalType &&\n prefixHead.version === prefix.version\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n prefix.progress,\n await principalHistoryPrefixProtection(input.protection, prefix),\n );\n if (restored.ok && restored.value.finish(prefixHead).ok) {\n await validatePublicHistoryAuthority(input, authorityReference, prefix);\n return {\n id,\n scopeId,\n verifier: restored.value,\n completedHead: prefixHead.version >= head.version ? prefixHead : null,\n afterVersion: Math.min(prefixHead.version, head.version - 1),\n saved: null,\n cachedPrefix: prefix,\n authorityReference,\n };\n }\n }\n if (!input.offline)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryPrefix({\n prefix,\n stillCurrent: current,\n });\n }\n return null;\n}\n\ntype RestoredVerifier = Awaited<\n ReturnType<typeof restorePrincipalPolicyHistoryVerifier>\n>;\n\n/** A restored verifier is reusable when a completed stage still finishes. */\nfunction finishesSavedHistory(\n restored: RestoredVerifier,\n complete: boolean,\n head: PublicPrincipalHistoryOptions[\"source\"][\"head\"],\n): restored is Extract<RestoredVerifier, { ok: true }> {\n return restored.ok && (!complete || restored.value.finish(head).ok);\n}\n\nexport async function restorePublicPrincipalHistoryProgress(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n): Promise<PublicPrincipalHistoryProgress> {\n const head = input.source.head;\n const historyInput = {\n principalType: head.principalType,\n principalId: head.principalId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head,\n protection: input.protection,\n });\n const id = await principalHistoryStageId(\n input.organizationId,\n head,\n input.protection.context,\n );\n const current = () => !input.signal?.aborted && input.stillCurrent();\n const saved = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryStage(id);\n if (saved) {\n const authorityReference = parsePublicHistoryAuthority(\n input,\n saved.currentJson,\n );\n if (\n allowReuse &&\n saved.organizationId === input.organizationId &&\n authorityReference !== undefined\n ) {\n const restored = await restorePrincipalPolicyHistoryVerifier(\n historyInput,\n saved.progress,\n await principalHistoryStageProtection(input.protection, head, saved),\n );\n if (finishesSavedHistory(restored, saved.complete, head)) {\n await validatePublicHistoryAuthority(input, authorityReference);\n return {\n id,\n scopeId,\n verifier: restored.value,\n completedHead: saved.complete ? head : null,\n afterVersion: saved.afterVersion,\n saved,\n cachedPrefix: null,\n authorityReference,\n };\n }\n }\n if (!input.offline)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryStage(saved, current);\n }\n const prefix = allowReuse\n ? await restorePublicPrefix(\n input,\n scopeId,\n id,\n await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryPrefix(scopeId),\n )\n : null;\n if (prefix) return prefix;\n return {\n id,\n scopeId,\n verifier: createPrincipalPolicyHistoryVerifier(historyInput),\n completedHead: null,\n afterVersion: 0,\n saved: null,\n cachedPrefix: null,\n authorityReference: null,\n };\n}\n\n/** A resumed stage may finish after the reader that rejected the prefix exits. */\nasync function rejectedCompletedPrefix(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n history: VerifiedPrincipalPolicyHistory,\n): Promise<PrincipalHistoryPrefix | null> {\n const candidate = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryPrefix(progress.scopeId);\n if (!candidate || candidate.version <= history.currentEntry.state.version)\n return null;\n try {\n const cached = await restorePublicPrefix(\n input,\n progress.scopeId,\n progress.id,\n candidate,\n );\n if (!cached?.completedHead) return null;\n const finished = cached.verifier.finish(cached.completedHead);\n if (!finished.ok) throw finished.error;\n const proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history: finished.value,\n version: input.source.head.version,\n });\n const verified = await verifyPrincipalPolicyHistoryReferences({\n history: finished.value,\n references: [proof],\n });\n if (!verified.ok) throw verified.error;\n return principalHeadMatchesReference(proof.entry.state, input.source.head)\n ? null\n : candidate;\n } catch (error) {\n if (\n error instanceof KeyingVerificationError ||\n error instanceof PublicHistoryAuthorityUnavailableError\n )\n return candidate;\n throw error;\n }\n}\n\nexport async function publishPublicPrincipalHistoryPrefix(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n history: VerifiedPrincipalPolicyHistory,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n): Promise<void> {\n const state = history.currentEntry.state;\n const head = {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n const prefix = {\n scopeId: progress.scopeId,\n organizationId: input.organizationId,\n version: head.version,\n headJson: serializeKeyingCanonicalJson(head),\n currentJson: publicHistoryAuthorityJson(progress.authorityReference),\n };\n const sealed = await progress.verifier.exportProgress(\n await principalHistoryPrefixProtection(input.protection, prefix),\n );\n if (!sealed.ok) throw sealed.error;\n const rejected =\n rejectedPrefix ??\n (progress.cachedPrefix\n ? null\n : await rejectedCompletedPrefix(input, progress, history));\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n await new PrincipalHistoryRepository(\n input.execSql,\n ).savePrincipalHistoryPrefix({\n indexRootHash: history.indexRootHash,\n prefix: { ...prefix, progress: sealed.value },\n stillCurrent,\n rejectedPrefix: rejected,\n });\n if (progress.saved)\n await new PrincipalHistoryRepository(\n input.execSql,\n ).discardPrincipalHistoryStage(progress.saved, stillCurrent);\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { computePrincipalStatePayloadCiphertextHash, } from "../../../internal/crypto/index.js";
2
- import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
2
+ import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
3
3
  import { rejectPublicProjection, selectPublicProjectionPrincipal, } from "./publicProjectionPrincipal.js";
4
4
  export async function publicProjectionDirectoryBindings(evidence, organization) {
5
5
  const policies = await selectPublicProjectionPrincipal(organization);
@@ -1 +1 @@
1
- {"version":3,"file":"publicProjectionDirectory.js","sourceRoot":"","sources":["publicProjectionDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0CAA0C,GAE3C,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAEL,sBAAsB,EACtB,+BAA+B,GAChC,MAAM,6BAA6B,CAAC;AAErC,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,QAA0C,EAC1C,YAAuC;IAEvC,MAAM,QAAQ,GAAG,MAAM,+BAA+B,CAAC,YAAY,CAAC,CAAC;IACrE,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;IACrE,MAAM,WAAW,GAAG,EAAE,CAAC;IACvB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,QAAQ,CAAC,oBAAoB,EAAE,CAAC;QACnE,MAAM,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CACvC,6BAA6B,CAAC,KAAK,EAAE,SAAS,CAAC,CAChD,EAAE,KAAK,CAAC;QACT,IACE,CAAC,KAAK;YACN,SAAS,CAAC,OAA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CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CACjD,CACF,CAAC;QACF,MAAM,SAAS,GAAG,SAAS,EAAE,UAAU,CAAC,IAAI,CAC1C,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,YAAY,CACtD,CAAC;QACF,IAAI,CAAC,SAAS;YACZ,sBAAsB,CAAC,iDAAiD,CAAC,CAAC;QAC5E,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n type PublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport async function publicProjectionDirectoryBindings(\n evidence: ProjectionPolicyEvidenceResponse,\n organization: PublicProjectionPrincipal,\n) {\n const policies = await selectPublicProjectionPrincipal(organization);\n const entries = policies.flatMap((policy) => policy.retainedHistory);\n const descriptors = [];\n const seen = new Set<string>();\n for (const { reference, payload } of evidence.organizationPayloads) {\n const state = entries.find(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )?.state;\n if (\n !state ||\n reference.version > organization.options.source.head.version ||\n payload.principalType !== \"organization\" ||\n payload.principalId !== organization.options.organizationId ||\n payload.stateHash !== state.stateHash ||\n seen.has(state.stateHash)\n )\n rejectPublicProjection(\"directory payload scope is invalid\");\n seen.add(state.stateHash);\n const hash = await computePrincipalStatePayloadCiphertextHash(\n payload.ciphertext,\n );\n if (hash !== payload.ciphertextHash || hash !== state.payloadCiphertextHash)\n rejectPublicProjection(\"directory payload differs from its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== organization.options.organizationId)\n rejectPublicProjection(\"directory belongs to another organization\");\n descriptors.push(descriptor);\n }\n const bindings = new Map<string, { adminHead: ReferencedPrincipalHead }>();\n for (const source of evidence.groups) {\n if (\n source.head.principalType !== \"group\" ||\n bindings.has(source.head.principalId)\n )\n rejectPublicProjection(\"group sources have invalid or repeated scopes\");\n const directory = descriptors.find((candidate) =>\n candidate.groupHeads.some((head) =>\n principalHeadMatchesReference(head, source.head),\n ),\n );\n const adminHead = directory?.groupHeads.find(\n (head) => head.principalId === directory.adminGroupId,\n );\n if (!adminHead)\n rejectPublicProjection(\"group source lacks its signed directory binding\");\n bindings.set(source.head.principalId, { adminHead });\n }\n return bindings;\n}\n"]}
1
+ {"version":3,"file":"publicProjectionDirectory.js","sourceRoot":"","sources":["publicProjectionDirectory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,0CAA0C,GAE3C,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAEL,sBAAsB,EACtB,+BAA+B,GAChC,MAAM,6BAA6B,CAAC;AAErC,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,QAA0C,EAC1C,YAAuC;IAEvC,MAAM,QAAQ,GAAG,MAAM,+BAA+B,CAAC,YAAY,CAAC,CAAC;IACrE,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC;IACrE,MAAM,WAAW,GAAG,EAAE,CAAC;IACvB,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,QAAQ,CAAC,oBAAoB,EAAE,CAAC;QACnE,MAAM,KAAK,GAAG,O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C,CAAC,CAAC;QAC1E,MAAM,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAC/C,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CACjC,6BAA6B,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,CACjD,CACF,CAAC;QACF,MAAM,SAAS,GAAG,SAAS,EAAE,UAAU,CAAC,IAAI,CAC1C,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,YAAY,CACtD,CAAC;QACF,IAAI,CAAC,SAAS;YACZ,sBAAsB,CAAC,iDAAiD,CAAC,CAAC;QAC5E,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,EAAE,SAAS,EAAE,CAAC,CAAC;IACvD,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport {\n type PublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport async function publicProjectionDirectoryBindings(\n evidence: ProjectionPolicyEvidenceResponse,\n organization: PublicProjectionPrincipal,\n) {\n const policies = await selectPublicProjectionPrincipal(organization);\n const entries = policies.flatMap((policy) => policy.retainedHistory);\n const descriptors = [];\n const seen = new Set<string>();\n for (const { reference, payload } of evidence.organizationPayloads) {\n const state = entries.find(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )?.state;\n if (\n !state ||\n reference.version > organization.options.source.head.version ||\n payload.principalType !== \"organization\" ||\n payload.principalId !== organization.options.organizationId ||\n payload.stateHash !== state.stateHash ||\n seen.has(state.stateHash)\n )\n rejectPublicProjection(\"directory payload scope is invalid\");\n seen.add(state.stateHash);\n const hash = await computePrincipalStatePayloadCiphertextHash(\n payload.ciphertext,\n );\n if (hash !== payload.ciphertextHash || hash !== state.payloadCiphertextHash)\n rejectPublicProjection(\"directory payload differs from its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== organization.options.organizationId)\n rejectPublicProjection(\"directory belongs to another organization\");\n descriptors.push(descriptor);\n }\n const bindings = new Map<string, { adminHead: ReferencedPrincipalHead }>();\n for (const source of evidence.groups) {\n if (\n source.head.principalType !== \"group\" ||\n bindings.has(source.head.principalId)\n )\n rejectPublicProjection(\"group sources have invalid or repeated scopes\");\n const directory = descriptors.find((candidate) =>\n candidate.groupHeads.some((head) =>\n principalHeadMatchesReference(head, source.head),\n ),\n );\n const adminHead = directory?.groupHeads.find(\n (head) => head.principalId === directory.adminGroupId,\n );\n if (!adminHead)\n rejectPublicProjection(\"group source lacks its signed directory binding\");\n bindings.set(source.head.principalId, { adminHead });\n }\n return bindings;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
- import { assertSelectedPolicyCommitments } from "../../../data/principals/principalIdentityCommitments.js";
4
+ import { assertSelectedPolicyCommitments } from "../../../data/principalContracts/principalIdentityCommitments.js";
5
5
  import { PrincipalHistoryEvidenceUnavailableError } from "../historyRecovery/principalHistoryRecoveryReferences.js";
6
6
  import { recoverPublicPrincipalHistory } from "./recoverPublicPrincipalHistory.js";
7
7
  import { selectPublicPrincipalHistory } from "./selectPublicPrincipalHistory.js";
@@ -1 +1 @@
1
- {"version":3,"file":"publicProjectionPrincipal.js","sourceRoot":"","sources":["publicProjectionPrinc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AC;QACrC,SAAS,EAAE,MAAM,6BAA6B,CAAC,OAAO,CAAC;QACvD,QAAQ,EAAE,KAAK;KAChB,CAAC;IACF,MAAM,+BAA+B,CAAC,SAAS,CAAC,CAAC;IACjD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED,MAAM,UAAU,sBAAsB,CAAC,OAAe;IACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8BAA8B,OAAO,EAAE,CACxC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertSelectedPolicyCommitments } from \"../../../data/principals/principalIdentityCommitments\";\nimport { PrincipalHistoryEvidenceUnavailableError } from \"../historyRecovery/principalHistoryRecoveryReferences\";\nimport type {\n PublicPrincipalHistoryOptions,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\nimport { recoverPublicPrincipalHistory } from \"./recoverPublicPrincipalHistory\";\nimport { selectPublicPrincipalHistory } from \"./selectPublicPrincipalHistory\";\n\nexport interface PublicProjectionPrincipal {\n readonly options: PublicPrincipalHistoryOptions;\n readonly references: readonly ReferencedPrincipalHead[];\n recovered: RecoveredPublicPrincipalHistory;\n replayed: boolean;\n}\n\n/** The source head and every citation remain bound independently of a newer prefix. */\nexport async function selectPublicProjectionPrincipal(\n principal: PublicProjectionPrincipal,\n references: readonly ReferencedPrincipalHead[] = principal.references,\n) {\n const { options } = principal;\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const checkpoint = await new KeyingCheckpointRepository(\n options.execSql,\n ).loadPrincipalPolicyCheckpoint(\n options.source.head.principalType,\n options.source.head.principalId,\n );\n let policies: Awaited<ReturnType<typeof selectPublicPrincipalHistory>>;\n try {\n policies = await selectPublicPrincipalHistory({\n execSql: options.execSql,\n recovered: principal.recovered,\n references: [options.source.head, ...references],\n checkpoint,\n deferCheckpointCheck: options.historicalProof,\n includeGenesis: options.source.head.principalType === \"organization\",\n stillCurrent: current,\n });\n } catch (error) {\n if (!(error instanceof PrincipalHistoryEvidenceUnavailableError))\n throw error;\n if (options.offline || principal.replayed) throw error.verificationError;\n principal.replayed = true;\n principal.recovered = await recoverPublicPrincipalHistory({\n ...options,\n replay: true,\n });\n return selectPublicProjectionPrincipal(principal, references);\n }\n await assertSelectedPolicyCommitments(\n policies,\n options.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n return policies;\n}\n\nexport async function recoverPublicProjectionPrincipal(\n options: PublicPrincipalHistoryOptions,\n references: readonly ReferencedPrincipalHead[],\n): Promise<PublicProjectionPrincipal> {\n const selected = references.filter(\n (head) =>\n head.principalType === options.source.head.principalType &&\n head.principalId === options.source.head.principalId,\n );\n if (selected.some((head) => head.version > options.source.head.version))\n rejectPublicProjection(\"citation exceeds its supplied source head\");\n const principal = {\n options,\n references: structuredClone(selected),\n recovered: await recoverPublicPrincipalHistory(options),\n replayed: false,\n };\n await selectPublicProjectionPrincipal(principal);\n return principal;\n}\n\nexport function rejectPublicProjection(message: string): never {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `Public projection history: ${message}`,\n );\n}\n"]}
1
+ {"version":3,"file":"publicProjectionPrincipal.js","sourceRoot":"","sources":["publicProjectionPrincipal.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,+DAA+D,CAAC;AAChH,OAAO,EAAE,wCAAwC,EAAE,MAAM,uDAAuD,CAAC;AAKjH,OA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AAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertSelectedPolicyCommitments } from \"../../../data/principalContracts/principalIdentityCommitments\";\nimport { PrincipalHistoryEvidenceUnavailableError } from \"../historyRecovery/principalHistoryRecoveryReferences\";\nimport type {\n PublicPrincipalHistoryOptions,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\nimport { recoverPublicPrincipalHistory } from \"./recoverPublicPrincipalHistory\";\nimport { selectPublicPrincipalHistory } from \"./selectPublicPrincipalHistory\";\n\nexport interface PublicProjectionPrincipal {\n readonly options: PublicPrincipalHistoryOptions;\n readonly references: readonly ReferencedPrincipalHead[];\n recovered: RecoveredPublicPrincipalHistory;\n replayed: boolean;\n}\n\n/** The source head and every citation remain bound independently of a newer prefix. */\nexport async function selectPublicProjectionPrincipal(\n principal: PublicProjectionPrincipal,\n references: readonly ReferencedPrincipalHead[] = principal.references,\n) {\n const { options } = principal;\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const checkpoint = await new KeyingCheckpointRepository(\n options.execSql,\n ).loadPrincipalPolicyCheckpoint(\n options.source.head.principalType,\n options.source.head.principalId,\n );\n let policies: Awaited<ReturnType<typeof selectPublicPrincipalHistory>>;\n try {\n policies = await selectPublicPrincipalHistory({\n execSql: options.execSql,\n recovered: principal.recovered,\n references: [options.source.head, ...references],\n checkpoint,\n deferCheckpointCheck: options.historicalProof,\n includeGenesis: options.source.head.principalType === \"organization\",\n stillCurrent: current,\n });\n } catch (error) {\n if (!(error instanceof PrincipalHistoryEvidenceUnavailableError))\n throw error;\n if (options.offline || principal.replayed) throw error.verificationError;\n principal.replayed = true;\n principal.recovered = await recoverPublicPrincipalHistory({\n ...options,\n replay: true,\n });\n return selectPublicProjectionPrincipal(principal, references);\n }\n await assertSelectedPolicyCommitments(\n policies,\n options.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n return policies;\n}\n\nexport async function recoverPublicProjectionPrincipal(\n options: PublicPrincipalHistoryOptions,\n references: readonly ReferencedPrincipalHead[],\n): Promise<PublicProjectionPrincipal> {\n const selected = references.filter(\n (head) =>\n head.principalType === options.source.head.principalType &&\n head.principalId === options.source.head.principalId,\n );\n if (selected.some((head) => head.version > options.source.head.version))\n rejectPublicProjection(\"citation exceeds its supplied source head\");\n const principal = {\n options,\n references: structuredClone(selected),\n recovered: await recoverPublicPrincipalHistory(options),\n replayed: false,\n };\n await selectPublicProjectionPrincipal(principal);\n return principal;\n}\n\nexport function rejectPublicProjection(message: string): never {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `Public projection history: ${message}`,\n );\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
3
- import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
3
+ import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
4
4
  import { publicProjectionDirectoryBindings } from "./publicProjectionDirectory.js";
5
5
  import { recoverPublicProjectionPrincipal, rejectPublicProjection, selectPublicProjectionPrincipal, } from "./publicProjectionPrincipal.js";
6
6
  function assertSourceCoverage(evidence, references) {
@@ -1 +1 @@
1
- {"version":3,"file":"recoverProjectionPolicyHistory.js","sourceRoot":"","sources":["recoverProjectionPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AAE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C,IAAI,CAAC,GAAG,CAAC,MAAM,+BAA+B,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IACvE,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { PublicPrincipalHistoryOptions } from \"./publicPrincipalHistoryTypes\";\nimport { publicProjectionDirectoryBindings } from \"./publicProjectionDirectory\";\nimport {\n type PublicProjectionPrincipal,\n recoverPublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport interface ProjectionPolicyHistoryRecoveryOptions\n extends Omit<\n PublicPrincipalHistoryOptions,\n | \"source\"\n | \"loadExternalAuthority\"\n | \"strictAdmins\"\n | \"authorityGroupId\"\n | \"replay\"\n > {\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly references: readonly ReferencedPrincipalHead[];\n}\n\nfunction assertSourceCoverage(\n evidence: ProjectionPolicyEvidenceResponse,\n references: readonly ReferencedPrincipalHead[],\n): void {\n const sources = [evidence.organization, ...evidence.groups];\n for (const reference of references)\n if (\n !sources.some(\n (source) =>\n source &&\n source.head.principalType === reference.principalType &&\n source.head.principalId === reference.principalId &&\n source.head.version >= reference.version,\n )\n )\n rejectPublicProjection(\"required citation has no covering source\");\n}\n\nasync function externalAuthority(\n admins: PublicProjectionPrincipal,\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix = false,\n): Promise<PrincipalPolicyExternalAuthority | undefined> {\n const head = admins.options.source.head;\n if (!references.length) return undefined;\n if (\n cachedPrefix &&\n references.some((reference) => reference.version > head.version)\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Cached group history requires a newer Admins source\",\n );\n if (\n references.some(\n (reference) =>\n reference.principalId !== head.principalId ||\n reference.version > head.version,\n )\n )\n rejectPublicProjection(\n \"external authority exceeds the bound Admins source\",\n );\n const policies = await selectPublicProjectionPrincipal(admins, references);\n const states = new Map(\n policies.flatMap((policy) =>\n // Only this page's citations and the bound source head are authority for\n // this verification step. A retained newer prefix is not another citation.\n policy.retainedHistory\n .filter(({ state }) =>\n [head, ...references].some((reference) =>\n principalHeadMatchesReference(state, reference),\n ),\n )\n .map(\n ({ state, projection }) =>\n [\n state.version,\n {\n head: {\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 projection,\n },\n ] as const,\n ),\n ),\n );\n return {\n currentHead: { ...head, principalType: \"group\" },\n states: [...states.values()],\n };\n}\n\n/** Public authorization only; no current-policy cache or checkpoint is written. */\nexport async function recoverProjectionPolicyHistory(\n input: ProjectionPolicyHistoryRecoveryOptions,\n): Promise<VerifiedPrincipalPolicySelection[]> {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n input = { ...input, references: structuredClone(input.references) };\n const evidence = structuredClone(input.evidence);\n assertSourceCoverage(evidence, input.references);\n if (!evidence.organization) {\n if (evidence.groups.length || evidence.organizationPayloads.length)\n rejectPublicProjection(\"group evidence requires organization history\");\n return [];\n }\n if (evidence.organization.head.principalType !== \"organization\")\n rejectPublicProjection(\"organization source has the wrong principal type\");\n const organization = await recoverPublicProjectionPrincipal(\n {\n ...input,\n source: evidence.organization,\n },\n [\n ...input.references,\n ...evidence.organizationPayloads.map(({ reference }) => reference),\n ],\n );\n const bindings = await publicProjectionDirectoryBindings(\n evidence,\n organization,\n );\n const principals = new Map<string, PublicProjectionPrincipal>();\n const adminHeads = [...bindings.values()].map(({ adminHead }) => adminHead);\n for (const adminId of new Set(adminHeads.map((head) => head.principalId))) {\n const source = evidence.groups.find(\n (group) => group.head.principalId === adminId,\n );\n if (!source) rejectPublicProjection(\"signed Admins source is missing\");\n principals.set(\n adminId,\n await recoverPublicProjectionPrincipal(\n { ...input, source, strictAdmins: true },\n [...input.references, ...adminHeads],\n ),\n );\n }\n for (const source of evidence.groups) {\n if (principals.has(source.head.principalId)) continue;\n const binding = bindings.get(source.head.principalId);\n const admins = binding && principals.get(binding.adminHead.principalId);\n if (!admins) rejectPublicProjection(\"verified Admins history is missing\");\n principals.set(\n source.head.principalId,\n await recoverPublicProjectionPrincipal(\n {\n ...input,\n source,\n authorityGroupId: admins.options.source.head.principalId,\n loadExternalAuthority: (references, cachedPrefix) =>\n externalAuthority(admins, references, cachedPrefix),\n },\n input.references,\n ),\n );\n }\n const policies: VerifiedPrincipalPolicySelection[] = [];\n for (const principal of [organization, ...principals.values()])\n policies.push(...(await selectPublicProjectionPrincipal(principal)));\n return policies;\n}\n"]}
1
+ {"version":3,"file":"recoverProjectionPolicyHistory.js","sourceRoot":"","sources":["recoverProjectionPolicyHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAChF,OAAO,EAEL,gCAAgC,EAChC,sBAAsB,EACtB,+BAA+B,GAChC,MAAM,6BAA6B,CAAC;AAerC,SAAS,oBAAoB,CAC3B,QAA0C,EAC1C,UAA8C;IAE9C,MAAM,OAAO,GAAG,CAAC,QAAQ,CAAC,YAAY,EAAE,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC;IAC5D,KAAK,MAAM,SAAS,IAAI,UAAU;QAChC,IACE,CAAC,OAAO,CAAC,IAAI,CACX,CAAC,MAAM,EAAE,EAAE,CACT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AE,CAAC;QACrC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC;YAAE,SAAS;QACtD,MAAM,OAAO,GAAG,QAAQ,CAAC,GAAG,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QACtD,MAAM,MAAM,GAAG,OAAO,IAAI,UAAU,CAAC,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,WAAW,CAAC,CAAC;QACxE,IAAI,CAAC,MAAM;YAAE,sBAAsB,CAAC,oCAAoC,CAAC,CAAC;QAC1E,UAAU,CAAC,GAAG,CACZ,MAAM,CAAC,IAAI,CAAC,WAAW,EACvB,MAAM,gCAAgC,CACpC;YACE,GAAG,KAAK;YACR,MAAM;YACN,gBAAgB,EAAE,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,WAAW;YACxD,qBAAqB,EAAE,CAAC,UAAU,EAAE,YAAY,EAAE,EAAE,CAClD,iBAAiB,CAAC,MAAM,EAAE,UAAU,EAAE,YAAY,CAAC;SACtD,EACD,KAAK,CAAC,UAAU,CACjB,CACF,CAAC;IACJ,CAAC;IACD,MAAM,QAAQ,GAAuC,EAAE,CAAC;IACxD,KAAK,MAAM,SAAS,IAAI,CAAC,YAAY,EAAE,GAAG,UAAU,CAAC,MAAM,EAAE,CAAC;QAC5D,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,+BAA+B,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;IACvE,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { PublicPrincipalHistoryOptions } from \"./publicPrincipalHistoryTypes\";\nimport { publicProjectionDirectoryBindings } from \"./publicProjectionDirectory\";\nimport {\n type PublicProjectionPrincipal,\n recoverPublicProjectionPrincipal,\n rejectPublicProjection,\n selectPublicProjectionPrincipal,\n} from \"./publicProjectionPrincipal\";\n\nexport interface ProjectionPolicyHistoryRecoveryOptions\n extends Omit<\n PublicPrincipalHistoryOptions,\n | \"source\"\n | \"loadExternalAuthority\"\n | \"strictAdmins\"\n | \"authorityGroupId\"\n | \"replay\"\n > {\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly references: readonly ReferencedPrincipalHead[];\n}\n\nfunction assertSourceCoverage(\n evidence: ProjectionPolicyEvidenceResponse,\n references: readonly ReferencedPrincipalHead[],\n): void {\n const sources = [evidence.organization, ...evidence.groups];\n for (const reference of references)\n if (\n !sources.some(\n (source) =>\n source &&\n source.head.principalType === reference.principalType &&\n source.head.principalId === reference.principalId &&\n source.head.version >= reference.version,\n )\n )\n rejectPublicProjection(\"required citation has no covering source\");\n}\n\nasync function externalAuthority(\n admins: PublicProjectionPrincipal,\n references: readonly ReferencedPrincipalHead[],\n cachedPrefix = false,\n): Promise<PrincipalPolicyExternalAuthority | undefined> {\n const head = admins.options.source.head;\n if (!references.length) return undefined;\n if (\n cachedPrefix &&\n references.some((reference) => reference.version > head.version)\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Cached group history requires a newer Admins source\",\n );\n if (\n references.some(\n (reference) =>\n reference.principalId !== head.principalId ||\n reference.version > head.version,\n )\n )\n rejectPublicProjection(\n \"external authority exceeds the bound Admins source\",\n );\n const policies = await selectPublicProjectionPrincipal(admins, references);\n const states = new Map(\n policies.flatMap((policy) =>\n // Only this page's citations and the bound source head are authority for\n // this verification step. A retained newer prefix is not another citation.\n policy.retainedHistory\n .filter(({ state }) =>\n [head, ...references].some((reference) =>\n principalHeadMatchesReference(state, reference),\n ),\n )\n .map(\n ({ state, projection }) =>\n [\n state.version,\n {\n head: {\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 projection,\n },\n ] as const,\n ),\n ),\n );\n return {\n currentHead: { ...head, principalType: \"group\" },\n states: [...states.values()],\n };\n}\n\n/** Public authorization only; no current-policy cache or checkpoint is written. */\nexport async function recoverProjectionPolicyHistory(\n input: ProjectionPolicyHistoryRecoveryOptions,\n): Promise<VerifiedPrincipalPolicySelection[]> {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n input = { ...input, references: structuredClone(input.references) };\n const evidence = structuredClone(input.evidence);\n assertSourceCoverage(evidence, input.references);\n if (!evidence.organization) {\n if (evidence.groups.length || evidence.organizationPayloads.length)\n rejectPublicProjection(\"group evidence requires organization history\");\n return [];\n }\n if (evidence.organization.head.principalType !== \"organization\")\n rejectPublicProjection(\"organization source has the wrong principal type\");\n const organization = await recoverPublicProjectionPrincipal(\n {\n ...input,\n source: evidence.organization,\n },\n [\n ...input.references,\n ...evidence.organizationPayloads.map(({ reference }) => reference),\n ],\n );\n const bindings = await publicProjectionDirectoryBindings(\n evidence,\n organization,\n );\n const principals = new Map<string, PublicProjectionPrincipal>();\n const adminHeads = [...bindings.values()].map(({ adminHead }) => adminHead);\n for (const adminId of new Set(adminHeads.map((head) => head.principalId))) {\n const source = evidence.groups.find(\n (group) => group.head.principalId === adminId,\n );\n if (!source) rejectPublicProjection(\"signed Admins source is missing\");\n principals.set(\n adminId,\n await recoverPublicProjectionPrincipal(\n { ...input, source, strictAdmins: true },\n [...input.references, ...adminHeads],\n ),\n );\n }\n for (const source of evidence.groups) {\n if (principals.has(source.head.principalId)) continue;\n const binding = bindings.get(source.head.principalId);\n const admins = binding && principals.get(binding.adminHead.principalId);\n if (!admins) rejectPublicProjection(\"verified Admins history is missing\");\n principals.set(\n source.head.principalId,\n await recoverPublicProjectionPrincipal(\n {\n ...input,\n source,\n authorityGroupId: admins.options.source.head.principalId,\n loadExternalAuthority: (references, cachedPrefix) =>\n externalAuthority(admins, references, cachedPrefix),\n },\n input.references,\n ),\n );\n }\n const policies: VerifiedPrincipalPolicySelection[] = [];\n for (const principal of [organization, ...principals.values()])\n policies.push(...(await selectPublicProjectionPrincipal(principal)));\n return policies;\n}\n"]}
@@ -3,9 +3,9 @@ import { isPrincipalPolicySnapshotPage, } from "../../../internal/validators/res
3
3
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
4
4
  import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
5
5
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
6
- import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
6
+ import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
7
+ import { publishAuthenticatedSigners } from "../../../data/principalContracts/principalIdentityCommitments.js";
7
8
  import { ownPrincipalHistoryProtection } from "../../../data/principals/principalHistoryProtection.js";
8
- import { publishAuthenticatedSigners } from "../../../data/principals/principalIdentityCommitments.js";
9
9
  import { PrincipalPolicyHistoryReadError } from "../historyRecovery/principalHistoryRecoveryTypes.js";
10
10
  import { initialHeldHeadState, transitionHeldHeadState, } from "./heldHeadStateMachine.js";
11
11
  import { PublicHistoryAuthorityUnavailableError } from "./publicPrincipalHistoryAuthority.js";
@@ -1 +1 @@
1
- {"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,6BAA6B,GAG9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,E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UAAU,GAAG,6BAA6B,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;IACrE,UAAU,CAAC,OAAO,GAAG,4BAA4B,CAAC;QAChD,2CAA2C;QAC3C,UAAU,CAAC,OAAO;QAClB,OAAO,CAAC,YAAY,KAAK,IAAI;QAC7B,OAAO,CAAC,gBAAgB,IAAI,IAAI;KACjC,CAAC,CAAC;IACH,MAAM,KAAK,GAAG;QACZ,GAAG,OAAO;QACV,MAAM,EAAE,eAAe,CAAC,OAAO,CAAC,MAAM,CAAC;QACvC,UAAU;KACX,CAAC;IACF,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IACvD,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPage,\n type PrincipalPolicySnapshotPage,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport { publishAuthenticatedSigners } from \"../../../data/principals/principalIdentityCommitments\";\nimport { PrincipalPolicyHistoryReadError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n type HeldHeadState,\n initialHeldHeadState,\n transitionHeldHeadState,\n} from \"./heldHeadStateMachine\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\n/** The attempt's held-head machine; written only through its transition. */\ninterface HeldHeadCell {\n state: HeldHeadState;\n}\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPage,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPage(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\n/**\n * A held copy of the head replaces only its download; the final page appends\n * and checks it exactly as a served state.\n */\nasync function loadHeldHead(\n input: PublicPrincipalHistoryOptions,\n held: HeldHeadCell,\n): Promise<PrincipalStateResponse | undefined> {\n const knownCurrentState =\n held.state.status === \"eligible\"\n ? ((await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadHeldPrincipalState(input.source.head)) ?? undefined)\n : undefined;\n held.state = transitionHeldHeadState(held.state, {\n type: knownCurrentState ? \"heldLoaded\" : \"heldMissing\",\n });\n return knownCurrentState;\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n held: HeldHeadCell,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPage | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n const knownCurrentState = await loadHeldHead(input, held);\n for await (const result of input.historyReader.getProjectionPolicyHistoryPages(\n input.source,\n {\n afterVersion: progress.afterVersion,\n knownCurrentState,\n signal: input.signal,\n },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\n/** The last page's current state must extend the same verified history. */\nasync function verifyLastPageCurrent(\n history: ReturnType<typeof finishPublicProgress>,\n proof: PrincipalPolicyHistoryReferenceProof,\n lastPage: Awaited<ReturnType<typeof readPublicPages>>[\"lastPage\"],\n): Promise<void> {\n if (!lastPage) return;\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n}\n\n// A signed cached candidate need not belong to this requested chain. Only\n// reused progress permits one replay; a fresh disconnected chain fails.\nfunction replaysReusedProgress(\n mayReplay: boolean,\n initial: { readonly afterVersion: number },\n): boolean {\n return mayReplay && initial.afterVersion > 0;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n held: HeldHeadCell,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial, held);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n if (replaysReusedProgress(mayReplay, initial))\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n await verifyLastPageCurrent(history, proof, lastPage);\n // The chain now reaches its source head: pin the signers it accepted.\n await publishAuthenticatedSigners(\n history.signers,\n input.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n useHeldState = true,\n): Promise<RecoveredPublicPrincipalHistory> {\n // A replay distrusts local material, so it reads the served head as well.\n const held: HeldHeadCell = {\n state: initialHeldHeadState(useHeldState && allowReuse),\n };\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix, held);\n } catch (error) {\n // A held head copy only saves its download; one the verifier rejects must\n // not block recovery, so read the served copy once instead.\n if (\n held.state.status === \"heldSent\" &&\n error instanceof KeyingVerificationError\n )\n return recover(input, allowReuse, rejectedPrefix, false);\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix, {\n state: initialHeldHeadState(false),\n });\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
1
+ {"version":3,"file":"recoverPublicPrincipalHistory.js","sourceRoot":"","sources":["recoverPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EAEvB,4BAA4B,EAC5B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,6BAA6B,GAG9B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AACjH,OAAO,EAAE,2BAA2B,EAAE,MAAM,+DAA+D,CAAC;AAC5G,OAAO,EAAE,6BAA6B,EAAE,MAAM,qDAAqD,CAAC;AACpG,OAAO,EAAE,+BAA+B,EAAE,MAAM,kDAAkD,CAAC;AACnG,OAAO,EAEL,oBAAoB,EACpB,uBAAuB,GACxB,MAAM,wBAAwB,CAAC;AAChC,OAAO,EAAE,sCAAsC,EAAE,MAAM,mCAAmC,CAAC;AAC3F,OAAO,EACL,gCAAgC,EAChC,6CAA6C,GAC9C,MAAM,8BAA8B,CAAC;AACtC,O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AC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n type PrincipalPolicyHistoryReferenceProof,\n serializeKeyingCanonicalJson,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicySnapshotPage,\n type PrincipalPolicySnapshotPage,\n type PrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryPrefix } from \"../../../data/persistence/principalHistory/principalHistoryPrefixPersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { publishAuthenticatedSigners } from \"../../../data/principalContracts/principalIdentityCommitments\";\nimport { ownPrincipalHistoryProtection } from \"../../../data/principals/principalHistoryProtection\";\nimport { PrincipalPolicyHistoryReadError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport {\n type HeldHeadState,\n initialHeldHeadState,\n transitionHeldHeadState,\n} from \"./heldHeadStateMachine\";\nimport { PublicHistoryAuthorityUnavailableError } from \"./publicPrincipalHistoryAuthority\";\nimport {\n appendPublicPrincipalHistoryPage,\n PublicPrincipalHistoryPrefixDisconnectedError,\n} from \"./publicPrincipalHistoryPage\";\nimport {\n publishPublicPrincipalHistoryPrefix,\n restorePublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryProgress\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n RecoveredPublicPrincipalHistory,\n} from \"./publicPrincipalHistoryTypes\";\n\n/** The attempt's held-head machine; written only through its transition. */\ninterface HeldHeadCell {\n state: HeldHeadState;\n}\n\nfunction assertPage(\n input: PublicPrincipalHistoryOptions,\n page: PrincipalPolicySnapshotPage,\n after: number,\n): void {\n if (\n !isPrincipalPolicySnapshotPage(page) ||\n !principalHeadMatchesReference(page.currentState, input.source.head) ||\n page.historyPage.afterVersion !== after\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history page does not match its requested head and cursor\",\n );\n const through = after + page.previousStates.length;\n if (\n page.previousStates.some(\n ({ state }, index) => state.version !== after + index + 1,\n ) ||\n through >= input.source.head.version ||\n (page.historyPage.nextAfterVersion === null\n ? through !== input.source.head.version - 1\n : through <= after || page.historyPage.nextAfterVersion !== through)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public history page has a gap or invalid continuation\",\n );\n}\n\n/**\n * A held copy of the head replaces only its download; the final page appends\n * and checks it exactly as a served state.\n */\nasync function loadHeldHead(\n input: PublicPrincipalHistoryOptions,\n held: HeldHeadCell,\n): Promise<PrincipalStateResponse | undefined> {\n const knownCurrentState =\n held.state.status === \"eligible\"\n ? ((await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadHeldPrincipalState(input.source.head)) ?? undefined)\n : undefined;\n held.state = transitionHeldHeadState(held.state, {\n type: knownCurrentState ? \"heldLoaded\" : \"heldMissing\",\n });\n return knownCurrentState;\n}\n\nasync function readPublicPages(\n input: PublicPrincipalHistoryOptions,\n initial: PublicPrincipalHistoryProgress,\n held: HeldHeadCell,\n) {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n let progress = initial;\n let lastPage: PrincipalPolicySnapshotPage | undefined;\n // Completed progress already verified every signed entry through the cited\n // head; a read pinned to that head could only repeat it or refuse.\n if (!input.offline && !progress.completedHead) {\n const knownCurrentState = await loadHeldHead(input, held);\n for await (const result of input.historyReader.getProjectionPolicyHistoryPages(\n input.source,\n {\n afterVersion: progress.afterVersion,\n knownCurrentState,\n signal: input.signal,\n },\n )) {\n assertProjectionVerificationCurrent(current);\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n const page = result.data;\n assertPage(input, page, progress.afterVersion);\n if (progress.completedHead)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Completed public history returned additional entries\",\n );\n progress = await appendPublicPrincipalHistoryPage(input, progress, page);\n lastPage = page;\n }\n if (lastPage?.historyPage.nextAfterVersion !== null)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history transport did not complete\",\n );\n }\n return { progress, lastPage };\n}\n\nfunction finishPublicProgress(progress: PublicPrincipalHistoryProgress) {\n if (!progress.completedHead)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Completed public history is unavailable\",\n );\n const finished = progress.verifier.finish(progress.completedHead);\n if (!finished.ok) throw finished.error;\n return finished.value;\n}\n\n/** The last page's current state must extend the same verified history. */\nasync function verifyLastPageCurrent(\n history: ReturnType<typeof finishPublicProgress>,\n proof: PrincipalPolicyHistoryReferenceProof,\n lastPage: Awaited<ReturnType<typeof readPublicPages>>[\"lastPage\"],\n): Promise<void> {\n if (!lastPage) return;\n const currentProof = {\n ...proof,\n entry: {\n state: lastPage.currentState,\n projection: lastPage.currentProjection,\n grants: lastPage.currentGrants,\n },\n };\n const checked = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [currentProof],\n });\n if (!checked.ok) throw checked.error;\n}\n\n// A signed cached candidate need not belong to this requested chain. Only\n// reused progress permits one replay; a fresh disconnected chain fails.\nfunction replaysReusedProgress(\n mayReplay: boolean,\n initial: { readonly afterVersion: number },\n): boolean {\n return mayReplay && initial.afterVersion > 0;\n}\n\nasync function recoverAttempt(\n input: PublicPrincipalHistoryOptions,\n allowReuse: boolean,\n rejectedPrefix: PrincipalHistoryPrefix | null,\n held: HeldHeadCell,\n): Promise<RecoveredPublicPrincipalHistory> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const mayReplay = allowReuse && !input.offline;\n const initial = await restorePublicPrincipalHistoryProgress(\n input,\n allowReuse,\n );\n let pages: Awaited<ReturnType<typeof readPublicPages>>;\n try {\n pages = await readPublicPages(input, initial, held);\n } catch (error) {\n if (!(error instanceof PublicPrincipalHistoryPrefixDisconnectedError))\n throw error;\n if (replaysReusedProgress(mayReplay, initial))\n return recover(input, false, initial.cachedPrefix);\n throw error.verificationError;\n }\n const { progress, lastPage } = pages;\n const history = finishPublicProgress(progress);\n let proof: PrincipalPolicyHistoryReferenceProof;\n try {\n proof = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId: progress.scopeId,\n history,\n version: input.source.head.version,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history,\n references: [proof],\n });\n if (!selected.ok) throw selected.error;\n } catch (error) {\n if (error instanceof KeyingVerificationError && mayReplay)\n return recover(input, false, initial.cachedPrefix);\n throw error;\n }\n // Public prefixes memoize signatures; they are not admitted trust pins. A\n // rejected projection may have left a valid but unrelated signed candidate.\n // Rebuild the requested chain once online; callers still check durable pins\n // and object authority before accepting it. Never reuse a mismatch offline.\n if (!principalHeadMatchesReference(proof.entry.state, input.source.head)) {\n if (mayReplay) return recover(input, false, initial.cachedPrefix);\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history source differs from the verified prefix\",\n );\n }\n await verifyLastPageCurrent(history, proof, lastPage);\n // The chain now reaches its source head: pin the signers it accepted.\n await publishAuthenticatedSigners(\n history.signers,\n input.resolveTrustedUserIdentity,\n () => assertProjectionVerificationCurrent(current),\n );\n assertProjectionVerificationCurrent(current);\n if (!input.offline)\n await publishPublicPrincipalHistoryPrefix(\n input,\n progress,\n history,\n rejectedPrefix,\n );\n assertProjectionVerificationCurrent(current);\n return { scopeId: progress.scopeId, history };\n}\n\nasync function recover(\n input: PublicPrincipalHistoryOptions,\n allowReuse = true,\n rejectedPrefix: PrincipalHistoryPrefix | null = null,\n useHeldState = true,\n): Promise<RecoveredPublicPrincipalHistory> {\n // A replay distrusts local material, so it reads the served head as well.\n const held: HeldHeadCell = {\n state: initialHeldHeadState(useHeldState && allowReuse),\n };\n try {\n return await recoverAttempt(input, allowReuse, rejectedPrefix, held);\n } catch (error) {\n // A held head copy only saves its download; one the verifier rejects must\n // not block recovery, so read the served copy once instead.\n if (\n held.state.status === \"heldSent\" &&\n error instanceof KeyingVerificationError\n )\n return recover(input, allowReuse, rejectedPrefix, false);\n if (!(error instanceof PublicHistoryAuthorityUnavailableError)) throw error;\n if (allowReuse && !input.offline)\n return recoverAttempt(input, false, error.rejectedPrefix, {\n state: initialHeldHeadState(false),\n });\n throw error.verificationError;\n }\n}\n\n/** Private-key-backed public history recovery; never admits a current policy pin. */\nexport async function recoverPublicPrincipalHistory(\n options: PublicPrincipalHistoryOptions,\n): Promise<RecoveredPublicPrincipalHistory> {\n if (\n !options.organizationId ||\n (options.historicalProof !== undefined &&\n typeof options.historicalProof !== \"boolean\") ||\n (options.offline !== undefined && typeof options.offline !== \"boolean\") ||\n (options.strictAdmins !== undefined &&\n typeof options.strictAdmins !== \"boolean\") ||\n (options.strictAdmins &&\n (options.source.head.principalType !== \"group\" ||\n options.loadExternalAuthority))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Invalid public history verification scope\",\n );\n if (\n options.source.head.principalType === \"organization\" &&\n options.source.head.principalId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public organization history is outside its scope\",\n );\n // Validate the caller's pinned head before any cache or transport access.\n createPrincipalPolicyHistoryVerifier({\n principalType: options.source.head.principalType,\n principalId: options.source.head.principalId,\n retainedReferences: [options.source.head],\n });\n const protection = ownPrincipalHistoryProtection(options.protection);\n protection.context = serializeKeyingCanonicalJson([\n \"tearleads.sdk.public-principal-history.v2\",\n protection.context,\n options.strictAdmins === true,\n options.authorityGroupId ?? null,\n ]);\n const input = {\n ...options,\n source: structuredClone(options.source),\n protection,\n };\n try {\n return await recover(input, options.replay !== true);\n } finally {\n protection.localKey.fill(0);\n }\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { KeyingVerificationError, PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT, selectPrincipalPolicyAuthorization, verifyPrincipalPolicyCheckpoint, verifyPrincipalPolicyHistoryReferences, } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.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 { PrincipalHistoryEvidenceUnavailableError } from "../historyRecovery/principalHistoryRecoveryReferences.js";
6
6
  async function selectBatch(input, versions, checkpointReference) {
7
7
  assertProjectionVerificationCurrent(input.stillCurrent);
@@ -1 +1 @@
1
- {"version":3,"file":"selectPublicPrincipalHistory.js","sourceRoot":"","sources":["selectPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAIlC,kCAAkC,EAElC,+BAA+B,EAC/B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AAEzG,OAAO,EAAE,wCAAwC,EAAE,MAAM,uDAAuD,CAAC;AAajH,KAAK,UAAU,WAAW,CACxB,KAAkC,EAClC,QAA2B,EAC3B,mBAAqE;IAErE,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,MAAM,GAAG,MAAM,IAAI,0BAA0B,CACjD,KAAK,CAAC,OAAO,CACd,CAAC,8BAA8B,CAAC;QAC/B,GAAG,KAAK,CAAC,SAAS;QAClB,QAAQ;KACT,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,QAAQ,GAAG,MAAM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Content":["import {\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryReferenceProof,\n type ReferencedPrincipalHead,\n selectPrincipalPolicyAuthorization,\n type VerifiedPrincipalPolicySelection,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { PrincipalHistoryEvidenceUnavailableError } from \"../historyRecovery/principalHistoryRecoveryReferences\";\nimport type { RecoveredPublicPrincipalHistory } from \"./publicPrincipalHistoryTypes\";\n\ninterface PublicHistorySelectionInput {\n readonly execSql: ExecSql;\n readonly recovered: RecoveredPublicPrincipalHistory;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly checkpoint: PrincipalPolicyCheckpoint | null;\n readonly deferCheckpointCheck?: boolean | undefined;\n readonly includeGenesis?: boolean;\n readonly stillCurrent: () => boolean;\n}\n\nasync function selectBatch(\n input: PublicHistorySelectionInput,\n versions: readonly number[],\n checkpointReference: PrincipalPolicyHistoryReferenceProof | undefined,\n) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const proofs = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReferences({\n ...input.recovered,\n versions,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: input.recovered.history,\n references: proofs,\n checkpointReference,\n });\n if (!selected.ok) throw selected.error;\n return selected.value;\n}\n\nasync function loadCheckpointProof(\n input: PublicHistorySelectionInput,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyHistoryReferenceProof | undefined> {\n let checkpointReference: PrincipalPolicyHistoryReferenceProof | undefined;\n try {\n if (checkpoint)\n checkpointReference = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n ...input.recovered,\n version: checkpoint.version,\n });\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n }\n return checkpointReference;\n}\n\nfunction checkSelectedReferences(\n input: PublicHistorySelectionInput,\n references: readonly ReferencedPrincipalHead[],\n batch: readonly number[],\n selected: Awaited<ReturnType<typeof selectBatch>>,\n checkpoint: PrincipalPolicyCheckpoint | null,\n) {\n // Authenticate the disposable proof before comparing caller citations or pins.\n for (const reference of references.filter(({ version }) =>\n batch.includes(version),\n ))\n if (\n !selected.retainedEntries.some(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history citation differs from its verified entry\",\n );\n if (!input.deferCheckpointCheck)\n verifyPrincipalPolicyCheckpoint({\n chain: selected.retainedEntries.map((entry) => ({\n ...entry,\n projection: [...entry.projection],\n grants: [...entry.grants],\n })),\n currentState: selected.currentEntry.state,\n localCheckpoint: checkpoint,\n });\n}\n\n/** Select bounded proof batches without admitting or advancing durable pins. */\nexport async function selectPublicPrincipalHistory(\n input: PublicHistorySelectionInput,\n): Promise<VerifiedPrincipalPolicySelection[]> {\n const references = structuredClone(input.references);\n const checkpoint = input.checkpoint && { ...input.checkpoint };\n const head = input.recovered.history.currentEntry.state;\n if (\n !input.deferCheckpointCheck &&\n checkpoint &&\n checkpoint.version > head.version\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history cannot connect to the newer durable checkpoint\",\n );\n if (\n references.some(\n (reference) =>\n reference.principalType !== head.principalType ||\n reference.principalId !== head.principalId ||\n reference.version > head.version,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history reference is outside the verified prefix\",\n );\n const versions = [\n ...new Set([\n ...(input.includeGenesis ? [1] : []),\n ...references.map(({ version }) => version),\n head.version,\n ]),\n ];\n const policies: VerifiedPrincipalPolicySelection[] = [];\n const checkpointReference = await loadCheckpointProof(\n input,\n checkpoint && checkpoint.version <= head.version ? checkpoint : null,\n );\n for (\n let offset = 0;\n offset < versions.length;\n offset += PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT\n ) {\n const batch = versions.slice(\n offset,\n offset + PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n );\n const selected = await selectBatch(input, batch, checkpointReference).catch(\n (error: unknown) => {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n },\n );\n checkSelectedReferences(input, references, batch, selected, checkpoint);\n const policy = await selectPrincipalPolicyAuthorization(selected);\n if (!policy.ok) throw policy.error;\n policies.push(policy.value);\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n}\n"]}
1
+ {"version":3,"file":"selectPublicPrincipalHistory.js","sourceRoot":"","sources":["selectPublicPrincipalHistory.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAIlC,kCAAkC,EAElC,+BAA+B,EAC/B,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AAEjH,OAAO,EAAE,wCAAwC,EAAE,MAAM,uDAAuD,CAAC;AAajH,KAAK,UAAU,WAAW,CACxB,KAAkC,EAClC,QAA2B,EAC3B,mBAAqE;IAErE,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,MAAM,GAAG,MAAM,IAAI,0BAA0B,CACjD,KAAK,CAAC,OAAO,CACd,CAAC,8BAA8B,CAAC;QAC/B,GAAG,KAAK,CAAC,SAAS;QAClB,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AC9B,CAAC;IACD,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n type PrincipalPolicyCheckpoint,\n type PrincipalPolicyHistoryReferenceProof,\n type ReferencedPrincipalHead,\n selectPrincipalPolicyAuthorization,\n type VerifiedPrincipalPolicySelection,\n verifyPrincipalPolicyCheckpoint,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport { PrincipalHistoryEvidenceUnavailableError } from \"../historyRecovery/principalHistoryRecoveryReferences\";\nimport type { RecoveredPublicPrincipalHistory } from \"./publicPrincipalHistoryTypes\";\n\ninterface PublicHistorySelectionInput {\n readonly execSql: ExecSql;\n readonly recovered: RecoveredPublicPrincipalHistory;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly checkpoint: PrincipalPolicyCheckpoint | null;\n readonly deferCheckpointCheck?: boolean | undefined;\n readonly includeGenesis?: boolean;\n readonly stillCurrent: () => boolean;\n}\n\nasync function selectBatch(\n input: PublicHistorySelectionInput,\n versions: readonly number[],\n checkpointReference: PrincipalPolicyHistoryReferenceProof | undefined,\n) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const proofs = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReferences({\n ...input.recovered,\n versions,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: input.recovered.history,\n references: proofs,\n checkpointReference,\n });\n if (!selected.ok) throw selected.error;\n return selected.value;\n}\n\nasync function loadCheckpointProof(\n input: PublicHistorySelectionInput,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): Promise<PrincipalPolicyHistoryReferenceProof | undefined> {\n let checkpointReference: PrincipalPolicyHistoryReferenceProof | undefined;\n try {\n if (checkpoint)\n checkpointReference = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n ...input.recovered,\n version: checkpoint.version,\n });\n } catch (error) {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n }\n return checkpointReference;\n}\n\nfunction checkSelectedReferences(\n input: PublicHistorySelectionInput,\n references: readonly ReferencedPrincipalHead[],\n batch: readonly number[],\n selected: Awaited<ReturnType<typeof selectBatch>>,\n checkpoint: PrincipalPolicyCheckpoint | null,\n) {\n // Authenticate the disposable proof before comparing caller citations or pins.\n for (const reference of references.filter(({ version }) =>\n batch.includes(version),\n ))\n if (\n !selected.retainedEntries.some(({ state }) =>\n principalHeadMatchesReference(state, reference),\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history citation differs from its verified entry\",\n );\n if (!input.deferCheckpointCheck)\n verifyPrincipalPolicyCheckpoint({\n chain: selected.retainedEntries.map((entry) => ({\n ...entry,\n projection: [...entry.projection],\n grants: [...entry.grants],\n })),\n currentState: selected.currentEntry.state,\n localCheckpoint: checkpoint,\n });\n}\n\n/** Select bounded proof batches without admitting or advancing durable pins. */\nexport async function selectPublicPrincipalHistory(\n input: PublicHistorySelectionInput,\n): Promise<VerifiedPrincipalPolicySelection[]> {\n const references = structuredClone(input.references);\n const checkpoint = input.checkpoint && { ...input.checkpoint };\n const head = input.recovered.history.currentEntry.state;\n if (\n !input.deferCheckpointCheck &&\n checkpoint &&\n checkpoint.version > head.version\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Public history cannot connect to the newer durable checkpoint\",\n );\n if (\n references.some(\n (reference) =>\n reference.principalType !== head.principalType ||\n reference.principalId !== head.principalId ||\n reference.version > head.version,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history reference is outside the verified prefix\",\n );\n const versions = [\n ...new Set([\n ...(input.includeGenesis ? [1] : []),\n ...references.map(({ version }) => version),\n head.version,\n ]),\n ];\n const policies: VerifiedPrincipalPolicySelection[] = [];\n const checkpointReference = await loadCheckpointProof(\n input,\n checkpoint && checkpoint.version <= head.version ? checkpoint : null,\n );\n for (\n let offset = 0;\n offset < versions.length;\n offset += PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT\n ) {\n const batch = versions.slice(\n offset,\n offset + PRINCIPAL_HISTORY_PAGE_ENTRY_LIMIT,\n );\n const selected = await selectBatch(input, batch, checkpointReference).catch(\n (error: unknown) => {\n if (error instanceof KeyingVerificationError)\n throw new PrincipalHistoryEvidenceUnavailableError(error);\n throw error;\n },\n );\n checkSelectedReferences(input, references, batch, selected, checkpoint);\n const policy = await selectPrincipalPolicyAuthorization(selected);\n if (!policy.ok) throw policy.error;\n policies.push(policy.value);\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n return policies;\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { type ReferencedPrincipalHead } from "../../../internal/crypto/index.js";
2
- import { type OrganizationAuthorityDescriptor } from "../../../data/principals/organizationAuthorityDescriptor.js";
2
+ import { type OrganizationAuthorityDescriptor } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
3
3
  import { type RecoveredPrincipalPolicyHistory, type RecoverPrincipalPolicyHistoryOptions } from "../historyRecovery/principalHistoryRecoveryTypes.js";
4
4
  export type PrincipalRecoveryContext = Omit<RecoverPrincipalPolicyHistoryOptions, "expectedHead" | "retainedReferences" | "historyVerification" | "loadExternalAuthority">;
5
5
  export interface RecoveredPolicyDirectory extends RecoveredPrincipalPolicyHistory {
@@ -2,7 +2,7 @@ import { KeyingVerificationError, verifyPrincipalPolicyHistoryReferences, } from
2
2
  import { isPrincipalPolicyPageResponse, isPrincipalPolicyUnchangedResponse, } from "../../../internal/validators/response/index.js";
3
3
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
4
4
  import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
5
- import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principals/organizationAuthorityDescriptor.js";
5
+ import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
6
6
  import { principalHistoryEvidenceScopeId } from "../../../data/principals/principalHistoryPrefixProtection.js";
7
7
  import { directoryHistoryProtection } from "../../../data/principals/principalHistoryScopeProtection.js";
8
8
  import { loadVerifiedPrincipalHistoryPrefix } from "../historyRecovery/principalHistoryRecoveryPrefix.js";
@@ -1 +1 @@
1
- {"version":3,"file":"principalRecoveryDirectory.js","sourceRoot":"","sources":["principalRecoveryDirectory.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EAEvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,6BAA6B,EAC7B,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,+BAA+B,EAAE,MAAM,2DAA2D,CAAC;AAC5G,OAAO,EAAE,0BAA0B,EAAE,MAAM,0DAA0D,CAAC;AACtG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EACL,+BAA+B,GAGhC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,2BAA2B,EAAE,MAAM,kCAAkC,CAAC;AAe/E,MAAM,OAAO,kCAAmC,SAAQ,KAAK;CA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from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicyPageResponse,\n isPrincipalPolicyUnchangedResponse,\n type PrincipalPolicyPageResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport { directoryHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { loadVerifiedPrincipalHistoryPrefix } from \"../historyRecovery/principalHistoryRecoveryPrefix\";\nimport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport { recoverPrincipalPolicyHistory } from \"../historyRecovery/recoverPrincipalPolicyHistory\";\nimport { reusePrincipalDiscoveryPage } from \"./principalRecoveryDiscoveryPage\";\n\nexport type PrincipalRecoveryContext = Omit<\n RecoverPrincipalPolicyHistoryOptions,\n | \"expectedHead\"\n | \"retainedReferences\"\n | \"historyVerification\"\n | \"loadExternalAuthority\"\n>;\n\nexport interface RecoveredPolicyDirectory\n extends RecoveredPrincipalPolicyHistory {\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport class PrincipalRecoveryDirectoryAdvanced extends Error {}\n\nfunction exactHead(state: ReferencedPrincipalHead): ReferencedPrincipalHead {\n return {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\ninterface DiscoveredDirectoryHead {\n readonly head: ReferencedPrincipalHead;\n readonly genesis: ReferencedPrincipalHead;\n readonly historyReader: PrincipalRecoveryContext[\"historyReader\"];\n}\n\nfunction assertDiscoveryCurrent(input: PrincipalRecoveryContext): void {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n}\n\n/**\n * The directory head and genesis this device has completely authenticated,\n * from its protected verified prefix, or null when it holds none.\n */\nasync function loadHeldDirectoryHead(\n input: PrincipalRecoveryContext,\n): Promise<Omit<DiscoveredDirectoryHead, \"historyReader\"> | null> {\n const principal = {\n principalType: \"organization\" as const,\n principalId: input.organizationId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: principal,\n protection: input.protection,\n });\n const prefix = await loadVerifiedPrincipalHistoryPrefix(\n input,\n principal,\n scopeId,\n );\n if (!prefix) return null;\n const history = prefix.verifier.finish(prefix.head);\n if (!history.ok) throw history.error;\n const genesis = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId,\n history: history.value,\n version: 1,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: history.value,\n references: [genesis],\n });\n if (!selected.ok) throw selected.error;\n return { head: exactHead(prefix.head), genesis: genesis.reference };\n}\n\n/** Disposable local evidence never refuses an online discovery; it reads fully. */\nasync function loadHeldDirectoryHeadOnline(input: PrincipalRecoveryContext) {\n try {\n return await loadHeldDirectoryHead(input);\n } catch {\n assertDiscoveryCurrent(input);\n return null;\n }\n}\n\nfunction discoveredPage(\n input: PrincipalRecoveryContext,\n result: RequestSuccess<PrincipalPolicyPageResponse>,\n): DiscoveredDirectoryHead {\n const state = result.data.currentState;\n const first = result.data.previousStates[0]?.state ?? state;\n if (\n first.version !== 1 ||\n first.principalType !== \"organization\" ||\n first.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory discovery requires genesis\",\n );\n return {\n historyReader: reusePrincipalDiscoveryPage(input.historyReader, result),\n genesis: exactHead(first),\n // The requested identity, never the page's: discovery picks only a pin.\n head: {\n principalType: \"organization\",\n principalId: input.organizationId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n },\n };\n}\n\n/**\n * Ask whether the held head is still live. An `unchanged` reply naming exactly\n * that head reuses it; recovery then authenticates the held artifacts again\n * and reloads the checkpoint. Any other reply that is not a page leaves the\n * caller to read the first page unconditionally.\n */\nasync function discoverConditionally(\n input: PrincipalRecoveryContext,\n discover: NonNullable<\n PrincipalRecoveryContext[\"historyReader\"][\"getPrincipalPolicyDiscovery\"]\n >,\n): Promise<DiscoveredDirectoryHead | null> {\n const held = await loadHeldDirectoryHeadOnline(input);\n assertDiscoveryCurrent(input);\n const result = await discover(\"organization\", input.organizationId, {\n signal: input.signal,\n ifHead: held?.head,\n });\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertDiscoveryCurrent(input);\n const reply = result.data;\n if (isPrincipalPolicyUnchangedResponse(reply))\n return held && principalHeadMatchesReference(reply.head, held.head)\n ? { ...held, historyReader: input.historyReader }\n : null;\n // Anything but the strict bare head must be a page; otherwise read again.\n return isPrincipalPolicyPageResponse(reply)\n ? discoveredPage(input, { ok: true, data: reply })\n : null;\n}\n\n/** An unverified discovery read chooses a pin; recovery must authenticate it. */\nasync function discoverDirectoryHead(\n input: PrincipalRecoveryContext,\n): Promise<DiscoveredDirectoryHead> {\n assertDiscoveryCurrent(input);\n if (input.offline) {\n const held = await loadHeldDirectoryHead(input);\n if (!held)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory is unavailable offline\",\n );\n return { ...held, historyReader: input.historyReader };\n }\n const discover = input.historyReader.getPrincipalPolicyDiscovery;\n const conditional = discover\n ? await discoverConditionally(input, discover)\n : null;\n if (conditional) return conditional;\n for await (const result of input.historyReader.getPrincipalPolicyPages(\n \"organization\",\n input.organizationId,\n { signal: input.signal },\n )) {\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertDiscoveryCurrent(input);\n return discoveredPage(input, result);\n }\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory head is unavailable\",\n );\n}\n\nexport async function recoverPolicyDirectory(\n input: PrincipalRecoveryContext,\n references: readonly ReferencedPrincipalHead[],\n selected?: RecoveredPolicyDirectory,\n): Promise<RecoveredPolicyDirectory> {\n const scoped = {\n ...input,\n protection: directoryHistoryProtection(input.protection),\n };\n const {\n head: expectedHead,\n genesis,\n historyReader,\n } = selected\n ? {\n head: exactHead(selected.policy.state),\n genesis: selected.policy.retainedHistory[0]?.state,\n historyReader: input.historyReader,\n }\n : await discoverDirectoryHead(scoped);\n if (genesis?.version !== 1)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory recovery requires verified genesis\",\n );\n if (references.some((reference) => reference.version > expectedHead.version))\n throw new PrincipalRecoveryDirectoryAdvanced();\n const recovered = await recoverPrincipalPolicyHistory({\n ...scoped,\n historyReader,\n expectedHead,\n retainedReferences: references.some((reference) => reference.version === 1)\n ? references\n : [exactHead(genesis), ...references],\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n recovered.current.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 { ...recovered, descriptor };\n}\n"]}
1
+ {"version":3,"file":"principalRecoveryDirectory.js","sourceRoot":"","sources":["principalRecoveryDirectory.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EAEvB,sCAAsC,GACvC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,6BAA6B,EAC7B,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,kD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,CAAC,EAAE,GAAG,UAAU,CAAC;KACxC,CAAC,CAAC;IACH,IAAI,UAA2C,CAAC;IAChD,IAAI,CAAC;QACH,UAAU,GAAG,oCAAoC,CAC/C,SAAS,CAAC,OAAO,CAAC,cAAc,CAAC,UAAU,CAC5C,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,2CAA2C,CAC5C,CAAC;IACJ,CAAC;IACD,IAAI,UAAU,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QACpD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,6CAA6C,CAC9C,CAAC;IACJ,OAAO,EAAE,GAAG,SAAS,EAAE,UAAU,EAAE,CAAC;AACtC,CAAC","sourcesContent":["import type { RequestSuccess } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n verifyPrincipalPolicyHistoryReferences,\n} from \"@tearleads/crypto\";\nimport {\n isPrincipalPolicyPageResponse,\n isPrincipalPolicyUnchangedResponse,\n type PrincipalPolicyPageResponse,\n} from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../../data/principals/principalHistoryPrefixProtection\";\nimport { directoryHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { loadVerifiedPrincipalHistoryPrefix } from \"../historyRecovery/principalHistoryRecoveryPrefix\";\nimport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport { recoverPrincipalPolicyHistory } from \"../historyRecovery/recoverPrincipalPolicyHistory\";\nimport { reusePrincipalDiscoveryPage } from \"./principalRecoveryDiscoveryPage\";\n\nexport type PrincipalRecoveryContext = Omit<\n RecoverPrincipalPolicyHistoryOptions,\n | \"expectedHead\"\n | \"retainedReferences\"\n | \"historyVerification\"\n | \"loadExternalAuthority\"\n>;\n\nexport interface RecoveredPolicyDirectory\n extends RecoveredPrincipalPolicyHistory {\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport class PrincipalRecoveryDirectoryAdvanced extends Error {}\n\nfunction exactHead(state: ReferencedPrincipalHead): ReferencedPrincipalHead {\n return {\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n };\n}\n\ninterface DiscoveredDirectoryHead {\n readonly head: ReferencedPrincipalHead;\n readonly genesis: ReferencedPrincipalHead;\n readonly historyReader: PrincipalRecoveryContext[\"historyReader\"];\n}\n\nfunction assertDiscoveryCurrent(input: PrincipalRecoveryContext): void {\n assertProjectionVerificationCurrent(\n () => !input.signal?.aborted && input.stillCurrent(),\n );\n}\n\n/**\n * The directory head and genesis this device has completely authenticated,\n * from its protected verified prefix, or null when it holds none.\n */\nasync function loadHeldDirectoryHead(\n input: PrincipalRecoveryContext,\n): Promise<Omit<DiscoveredDirectoryHead, \"historyReader\"> | null> {\n const principal = {\n principalType: \"organization\" as const,\n principalId: input.organizationId,\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: principal,\n protection: input.protection,\n });\n const prefix = await loadVerifiedPrincipalHistoryPrefix(\n input,\n principal,\n scopeId,\n );\n if (!prefix) return null;\n const history = prefix.verifier.finish(prefix.head);\n if (!history.ok) throw history.error;\n const genesis = await new PrincipalHistoryRepository(\n input.execSql,\n ).loadPrincipalHistoryReference({\n scopeId,\n history: history.value,\n version: 1,\n });\n const selected = await verifyPrincipalPolicyHistoryReferences({\n history: history.value,\n references: [genesis],\n });\n if (!selected.ok) throw selected.error;\n return { head: exactHead(prefix.head), genesis: genesis.reference };\n}\n\n/** Disposable local evidence never refuses an online discovery; it reads fully. */\nasync function loadHeldDirectoryHeadOnline(input: PrincipalRecoveryContext) {\n try {\n return await loadHeldDirectoryHead(input);\n } catch {\n assertDiscoveryCurrent(input);\n return null;\n }\n}\n\nfunction discoveredPage(\n input: PrincipalRecoveryContext,\n result: RequestSuccess<PrincipalPolicyPageResponse>,\n): DiscoveredDirectoryHead {\n const state = result.data.currentState;\n const first = result.data.previousStates[0]?.state ?? state;\n if (\n first.version !== 1 ||\n first.principalType !== \"organization\" ||\n first.principalId !== input.organizationId\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory discovery requires genesis\",\n );\n return {\n historyReader: reusePrincipalDiscoveryPage(input.historyReader, result),\n genesis: exactHead(first),\n // The requested identity, never the page's: discovery picks only a pin.\n head: {\n principalType: \"organization\",\n principalId: input.organizationId,\n version: state.version,\n stateHash: state.stateHash,\n keyEpoch: state.keyEpoch,\n keyFingerprint: state.keyFingerprint,\n },\n };\n}\n\n/**\n * Ask whether the held head is still live. An `unchanged` reply naming exactly\n * that head reuses it; recovery then authenticates the held artifacts again\n * and reloads the checkpoint. Any other reply that is not a page leaves the\n * caller to read the first page unconditionally.\n */\nasync function discoverConditionally(\n input: PrincipalRecoveryContext,\n discover: NonNullable<\n PrincipalRecoveryContext[\"historyReader\"][\"getPrincipalPolicyDiscovery\"]\n >,\n): Promise<DiscoveredDirectoryHead | null> {\n const held = await loadHeldDirectoryHeadOnline(input);\n assertDiscoveryCurrent(input);\n const result = await discover(\"organization\", input.organizationId, {\n signal: input.signal,\n ifHead: held?.head,\n });\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertDiscoveryCurrent(input);\n const reply = result.data;\n if (isPrincipalPolicyUnchangedResponse(reply))\n return held && principalHeadMatchesReference(reply.head, held.head)\n ? { ...held, historyReader: input.historyReader }\n : null;\n // Anything but the strict bare head must be a page; otherwise read again.\n return isPrincipalPolicyPageResponse(reply)\n ? discoveredPage(input, { ok: true, data: reply })\n : null;\n}\n\n/** An unverified discovery read chooses a pin; recovery must authenticate it. */\nasync function discoverDirectoryHead(\n input: PrincipalRecoveryContext,\n): Promise<DiscoveredDirectoryHead> {\n assertDiscoveryCurrent(input);\n if (input.offline) {\n const held = await loadHeldDirectoryHead(input);\n if (!held)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory is unavailable offline\",\n );\n return { ...held, historyReader: input.historyReader };\n }\n const discover = input.historyReader.getPrincipalPolicyDiscovery;\n const conditional = discover\n ? await discoverConditionally(input, discover)\n : null;\n if (conditional) return conditional;\n for await (const result of input.historyReader.getPrincipalPolicyPages(\n \"organization\",\n input.organizationId,\n { signal: input.signal },\n )) {\n if (!result.ok) throw new PrincipalPolicyHistoryReadError(result);\n assertDiscoveryCurrent(input);\n return discoveredPage(input, result);\n }\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory head is unavailable\",\n );\n}\n\nexport async function recoverPolicyDirectory(\n input: PrincipalRecoveryContext,\n references: readonly ReferencedPrincipalHead[],\n selected?: RecoveredPolicyDirectory,\n): Promise<RecoveredPolicyDirectory> {\n const scoped = {\n ...input,\n protection: directoryHistoryProtection(input.protection),\n };\n const {\n head: expectedHead,\n genesis,\n historyReader,\n } = selected\n ? {\n head: exactHead(selected.policy.state),\n genesis: selected.policy.retainedHistory[0]?.state,\n historyReader: input.historyReader,\n }\n : await discoverDirectoryHead(scoped);\n if (genesis?.version !== 1)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization directory recovery requires verified genesis\",\n );\n if (references.some((reference) => reference.version > expectedHead.version))\n throw new PrincipalRecoveryDirectoryAdvanced();\n const recovered = await recoverPrincipalPolicyHistory({\n ...scoped,\n historyReader,\n expectedHead,\n retainedReferences: references.some((reference) => reference.version === 1)\n ? references\n : [exactHead(genesis), ...references],\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n recovered.current.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 { ...recovered, descriptor };\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
3
- import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
3
+ import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
4
4
  import { PrincipalHistoryRecoveryRaceError } from "../historyRecovery/principalHistoryRecoveryTypes.js";
5
5
  import { recoverWithPrincipalOutageFallback } from "./principalRecoveryOutage.js";
6
6
  /** Reuse exact current artifacts, or a proved historical page within a newer prefix. */
@@ -1 +1 @@
1
- {"version":3,"file":"principalRecoveryLocalPreference.js","sourceRoot":"","sources":["principalRecoveryLocalPreference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,iCAAiC,EAAE,MAAM,kDAAkD,CAAC;AAKrG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAE/E,wFAAwF;AACxF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,OAA2C,EAC3C,OAAmD,EACnD,kBAA2B,EAC3B,wBAAwB,GAAG,KAAK;IAEhC,IAAI,kBAAkB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QAC3C,IAAI,CAAC;YACH,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC;gBAC1B,GAAG,OAAO;gBACV,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;YACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,wBAAwB;gBACxB,OAAO,CAAC,WAAW;gBACnB,6BAA6B,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC;gBAEpE,OAAO,KAAK,CAAC;QACjB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,CAAC,CAAC,KAAK,YAAY,iCAAiC,CAAC;gBACrD,CAAC,CACC,KAAK,YAAY,uBAAuB;oBACxC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CACpC;gBAED,MAAM,KAAK,CAAC;QAChB,CAAC;IACH,CAAC;IACD,OAAO,kCAAkC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { PrincipalHistoryRecoveryRaceError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport type {\n RecoverScopedPrincipalPolicyHistoryOptions,\n ScopedPrincipalPolicyRecoveryBatch,\n} from \"../historyRecovery/recoverScopedPrincipalPolicyHistory\";\nimport { recoverWithPrincipalOutageFallback } from \"./principalRecoveryOutage\";\n\n/** Reuse exact current artifacts, or a proved historical page within a newer prefix. */\nexport async function recoverWithPrincipalLocalPreference(\n recover: ScopedPrincipalPolicyRecoveryBatch,\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n preferLocalCurrent: boolean,\n allowHistoricalReference = false,\n) {\n if (preferLocalCurrent && !options.offline) {\n try {\n const local = await recover({\n ...options,\n offline: true,\n });\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n allowHistoricalReference ||\n options.historyPage ||\n principalHeadMatchesReference(local.policy.state, options.reference)\n )\n return local;\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n !(error instanceof PrincipalHistoryRecoveryRaceError) &&\n !(\n error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\"\n )\n )\n throw error;\n }\n }\n return recoverWithPrincipalOutageFallback(recover, options);\n}\n"]}
1
+ {"version":3,"file":"principalRecoveryLocalPreference.js","sourceRoot":"","sources":["principalRecoveryLocalPreference.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,6BAA6B,EAAE,MAAM,kEAAkE,CAAC;AACjH,OAAO,EAAE,iCAAiC,EAAE,MAAM,kDAAkD,CAAC;AAKrG,OAAO,EAAE,kCAAkC,EAAE,MAAM,2BAA2B,CAAC;AAE/E,wFAAwF;AACxF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CACvD,OAA2C,EAC3C,OAAmD,EACnD,kBAA2B,EAC3B,wBAAwB,GAAG,KAAK;IAEhC,IAAI,kBAAkB,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC;QAC3C,IAAI,CAAC;YACH,MAAM,KAAK,GAAG,MAAM,OAAO,CAAC;gBAC1B,GAAG,OAAO;gBACV,OAAO,EAAE,IAAI;aACd,CAAC,CAAC;YACH,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,wBAAwB;gBACxB,OAAO,CAAC,WAAW;gBACnB,6BAA6B,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,OAAO,CAAC,SAAS,CAAC;gBAEpE,OAAO,KAAK,CAAC;QACjB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;YAC1D,IACE,CAAC,CAAC,KAAK,YAAY,iCAAiC,CAAC;gBACrD,CAAC,CACC,KAAK,YAAY,uBAAuB;oBACxC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CACpC;gBAED,MAAM,KAAK,CAAC;QAChB,CAAC;IACH,CAAC;IACD,OAAO,kCAAkC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { principalHeadMatchesReference } from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { PrincipalHistoryRecoveryRaceError } from \"../historyRecovery/principalHistoryRecoveryTypes\";\nimport type {\n RecoverScopedPrincipalPolicyHistoryOptions,\n ScopedPrincipalPolicyRecoveryBatch,\n} from \"../historyRecovery/recoverScopedPrincipalPolicyHistory\";\nimport { recoverWithPrincipalOutageFallback } from \"./principalRecoveryOutage\";\n\n/** Reuse exact current artifacts, or a proved historical page within a newer prefix. */\nexport async function recoverWithPrincipalLocalPreference(\n recover: ScopedPrincipalPolicyRecoveryBatch,\n options: RecoverScopedPrincipalPolicyHistoryOptions,\n preferLocalCurrent: boolean,\n allowHistoricalReference = false,\n) {\n if (preferLocalCurrent && !options.offline) {\n try {\n const local = await recover({\n ...options,\n offline: true,\n });\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n allowHistoricalReference ||\n options.historyPage ||\n principalHeadMatchesReference(local.policy.state, options.reference)\n )\n return local;\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (\n !(error instanceof PrincipalHistoryRecoveryRaceError) &&\n !(\n error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\"\n )\n )\n throw error;\n }\n }\n return recoverWithPrincipalOutageFallback(recover, options);\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { KeyingVerificationError, serializeKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
3
- import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
3
+ import { principalHeadMatchesReference } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
4
4
  import { recoverPrincipalPolicyHistory } from "../historyRecovery/recoverPrincipalPolicyHistory.js";
5
5
  import { recoverPolicyDirectory, } from "./principalRecoveryDirectory.js";
6
6
  import { adminsMemoValidity, directoryMemoValidity, } from "./principalRecoveryMemoValidity.js";