@tearleads/client-sdk 0.1.14 → 0.1.16

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 (354) hide show
  1. package/client/Tearleads.d.ts +2 -0
  2. package/client/Tearleads.js +1 -0
  3. package/client/Tearleads.js.map +1 -1
  4. package/client/containerContents.js +2 -1
  5. package/client/containerContents.js.map +1 -1
  6. package/client/index.d.ts +1 -1
  7. package/client/index.js.map +1 -1
  8. package/client/organizations/index.d.ts +4 -42
  9. package/client/organizations/index.js +13 -0
  10. package/client/organizations/index.js.map +1 -1
  11. package/client/organizations/organizationGroupNameHydration.js +8 -1
  12. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  13. package/client/organizations/organizationsTypes.d.ts +47 -0
  14. package/client/organizations/organizationsTypes.js +2 -0
  15. package/client/organizations/organizationsTypes.js.map +1 -0
  16. package/client/organizations/principalMutationRecovery.d.ts +16 -0
  17. package/client/organizations/principalMutationRecovery.js +23 -0
  18. package/client/organizations/principalMutationRecovery.js.map +1 -0
  19. package/client/organizations/principalMutationScope.js +7 -2
  20. package/client/organizations/principalMutationScope.js.map +1 -1
  21. package/client/principalMutationApi.d.ts +24 -0
  22. package/client/principalMutationApi.js +108 -0
  23. package/client/principalMutationApi.js.map +1 -0
  24. package/client/principalMutationDeadline.js +23 -0
  25. package/client/principalMutationDeadline.js.map +1 -0
  26. package/client/workflowRuntime.d.ts +3 -1
  27. package/client/workflowRuntime.js +44 -5
  28. package/client/workflowRuntime.js.map +1 -1
  29. package/data/documents/blob/shared/types.d.ts +4 -0
  30. package/data/documents/blob/shared/types.js.map +1 -1
  31. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js +2 -0
  32. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
  33. package/data/keyingProjectionVerification/checkpointContext.d.ts +2 -1
  34. package/data/keyingProjectionVerification/checkpointContext.js +22 -0
  35. package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
  36. package/data/keyingProjectionVerification/containerDestinationVerification.js +11 -1
  37. package/data/keyingProjectionVerification/containerDestinationVerification.js.map +1 -1
  38. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  39. package/data/keyingProjectionVerification/containerPathVerification.js.map +1 -1
  40. package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +3 -2
  41. package/data/keyingProjectionVerification/containerProjectionVerification.js +10 -11
  42. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
  43. package/data/keyingProjectionVerification/documentManifestPolicies.js.map +1 -1
  44. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  45. package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +2 -3
  46. package/data/keyingProjectionVerification/documentProjectionVerification.js +4 -0
  47. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
  48. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js +14 -12
  49. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js.map +1 -1
  50. package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
  51. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js +33 -6
  52. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
  53. package/data/keyingProjectionVerification/projectionLifetimes.js +13 -0
  54. package/data/keyingProjectionVerification/projectionLifetimes.js.map +1 -0
  55. package/data/keyingProjectionVerification/projectionPolicyEvidence.js +19 -66
  56. package/data/keyingProjectionVerification/projectionPolicyEvidence.js.map +1 -1
  57. package/data/keyingProjectionVerification/types.d.ts +13 -2
  58. package/data/keyingProjectionVerification/types.js +15 -0
  59. package/data/keyingProjectionVerification/types.js.map +1 -1
  60. package/data/persistence/keyingCheckpointAdvancePersistence.js +4 -1
  61. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +1 -1
  62. package/data/persistence/organizationFounderPersistence.js +2 -2
  63. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  64. package/data/persistence/principalAuthorizationCheckpoints.js +29 -0
  65. package/data/persistence/principalAuthorizationCheckpoints.js.map +1 -0
  66. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +27 -0
  67. package/data/persistence/principalCurrentAcknowledgementPersistence.js +109 -0
  68. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -0
  69. package/data/persistence/principalGrantRetirementPersistence.d.ts +3 -3
  70. package/data/persistence/principalGrantRetirementPersistence.js +4 -1
  71. package/data/persistence/principalGrantRetirementPersistence.js.map +1 -1
  72. package/data/persistence/principalHistoryEvidencePersistence.d.ts +30 -0
  73. package/data/persistence/principalHistoryPrefixPersistence.d.ts +24 -0
  74. package/data/persistence/principalHistoryPrefixPersistence.js +6 -2
  75. package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -1
  76. package/data/persistence/principalHistoryStagePersistence.d.ts +21 -0
  77. package/data/persistence/principalKeyEnvelopeCandidates.js +12 -1
  78. package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -1
  79. package/data/persistence/principalMutationJournalPersistence.d.ts +19 -0
  80. package/data/persistence/principalMutationJournalPersistence.js +53 -0
  81. package/data/persistence/principalMutationJournalPersistence.js.map +1 -0
  82. package/data/persistence/verifiedPrincipalPolicyBundle.js +7 -51
  83. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
  84. package/data/persistence/verifiedPrincipalPolicyCurrent.js +56 -0
  85. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -0
  86. package/data/principals/principalHistoryRuntime.js +12 -0
  87. package/data/principals/principalHistoryRuntime.js.map +1 -0
  88. package/data/principals/principalHistoryStageProtection.js +2 -12
  89. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  90. package/data/principals/principalMutationJournal.d.ts +26 -0
  91. package/data/principals/principalMutationJournal.js +90 -0
  92. package/data/principals/principalMutationJournal.js.map +1 -0
  93. package/data/principals/principalMutationJournalRecord.d.ts +8 -0
  94. package/data/principals/principalMutationJournalRecord.js +25 -0
  95. package/data/principals/principalMutationJournalRecord.js.map +1 -0
  96. package/data/principals/principalPolicyEvidence.d.ts +2 -2
  97. package/data/principals/principalPolicyEvidence.js.map +1 -1
  98. package/data/sqlite/principalHistoryEvidenceSchema.d.ts +308 -0
  99. package/data/sqlite/principalHistoryStageSchema.d.ts +119 -0
  100. package/data/sqlite/principalHistoryStageSchema.js +3 -0
  101. package/data/sqlite/principalHistoryStageSchema.js.map +1 -1
  102. package/data/sqlite/principalMutationJournalSchema.d.ts +85 -0
  103. package/data/sqlite/principalMutationJournalSchema.js +13 -0
  104. package/data/sqlite/principalMutationJournalSchema.js.map +1 -0
  105. package/data/sqlite/schema.d.ts +83 -0
  106. package/data/sqlite/schema.js +3 -0
  107. package/data/sqlite/schema.js.map +1 -1
  108. package/index.d.ts +5 -5
  109. package/index.js +2 -2
  110. package/index.js.map +1 -1
  111. package/internal/api-client/ApiCache.d.ts +54 -0
  112. package/internal/api-client/ApiClient.d.ts +255 -309
  113. package/internal/api-client/ApiClient.js +15 -6
  114. package/internal/api-client/ApiClient.js.map +1 -1
  115. package/internal/api-client/index.d.ts +1 -0
  116. package/internal/api-client/index.js.map +1 -1
  117. package/internal/api-client/principalHistoryDeadline.js +20 -0
  118. package/internal/api-client/principalHistoryDeadline.js.map +1 -0
  119. package/internal/api-client/principalHistoryRequest.js +59 -22
  120. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  121. package/internal/api-client/principalHistoryRequestContext.js +18 -5
  122. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  123. package/internal/api-client/principalPolicyRequests.d.ts +799 -0
  124. package/internal/api-client/principalPolicyRequests.js +9 -4
  125. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  126. package/internal/api-client/projectionPolicyHistoryPages.d.ts +9 -0
  127. package/internal/api-client/projectionPolicyHistoryPages.js +88 -0
  128. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -0
  129. package/internal/api-client/writerProjectionRequests.js +26 -0
  130. package/internal/api-client/writerProjectionRequests.js.map +1 -0
  131. package/internal/crypto/index.d.ts +1 -1
  132. package/internal/crypto/index.js +1 -1
  133. package/internal/crypto/index.js.map +1 -1
  134. package/internal/crypto/keying/index.d.ts +2 -0
  135. package/internal/crypto/keying/index.js +2 -0
  136. package/internal/crypto/keying/index.js.map +1 -1
  137. package/internal/crypto/keying/principalPolicyCurrent.d.ts +1 -1
  138. package/internal/crypto/keying/principalPolicyCurrent.js +3 -3
  139. package/internal/crypto/keying/principalPolicyCurrent.js.map +1 -1
  140. package/internal/crypto/keying/principalPolicyCurrentEvidence.js +16 -0
  141. package/internal/crypto/keying/principalPolicyCurrentEvidence.js.map +1 -0
  142. package/internal/crypto/keying/principalPolicyCurrentMutation.d.ts +10 -0
  143. package/internal/crypto/keying/principalPolicyCurrentMutation.js +51 -0
  144. package/internal/crypto/keying/principalPolicyCurrentMutation.js.map +1 -0
  145. package/internal/crypto/keying/principalPolicyCurrentSuccessor.d.ts +10 -0
  146. package/internal/crypto/keying/principalPolicyCurrentSuccessor.js +60 -0
  147. package/internal/crypto/keying/principalPolicyCurrentSuccessor.js.map +1 -0
  148. package/internal/crypto/keying/principalPolicyHistory.js +8 -1
  149. package/internal/crypto/keying/principalPolicyHistory.js.map +1 -1
  150. package/internal/crypto/keying/principalPolicyHistoryReferences.js +1 -1
  151. package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
  152. package/internal/crypto/keying/principalPolicyHistoryTypes.d.ts +7 -2
  153. package/internal/crypto/keying/principalPolicyHistoryTypes.js +6 -3
  154. package/internal/crypto/keying/principalPolicyHistoryTypes.js.map +1 -1
  155. package/internal/crypto/projectionHistorySlots.js +0 -4
  156. package/internal/crypto/projectionHistorySlots.js.map +1 -1
  157. package/internal/validators/operation/index.d.ts +1 -0
  158. package/internal/validators/operation/index.js +1 -0
  159. package/internal/validators/operation/index.js.map +1 -1
  160. package/internal/validators/operation/principals.d.ts +38 -16
  161. package/internal/validators/operation/principals.js +11 -5
  162. package/internal/validators/operation/principals.js.map +1 -1
  163. package/internal/validators/operation/projectionPolicyHistory.d.ts +512 -0
  164. package/internal/validators/operation/projectionPolicyHistory.js +37 -0
  165. package/internal/validators/operation/projectionPolicyHistory.js.map +1 -0
  166. package/internal/validators/operation/registry.d.ts +2 -0
  167. package/internal/validators/operation/registry.js +2 -0
  168. package/internal/validators/operation/registry.js.map +1 -1
  169. package/internal/validators/operation/writerProjections.d.ts +178 -1224
  170. package/internal/validators/operation/writerProjections.js +9 -2
  171. package/internal/validators/operation/writerProjections.js.map +1 -1
  172. package/internal/validators/response/container.d.ts +84 -612
  173. package/internal/validators/response/documentMutation.d.ts +84 -612
  174. package/internal/validators/response/index.d.ts +1 -0
  175. package/internal/validators/response/index.js +1 -0
  176. package/internal/validators/response/index.js.map +1 -1
  177. package/internal/validators/response/organizationBilling.d.ts +1 -0
  178. package/internal/validators/response/organizationBilling.js +1 -1
  179. package/internal/validators/response/organizationBilling.js.map +1 -1
  180. package/internal/validators/response/principalHistoryPreparation.js +28 -1
  181. package/internal/validators/response/principalHistoryPreparation.js.map +1 -1
  182. package/internal/validators/response/principalPolicySnapshotPage.d.ts +388 -0
  183. package/internal/validators/response/principalPolicySnapshotPage.js +24 -0
  184. package/internal/validators/response/principalPolicySnapshotPage.js.map +1 -0
  185. package/internal/validators/response/projectionPolicyEvidence.d.ts +85 -613
  186. package/internal/validators/response/projectionPolicyEvidence.js +10 -5
  187. package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
  188. package/package.json +1 -1
  189. package/stores/documents/documentStore/attachmentHydration.js +3 -0
  190. package/stores/documents/documentStore/attachmentHydration.js.map +1 -1
  191. package/stores/documents/documentStore/syncDetachedAttachments.js +3 -0
  192. package/stores/documents/documentStore/syncDetachedAttachments.js.map +1 -1
  193. package/workflows/blobs/decrypt.d.ts +1 -1
  194. package/workflows/blobs/decrypt.js +3 -1
  195. package/workflows/blobs/decrypt.js.map +1 -1
  196. package/workflows/blobs/detach.js +6 -1
  197. package/workflows/blobs/detach.js.map +1 -1
  198. package/workflows/blobs/hydrate.d.ts +3 -1
  199. package/workflows/blobs/hydrate.js +2 -0
  200. package/workflows/blobs/hydrate.js.map +1 -1
  201. package/workflows/blobs/retainedAttachmentVerification.js +2 -0
  202. package/workflows/blobs/retainedAttachmentVerification.js.map +1 -1
  203. package/workflows/container-contents/container-state/createAdoption.js +2 -0
  204. package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
  205. package/workflows/container-contents/container-state/createWithMetadata.js +7 -39
  206. package/workflows/container-contents/container-state/createWithMetadata.js.map +1 -1
  207. package/workflows/container-contents/container-state/createWithMetadataPlan.js +68 -0
  208. package/workflows/container-contents/container-state/createWithMetadataPlan.js.map +1 -0
  209. package/workflows/container-contents/remoteContainerState.js +3 -1
  210. package/workflows/container-contents/remoteContainerState.js.map +1 -1
  211. package/workflows/container-contents/remoteHydration/verifiedDestination.js +3 -0
  212. package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +1 -1
  213. package/workflows/container-contents/runtime.d.ts +3 -0
  214. package/workflows/container-contents/runtime.js +7 -6
  215. package/workflows/container-contents/runtime.js.map +1 -1
  216. package/workflows/containers/child/share.js +4 -0
  217. package/workflows/containers/child/share.js.map +1 -1
  218. package/workflows/containers/child/sharePrincipalPolicy.d.ts +1 -0
  219. package/workflows/containers/child/sharePrincipalPolicy.js.map +1 -1
  220. package/workflows/documents/create.d.ts +2 -15
  221. package/workflows/documents/create.js +9 -64
  222. package/workflows/documents/create.js.map +1 -1
  223. package/workflows/documents/createProjection.d.ts +14 -0
  224. package/workflows/documents/createProjection.js +26 -0
  225. package/workflows/documents/createProjection.js.map +1 -0
  226. package/workflows/documents/createResponse.js +49 -0
  227. package/workflows/documents/createResponse.js.map +1 -0
  228. package/workflows/documents/linkSetBlobRewraps.js +2 -0
  229. package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
  230. package/workflows/documents/runtime.d.ts +3 -0
  231. package/workflows/documents/runtime.js +3 -2
  232. package/workflows/documents/runtime.js.map +1 -1
  233. package/workflows/documents/syncFailureClassification.js +3 -1
  234. package/workflows/documents/syncFailureClassification.js.map +1 -1
  235. package/workflows/organizations/acknowledgedDirectoryBindings.js +18 -0
  236. package/workflows/organizations/acknowledgedDirectoryBindings.js.map +1 -0
  237. package/workflows/organizations/currentGroupMetadataAuthority.js +32 -0
  238. package/workflows/organizations/currentGroupMetadataAuthority.js.map +1 -0
  239. package/workflows/organizations/currentOrganizationAuthority.js +88 -0
  240. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -0
  241. package/workflows/organizations/currentOrganizationGroupNames.js +68 -0
  242. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -0
  243. package/workflows/organizations/currentPolicyMutationAcknowledgement.js +65 -0
  244. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -0
  245. package/workflows/organizations/deleteOrganizationGroup.js +1 -0
  246. package/workflows/organizations/deleteOrganizationGroup.js.map +1 -1
  247. package/workflows/organizations/groupCreation.js +1 -0
  248. package/workflows/organizations/groupCreation.js.map +1 -1
  249. package/workflows/organizations/groupMetadataAccess.d.ts +2 -2
  250. package/workflows/organizations/groupMetadataAccess.js +1 -1
  251. package/workflows/organizations/groupMetadataAccess.js.map +1 -1
  252. package/workflows/organizations/groupMetadataBinding.js.map +1 -1
  253. package/workflows/organizations/groupMetadataContainerAuthority.js +2 -47
  254. package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
  255. package/workflows/organizations/groupMetadataRootBinding.js +51 -0
  256. package/workflows/organizations/groupMetadataRootBinding.js.map +1 -0
  257. package/workflows/organizations/groupMetadataRuntime.js +20 -9
  258. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  259. package/workflows/organizations/groupMutationAuthorization.js.map +1 -1
  260. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +9 -75
  261. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  262. package/workflows/organizations/groupPolicyMutationContext.d.ts +5 -13
  263. package/workflows/organizations/groupPolicyMutationContext.js +1 -0
  264. package/workflows/organizations/groupPolicyMutationContext.js.map +1 -1
  265. package/workflows/organizations/groupPolicyMutationEvidence.d.ts +26 -0
  266. package/workflows/organizations/groupPolicyMutationEvidence.js +64 -0
  267. package/workflows/organizations/groupPolicyMutationEvidence.js.map +1 -0
  268. package/workflows/organizations/groupPolicyMutationHead.js.map +1 -1
  269. package/workflows/organizations/groupPolicyRequests.js +69 -63
  270. package/workflows/organizations/groupPolicyRequests.js.map +1 -1
  271. package/workflows/organizations/index.d.ts +6 -0
  272. package/workflows/organizations/index.js +5 -0
  273. package/workflows/organizations/index.js.map +1 -1
  274. package/workflows/organizations/organizationGroupNames.js +7 -0
  275. package/workflows/organizations/organizationGroupNames.js.map +1 -1
  276. package/workflows/organizations/principalCurrentPublicationSeal.js +51 -0
  277. package/workflows/organizations/principalCurrentPublicationSeal.js.map +1 -0
  278. package/workflows/organizations/principalMutationJournalLane.js +26 -0
  279. package/workflows/organizations/principalMutationJournalLane.js.map +1 -0
  280. package/workflows/organizations/principalMutationJournalManagement.d.ts +26 -0
  281. package/workflows/organizations/principalMutationJournalManagement.js +104 -0
  282. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -0
  283. package/workflows/organizations/principalMutationJournalSession.d.ts +26 -0
  284. package/workflows/organizations/principalMutationJournalSession.js +85 -0
  285. package/workflows/organizations/principalMutationJournalSession.js.map +1 -0
  286. package/workflows/organizations/principalMutationReceipt.js +21 -0
  287. package/workflows/organizations/principalMutationReceipt.js.map +1 -0
  288. package/workflows/organizations/principalPolicyReceiptArtifacts.js +74 -0
  289. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -0
  290. package/workflows/organizations/principalPolicyRequest.d.ts +5 -4
  291. package/workflows/organizations/principalPolicyRequest.js.map +1 -1
  292. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +21 -0
  293. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +155 -0
  294. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -0
  295. package/workflows/principals/index.d.ts +2 -0
  296. package/workflows/principals/index.js +1 -0
  297. package/workflows/principals/index.js.map +1 -1
  298. package/workflows/principals/policyVerification.js.map +1 -1
  299. package/workflows/principals/principalCurrentRecoveryBatch.js +14 -0
  300. package/workflows/principals/principalCurrentRecoveryBatch.js.map +1 -0
  301. package/workflows/principals/principalHistoryRecoveryAuthority.js +20 -0
  302. package/workflows/principals/principalHistoryRecoveryAuthority.js.map +1 -0
  303. package/workflows/principals/principalHistoryRecoveryStage.js +1 -1
  304. package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
  305. package/workflows/principals/principalHistoryRecoveryTypes.d.ts +3 -3
  306. package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
  307. package/workflows/principals/principalHistoryRecoveryVerification.js +6 -1
  308. package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -1
  309. package/workflows/principals/principalRecoveryDirectory.d.ts +1 -1
  310. package/workflows/principals/principalRecoveryDirectory.js +29 -4
  311. package/workflows/principals/principalRecoveryDirectory.js.map +1 -1
  312. package/workflows/principals/principalRecoveryDiscoveryPage.js +36 -0
  313. package/workflows/principals/principalRecoveryDiscoveryPage.js.map +1 -0
  314. package/workflows/principals/principalRecoveryLocalPreference.js +28 -0
  315. package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -0
  316. package/workflows/principals/principalRecoveryMemo.d.ts +16 -0
  317. package/workflows/principals/principalRecoveryMemo.js +88 -16
  318. package/workflows/principals/principalRecoveryMemo.js.map +1 -1
  319. package/workflows/principals/principalRecoveryOutage.js +1 -1
  320. package/workflows/principals/principalRecoveryOutage.js.map +1 -1
  321. package/workflows/principals/publicPrincipalHistoryAuthority.js +60 -0
  322. package/workflows/principals/publicPrincipalHistoryAuthority.js.map +1 -0
  323. package/workflows/principals/publicPrincipalHistoryPage.js +87 -0
  324. package/workflows/principals/publicPrincipalHistoryPage.js.map +1 -0
  325. package/workflows/principals/publicPrincipalHistoryProgress.js +178 -0
  326. package/workflows/principals/publicPrincipalHistoryProgress.js.map +1 -0
  327. package/workflows/principals/publicPrincipalHistoryTypes.d.ts +39 -0
  328. package/workflows/principals/publicPrincipalHistoryTypes.js +2 -0
  329. package/workflows/principals/publicPrincipalHistoryTypes.js.map +1 -0
  330. package/workflows/principals/publicProjectionDirectory.js +40 -0
  331. package/workflows/principals/publicProjectionDirectory.js.map +1 -0
  332. package/workflows/principals/publicProjectionPrincipal.js +53 -0
  333. package/workflows/principals/publicProjectionPrincipal.js.map +1 -0
  334. package/workflows/principals/recoverCurrentOrganizationPolicy.js +33 -0
  335. package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +1 -0
  336. package/workflows/principals/recoverPrincipalPolicyHistory.js +4 -1
  337. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
  338. package/workflows/principals/recoverProjectionPolicyHistory.d.ts +9 -0
  339. package/workflows/principals/recoverProjectionPolicyHistory.js +98 -0
  340. package/workflows/principals/recoverProjectionPolicyHistory.js.map +1 -0
  341. package/workflows/principals/recoverPublicPrincipalHistory.js +176 -0
  342. package/workflows/principals/recoverPublicPrincipalHistory.js.map +1 -0
  343. package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +2 -1
  344. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +15 -20
  345. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  346. package/workflows/principals/runtimePolicyRecovery.js +16 -9
  347. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  348. package/workflows/principals/runtimePolicyWarmer.js +2 -0
  349. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  350. package/workflows/principals/runtimeProjectionPolicyRecovery.js +56 -0
  351. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -0
  352. package/workflows/principals/selectPublicPrincipalHistory.js +90 -0
  353. package/workflows/principals/selectPublicPrincipalHistory.js.map +1 -0
  354. package/workflows/registration/provisioningBootstrapBuilders.d.ts +21 -153
@@ -1,70 +1,23 @@
1
- import { computePrincipalStatePayloadCiphertextHash, KeyingVerificationError, } from "../../internal/crypto/index.js";
2
- import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../principals/organizationAuthorityDescriptor.js";
3
- import { enforcePrincipalPolicySnapshotCheckpoints, verifyPrincipalPolicySnapshots, } from "./principalPolicySnapshotVerification.js";
4
- function reject(message) {
5
- throw new KeyingVerificationError("object_mismatch", `Projection policy evidence: ${message}`);
6
- }
7
- async function verifyDirectories(input) {
8
- const states = new Map(input.organization.history.map(({ state }) => [state.stateHash, state]));
9
- const descriptors = [];
10
- for (const payload of input.evidence.organizationPayloads) {
11
- const state = states.get(payload.stateHash);
12
- if (!state ||
13
- payload.principalType !== "organization" ||
14
- payload.principalId !== input.organizationId)
15
- reject("directory payload scope is invalid");
16
- const hash = await computePrincipalStatePayloadCiphertextHash(payload.ciphertext);
17
- if (hash !== state.payloadCiphertextHash || hash !== payload.ciphertextHash)
18
- reject("directory payload does not match its signed hash");
19
- const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);
20
- if (descriptor.organizationId !== input.organizationId)
21
- reject("directory belongs to another organization");
22
- descriptors.push(descriptor);
23
- states.delete(payload.stateHash);
24
- }
25
- // Only directory payloads needed to bind the supplied group heads are
26
- // required. The organization's complete signed state chain is verified above;
27
- // unrelated payload bodies add no authority and need not be disclosed.
28
- return descriptors;
29
- }
30
- /** Evidence authenticates signed citations only; it never becomes current policy. */
1
+ import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
+ import { ProjectionDependencyUnavailableError } from "./dependencyUnavailable.js";
3
+ import { assertProjectionVerificationCurrent, } from "./types.js";
4
+ /** Recover public authorization without admitting historical heads as current policy. */
31
5
  export async function verifyProjectionPolicyEvidence(input) {
32
- const { evidence, organizationId } = input;
33
- if (evidence.organization === null) {
34
- if (evidence.groups.length > 0 || evidence.organizationPayloads.length > 0)
35
- reject("group evidence requires its signed organization history");
36
- return [];
37
- }
38
- if (evidence.organization.currentState.principalType !== "organization" ||
39
- evidence.organization.currentState.principalId !== organizationId ||
40
- evidence.groups.some((group) => group.currentState.principalType !== "group"))
41
- reject("principal scope is invalid");
42
- const policies = await verifyPrincipalPolicySnapshots({
43
- resolveUserKey: input.resolveUserKey,
44
- snapshots: [evidence.organization, ...evidence.groups],
45
- });
46
- const organization = policies.find((policy) => policy.principalType === "organization");
47
- if (!organization)
48
- reject("organization snapshot is missing");
49
- const directories = await verifyDirectories({ ...input, organization });
50
- for (const group of policies.filter((policy) => policy.principalType === "group")) {
51
- const directory = directories.find((candidate) => candidate.groupHeads.some((reference) => principalHeadMatchesReference(group.state, reference)));
52
- if (!directory)
53
- reject("group state is absent from signed directory history");
54
- // The snapshot's authenticated predecessor chain supplies older states;
55
- // only its bound head needs to appear in a directory payload.
56
- for (const { state } of group.history) {
57
- if (state.externalAuthority &&
58
- state.externalAuthority.principalId !== directory.adminGroupId)
59
- reject("group authority is not the organization's Admins group");
60
- }
6
+ const stillCurrent = () => input.stillCurrent?.() !== false;
7
+ assertProjectionVerificationCurrent(stillCurrent);
8
+ if (!input.evidence.organization) {
9
+ if (input.evidence.groups.length ||
10
+ input.evidence.organizationPayloads.length ||
11
+ input.references.length)
12
+ throw new KeyingVerificationError("missing_dependency", "Projection omits required organization history");
13
+ return { policies: [], stillCurrent };
61
14
  }
62
- // Check connection to known chains without pinning historical group heads or
63
- // caching keyless evidence as a live policy bundle.
64
- await enforcePrincipalPolicySnapshotCheckpoints({
65
- execSql: input.execSql,
66
- policies,
67
- });
68
- return policies;
15
+ const resolve = input.warmReferencedPrincipalPolicies?.resolveProjectionHistory;
16
+ if (!resolve)
17
+ throw new ProjectionDependencyUnavailableError("Private projection history recovery is unavailable");
18
+ const result = await resolve({ ...input, stillCurrent });
19
+ assertProjectionVerificationCurrent(stillCurrent);
20
+ assertProjectionVerificationCurrent(result.stillCurrent);
21
+ return result;
69
22
  }
70
23
  //# sourceMappingURL=projectionPolicyEvidence.js.map
@@ -1 +1 @@
1
- {"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K,cAAc,CACpD,CAAC;IACF,IAAI,CAAC,YAAY;QAAE,MAAM,CAAC,kCAAkC,CAAC,CAAC;IAC9D,MAAM,WAAW,GAAG,MAAM,iBAAiB,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;IACxE,KAAK,MAAM,KAAK,IAAI,QAAQ,CAAC,MAAM,CACjC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,aAAa,KAAK,OAAO,CAC7C,EAAE,CAAC;QACF,MAAM,SAAS,GAAG,WAAW,CAAC,IAAI,CAAC,CAAC,SAAS,EAAE,EAAE,CAC/C,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,SAAkC,EAAE,EAAE,CAC/D,6BAA6B,CAAC,KAAK,CAAC,KAAK,EAAE,SAAS,CAAC,CACtD,CACF,CAAC;QACF,IAAI,CAAC,SAAS;YACZ,MAAM,CAAC,qDAAqD,CAAC,CAAC;QAChE,wEAAwE;QACxE,8DAA8D;QAC9D,KAAK,MAAM,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC,OAAO,EAAE,CAAC;YACtC,IACE,KAAK,CAAC,iBAAiB;gBACvB,KAAK,CAAC,iBAAiB,CAAC,WAAW,KAAK,SAAS,CAAC,YAAY;gBAE9D,MAAM,CAAC,wDAAwD,CAAC,CAAC;QACrE,CAAC;IACH,CAAC;IACD,6EAA6E;IAC7E,oDAAoD;IACpD,MAAM,yCAAyC,CAAC;QAC9C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ;KACT,CAAC,CAAC;IACH,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n computePrincipalStatePayloadCiphertextHash,\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicySnapshot,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport {\n enforcePrincipalPolicySnapshotCheckpoints,\n verifyPrincipalPolicySnapshots,\n} from \"./principalPolicySnapshotVerification\";\nimport type { ProjectionUserKeyResolver } from \"./types\";\n\nfunction reject(message: string): never {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `Projection policy evidence: ${message}`,\n );\n}\n\nasync function verifyDirectories(input: {\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly organization: VerifiedPrincipalPolicySnapshot;\n readonly organizationId: string;\n}): Promise<OrganizationAuthorityDescriptor[]> {\n const states = new Map(\n input.organization.history.map(({ state }) => [state.stateHash, state]),\n );\n const descriptors: OrganizationAuthorityDescriptor[] = [];\n for (const payload of input.evidence.organizationPayloads) {\n const state = states.get(payload.stateHash);\n if (\n !state ||\n payload.principalType !== \"organization\" ||\n payload.principalId !== input.organizationId\n )\n reject(\"directory payload scope is invalid\");\n const hash = await computePrincipalStatePayloadCiphertextHash(\n payload.ciphertext,\n );\n if (hash !== state.payloadCiphertextHash || hash !== payload.ciphertextHash)\n reject(\"directory payload does not match its signed hash\");\n const descriptor = parseOrganizationAuthorityDescriptor(payload.ciphertext);\n if (descriptor.organizationId !== input.organizationId)\n reject(\"directory belongs to another organization\");\n descriptors.push(descriptor);\n states.delete(payload.stateHash);\n }\n // Only directory payloads needed to bind the supplied group heads are\n // required. The organization's complete signed state chain is verified above;\n // unrelated payload bodies add no authority and need not be disclosed.\n return descriptors;\n}\n\n/** Evidence authenticates signed citations only; it never becomes current policy. */\nexport async function verifyProjectionPolicyEvidence(input: {\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<VerifiedPrincipalPolicySnapshot[]> {\n const { evidence, organizationId } = input;\n if (evidence.organization === null) {\n if (evidence.groups.length > 0 || evidence.organizationPayloads.length > 0)\n reject(\"group evidence requires its signed organization history\");\n return [];\n }\n if (\n evidence.organization.currentState.principalType !== \"organization\" ||\n evidence.organization.currentState.principalId !== organizationId ||\n evidence.groups.some(\n (group) => group.currentState.principalType !== \"group\",\n )\n )\n reject(\"principal scope is invalid\");\n const policies = await verifyPrincipalPolicySnapshots({\n resolveUserKey: input.resolveUserKey,\n snapshots: [evidence.organization, ...evidence.groups],\n });\n const organization = policies.find(\n (policy) => policy.principalType === \"organization\",\n );\n if (!organization) reject(\"organization snapshot is missing\");\n const directories = await verifyDirectories({ ...input, organization });\n for (const group of policies.filter(\n (policy) => policy.principalType === \"group\",\n )) {\n const directory = directories.find((candidate) =>\n candidate.groupHeads.some((reference: ReferencedPrincipalHead) =>\n principalHeadMatchesReference(group.state, reference),\n ),\n );\n if (!directory)\n reject(\"group state is absent from signed directory history\");\n // The snapshot's authenticated predecessor chain supplies older states;\n // only its bound head needs to appear in a directory payload.\n for (const { state } of group.history) {\n if (\n state.externalAuthority &&\n state.externalAuthority.principalId !== directory.adminGroupId\n )\n reject(\"group authority is not the organization's Admins group\");\n }\n }\n // Check connection to known chains without pinning historical group heads or\n // caching keyless evidence as a live policy bundle.\n await enforcePrincipalPolicySnapshotCheckpoints({\n execSql: input.execSql,\n policies,\n });\n return policies;\n}\n"]}
1
+ {"version":3,"file":"projectionPolicyEvidence.js","sourceRoot":"","sources":["projectionPolicyEvidence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,yBAAyB,CAAC;AAC/E,OAAO,EACL,mCAAmC,GAGpC,MAAM,SAAS,CAAC;AAEjB,yFAAyF;AACzF,MAAM,CAAC,KAAK,UAAU,8BAA8B,CAAC,KAQpD;IACC,MAAM,YAAY,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,CAAC;IAC5D,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,YAAY,EAAE,CAAC;QACjC,IACE,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM;YAC5B,KAAK,CAAC,QAAQ,CAAC,oBAAoB,CAAC,MAAM;YAC1C,KAAK,CAAC,UAAU,CAAC,MAAM;YAEvB,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,gDAAgD,CACjD,CAAC;QACJ,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,YAAY,EAAE,CAAC;IACxC,CAAC;IACD,MAAM,OAAO,GACX,KAAK,CAAC,+BAA+B,EAAE,wBAAwB,CAAC;IAClE,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,oDAAoD,CACrD,CAAC;IACJ,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;IACzD,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,mCAAmC,CAAC,MAAM,CAAC,YAAY,CAAC,CAAC;IACzD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { ProjectionPolicyEvidenceResponse } from \"@tearleads/validators/response\";\nimport { ProjectionDependencyUnavailableError } from \"./dependencyUnavailable\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedProjectionPolicyHistory,\n} from \"./types\";\n\n/** Recover public authorization without admitting historical heads as current policy. */\nexport async function verifyProjectionPolicyEvidence(input: {\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly organizationId: string;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}): Promise<ResolvedProjectionPolicyHistory> {\n const stillCurrent = () => input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n if (!input.evidence.organization) {\n if (\n input.evidence.groups.length ||\n input.evidence.organizationPayloads.length ||\n input.references.length\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection omits required organization history\",\n );\n return { policies: [], stillCurrent };\n }\n const resolve =\n input.warmReferencedPrincipalPolicies?.resolveProjectionHistory;\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Private projection history recovery is unavailable\",\n );\n const result = await resolve({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n assertProjectionVerificationCurrent(result.stillCurrent);\n return result;\n}\n"]}
@@ -1,5 +1,5 @@
1
- import type { ReferencedPrincipalHead, VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
2
- import type { PrincipalPolicyBundleResponse } from "../../internal/validators/response/index.js";
1
+ import type { ReferencedPrincipalHead, VerifiedPrincipalPolicyCurrent, VerifiedPrincipalPolicySelection } from "../../internal/crypto/index.js";
2
+ import type { PrincipalPolicyBundleResponse, ProjectionPolicyEvidenceResponse } from "../../internal/validators/response/index.js";
3
3
  import type { PrincipalPolicyCurrentEvidence } from "../principals/principalPolicyEvidence.js";
4
4
  import type { TrustedUserIdentity } from "../trustedUserIdentity/index.js";
5
5
  export type ProjectionUserKey = TrustedUserIdentity;
@@ -28,9 +28,20 @@ export interface PrincipalPolicyBundleCacheRequest {
28
28
  readonly organizationId: string;
29
29
  readonly stillCurrent?: (() => boolean) | undefined;
30
30
  }
31
+ export interface ProjectionPolicyHistoryResolveRequest {
32
+ readonly organizationId: string;
33
+ readonly evidence: ProjectionPolicyEvidenceResponse;
34
+ readonly references: readonly ReferencedPrincipalHead[];
35
+ readonly stillCurrent?: (() => boolean) | undefined;
36
+ }
37
+ export interface ResolvedProjectionPolicyHistory {
38
+ readonly policies: readonly VerifiedPrincipalPolicySelection[];
39
+ readonly stillCurrent: () => boolean;
40
+ }
31
41
  export type PrincipalPolicyBundleCacher = (input: PrincipalPolicyBundleCacheRequest) => Promise<void>;
32
42
  export type ReferencedPrincipalPolicyWarmer = ((input: ReferencedPrincipalPolicyWarmRequest) => Promise<void>) & {
33
43
  readonly cacheBundles?: PrincipalPolicyBundleCacher | undefined;
44
+ readonly resolveProjectionHistory?: ((input: ProjectionPolicyHistoryResolveRequest) => Promise<ResolvedProjectionPolicyHistory>) | undefined;
34
45
  readonly resolveReference?: ((input: PrincipalPolicyResolveRequest) => Promise<ResolvedPrincipalPolicyEvidence>) | undefined;
35
46
  };
36
47
  export declare class ProjectionVerificationCancelledError extends Error {
@@ -38,7 +38,22 @@ export function generationGuardedPrincipalPolicyWarmer(warmer, stillCurrent) {
38
38
  const guardWithCapabilities = (operation) => {
39
39
  const guarded = guard(operation);
40
40
  const resolve = operation.resolveReference;
41
+ const resolveProjectionHistory = operation.resolveProjectionHistory;
41
42
  return Object.assign(guarded, {
43
+ ...(resolveProjectionHistory
44
+ ? {
45
+ resolveProjectionHistory: async (input) => {
46
+ const current = () => stillCurrent() && input.stillCurrent?.() !== false;
47
+ assertProjectionVerificationCurrent(current);
48
+ const result = await resolveProjectionHistory({
49
+ ...input,
50
+ stillCurrent: current,
51
+ });
52
+ assertProjectionVerificationCurrent(current);
53
+ return result;
54
+ },
55
+ }
56
+ : {}),
42
57
  ...(resolve
43
58
  ? {
44
59
  resolveReference: async (input) => {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AA0DA,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D;QACE,KAAK,CAAC,4CAA4C,CAAC,CAAC;QACpD,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;AAED,MAAM,kCAAkC,GACtC,IAAI,oCAAoC,EAAE,CAAC;AAE7C,MAAM,UAAU,sCAAsC,CACpD,KAAc;IAEd,OAAO,KAAK,KAAK,kCAAkC,CAAC;AACtD,CAAC;AAED,MAAM,UAAU,sCAA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KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,CAAC;wBACrD,mCAAmC,CAAC,OAAO,CAAC,CAAC;wBAC7C,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,CAAC,CAAC;wBAClE,mCAAmC,CAAC,OAAO,CAAC,CAAC;wBAC7C,OAAO,MAAM,CAAC;oBAChB,CAAC;iBACF;gBACH,CAAC,CAAC,EAAE,CAAC;YACP,GAAG,CAAC,SAAS,CAAC,YAAY;gBACxB,CAAC,CAAC;oBACE,YAAY,EAAE,KAAK,EAAE,KAAwC,EAAE,EAAE;wBAC/D,mCAAmC,CAAC,YAAY,CAAC,CAAC;wBAClD,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;wBAC3D,mCAAmC,CAAC,YAAY,CAAC,CAAC;oBACpD,CAAC;iBACF;gBACH,CAAC,CAAC,EAAE,CAAC;SACR,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,iCAAiC,CAO/C,KAAY;IACZ,OAAO;QACL,GAAG,KAAK;QACR,+BAA+B,EAAE,sCAAsC,CACrE,KAAK,CAAC,+BAA+B,EACrC,KAAK,CAAC,YAAY,CACnB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\n\nexport type ProjectionUserKey = TrustedUserIdentity;\n\nexport type ProjectionUserKeyResolver = (\n userId: string,\n) => Promise<ProjectionUserKey | null>;\n\nexport type PrincipalPolicyCache = Map<string, PrincipalPolicyCurrentEvidence>;\n\nexport interface PrincipalPolicyResolveRequest {\n /** Identity of one projection collection, never caller-supplied evidence. */\n readonly recoveryBatch?: object | undefined;\n readonly organizationId: string;\n readonly reference: ReferencedPrincipalHead;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ResolvedPrincipalPolicyEvidence {\n readonly stillCurrent: () => boolean;\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n}\n\nexport interface ReferencedPrincipalPolicyWarmRequest {\n readonly organizationId: string;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface PrincipalPolicyBundleCacheRequest {\n readonly bundles: readonly PrincipalPolicyBundleResponse[];\n readonly organizationId: string;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport type PrincipalPolicyBundleCacher = (\n input: PrincipalPolicyBundleCacheRequest,\n) => Promise<void>;\n\nexport type ReferencedPrincipalPolicyWarmer = ((\n input: ReferencedPrincipalPolicyWarmRequest,\n) => Promise<void>) & {\n readonly cacheBundles?: PrincipalPolicyBundleCacher | undefined;\n readonly resolveReference?:\n | ((\n input: PrincipalPolicyResolveRequest,\n ) => Promise<ResolvedPrincipalPolicyEvidence>)\n | undefined;\n};\n\nexport class ProjectionVerificationCancelledError extends Error {\n constructor() {\n super(\"Projection verification generation expired\");\n this.name = \"ProjectionVerificationCancelledError\";\n }\n}\n\nconst projectionVerificationCancellation =\n new ProjectionVerificationCancelledError();\n\nexport function isProjectionVerificationCancelledError(\n error: unknown,\n): error is ProjectionVerificationCancelledError {\n return error === projectionVerificationCancellation;\n}\n\nexport function rethrowProjectionVerificationCancelled(error: unknown): void {\n if (isProjectionVerificationCancelledError(error)) throw error;\n}\n\nexport async function nullOnProjectionVerificationCancellation<T>(\n operation: () => Promise<T>,\n): Promise<T | null> {\n try {\n return await operation();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return null;\n throw error;\n }\n}\n\nexport function assertProjectionVerificationCurrent(\n stillCurrent: (() => boolean) | undefined,\n): void {\n if (stillCurrent?.() === false) {\n throw projectionVerificationCancellation;\n }\n}\n\nexport function generationGuardedPrincipalPolicyWarmer(\n warmer: ReferencedPrincipalPolicyWarmer | undefined,\n stillCurrent: (() => boolean) | undefined,\n): ReferencedPrincipalPolicyWarmer | undefined {\n if (!warmer || !stillCurrent) return warmer;\n const guard =\n (operation: ReferencedPrincipalPolicyWarmer) =>\n async (input: ReferencedPrincipalPolicyWarmRequest) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await operation({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n };\n const guardWithCapabilities = (\n operation: ReferencedPrincipalPolicyWarmer,\n ): ReferencedPrincipalPolicyWarmer => {\n const guarded = guard(operation);\n const resolve = operation.resolveReference;\n return Object.assign(guarded, {\n ...(resolve\n ? {\n resolveReference: async (input: PrincipalPolicyResolveRequest) => {\n const current = () =>\n stillCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(current);\n const result = await resolve({ ...input, stillCurrent: current });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n }\n : {}),\n ...(operation.cacheBundles\n ? {\n cacheBundles: async (input: PrincipalPolicyBundleCacheRequest) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await operation.cacheBundles?.({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n },\n }\n : {}),\n });\n };\n return guardWithCapabilities(warmer);\n}\n\nexport function withGenerationGuardedPolicyWarmer<\n Input extends {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n },\n>(input: Input): Input {\n return {\n ...input,\n warmReferencedPrincipalPolicies: generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n ),\n };\n}\n"]}
1
+ {"version":3,"file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AC,CAAC;oBACE,YAAY,EAAE,KAAK,EAAE,KAAwC,EAAE,EAAE;wBAC/D,mCAAmC,CAAC,YAAY,CAAC,CAAC;wBAClD,MAAM,SAAS,CAAC,YAAY,EAAE,CAAC,EAAE,GAAG,KAAK,EAAE,YAAY,EAAE,CAAC,CAAC;wBAC3D,mCAAmC,CAAC,YAAY,CAAC,CAAC;oBACpD,CAAC;iBACF;gBACH,CAAC,CAAC,EAAE,CAAC;SACR,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC;AAED,MAAM,UAAU,iCAAiC,CAO/C,KAAY;IACZ,OAAO;QACL,GAAG,KAAK;QACR,+BAA+B,EAAE,sCAAsC,CACrE,KAAK,CAAC,+BAA+B,EACrC,KAAK,CAAC,YAAY,CACnB;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedPrincipalPolicyCurrent,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ProjectionPolicyEvidenceResponse,\n} from \"@tearleads/validators/response\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../principals/principalPolicyEvidence\";\nimport type { TrustedUserIdentity } from \"../trustedUserIdentity\";\n\nexport type ProjectionUserKey = TrustedUserIdentity;\n\nexport type ProjectionUserKeyResolver = (\n userId: string,\n) => Promise<ProjectionUserKey | null>;\n\nexport type PrincipalPolicyCache = Map<string, PrincipalPolicyCurrentEvidence>;\n\nexport interface PrincipalPolicyResolveRequest {\n /** Identity of one projection collection, never caller-supplied evidence. */\n readonly recoveryBatch?: object | undefined;\n readonly organizationId: string;\n readonly reference: ReferencedPrincipalHead;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ResolvedPrincipalPolicyEvidence {\n readonly stillCurrent: () => boolean;\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly dependencies: readonly VerifiedPrincipalPolicyCurrent[];\n}\n\nexport interface ReferencedPrincipalPolicyWarmRequest {\n readonly organizationId: string;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface PrincipalPolicyBundleCacheRequest {\n readonly bundles: readonly PrincipalPolicyBundleResponse[];\n readonly organizationId: string;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ProjectionPolicyHistoryResolveRequest {\n readonly organizationId: string;\n readonly evidence: ProjectionPolicyEvidenceResponse;\n readonly references: readonly ReferencedPrincipalHead[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface ResolvedProjectionPolicyHistory {\n readonly policies: readonly VerifiedPrincipalPolicySelection[];\n readonly stillCurrent: () => boolean;\n}\n\nexport type PrincipalPolicyBundleCacher = (\n input: PrincipalPolicyBundleCacheRequest,\n) => Promise<void>;\n\nexport type ReferencedPrincipalPolicyWarmer = ((\n input: ReferencedPrincipalPolicyWarmRequest,\n) => Promise<void>) & {\n readonly cacheBundles?: PrincipalPolicyBundleCacher | undefined;\n readonly resolveProjectionHistory?:\n | ((\n input: ProjectionPolicyHistoryResolveRequest,\n ) => Promise<ResolvedProjectionPolicyHistory>)\n | undefined;\n readonly resolveReference?:\n | ((\n input: PrincipalPolicyResolveRequest,\n ) => Promise<ResolvedPrincipalPolicyEvidence>)\n | undefined;\n};\n\nexport class ProjectionVerificationCancelledError extends Error {\n constructor() {\n super(\"Projection verification generation expired\");\n this.name = \"ProjectionVerificationCancelledError\";\n }\n}\n\nconst projectionVerificationCancellation =\n new ProjectionVerificationCancelledError();\n\nexport function isProjectionVerificationCancelledError(\n error: unknown,\n): error is ProjectionVerificationCancelledError {\n return error === projectionVerificationCancellation;\n}\n\nexport function rethrowProjectionVerificationCancelled(error: unknown): void {\n if (isProjectionVerificationCancelledError(error)) throw error;\n}\n\nexport async function nullOnProjectionVerificationCancellation<T>(\n operation: () => Promise<T>,\n): Promise<T | null> {\n try {\n return await operation();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return null;\n throw error;\n }\n}\n\nexport function assertProjectionVerificationCurrent(\n stillCurrent: (() => boolean) | undefined,\n): void {\n if (stillCurrent?.() === false) {\n throw projectionVerificationCancellation;\n }\n}\n\nexport function generationGuardedPrincipalPolicyWarmer(\n warmer: ReferencedPrincipalPolicyWarmer | undefined,\n stillCurrent: (() => boolean) | undefined,\n): ReferencedPrincipalPolicyWarmer | undefined {\n if (!warmer || !stillCurrent) return warmer;\n const guard =\n (operation: ReferencedPrincipalPolicyWarmer) =>\n async (input: ReferencedPrincipalPolicyWarmRequest) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await operation({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n };\n const guardWithCapabilities = (\n operation: ReferencedPrincipalPolicyWarmer,\n ): ReferencedPrincipalPolicyWarmer => {\n const guarded = guard(operation);\n const resolve = operation.resolveReference;\n const resolveProjectionHistory = operation.resolveProjectionHistory;\n return Object.assign(guarded, {\n ...(resolveProjectionHistory\n ? {\n resolveProjectionHistory: async (\n input: ProjectionPolicyHistoryResolveRequest,\n ) => {\n const current = () =>\n stillCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(current);\n const result = await resolveProjectionHistory({\n ...input,\n stillCurrent: current,\n });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n }\n : {}),\n ...(resolve\n ? {\n resolveReference: async (input: PrincipalPolicyResolveRequest) => {\n const current = () =>\n stillCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(current);\n const result = await resolve({ ...input, stillCurrent: current });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n }\n : {}),\n ...(operation.cacheBundles\n ? {\n cacheBundles: async (input: PrincipalPolicyBundleCacheRequest) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await operation.cacheBundles?.({ ...input, stillCurrent });\n assertProjectionVerificationCurrent(stillCurrent);\n },\n }\n : {}),\n });\n };\n return guardWithCapabilities(warmer);\n}\n\nexport function withGenerationGuardedPolicyWarmer<\n Input extends {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n },\n>(input: Input): Input {\n return {\n ...input,\n warmReferencedPrincipalPolicies: generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n ),\n };\n}\n"]}
@@ -5,6 +5,7 @@ import { ensureSqlTables } from "../sqlite/sqlSchema.js";
5
5
  import { storeDocumentPurgeCheckpointInTransaction, } from "./documentPurgeCheckpointPersistence.js";
6
6
  import { validateAccessManifestCheckpointEvidence } from "./keyingCheckpointEvidence.js";
7
7
  import { accessManifestObjectKey, loadStoredAccessManifestCheckpoint, loadStoredPrincipalPolicyCheckpoint, principalPolicyKey, upsertAccessManifestCheckpointInTransaction, upsertPrincipalPolicyCheckpointInTransaction, } from "./keyingCheckpointPersistence.js";
8
+ import { validatePrincipalAuthorizationCheckpoints } from "./principalAuthorizationCheckpoints.js";
8
9
  import { assertContainerNotRetired } from "./principalGrantRetirementPersistence.js";
9
10
  import { assertPrincipalPolicyBundleStoredInTransaction, writePrincipalPolicyBundleInTransaction, } from "./principalPolicyPersistence.js";
10
11
  import { assertBundleMatchesVerifiedPolicy } from "./verifiedPrincipalPolicyBundle.js";
@@ -106,7 +107,7 @@ async function writePolicyCheckpoints(tx, pending, updatedAt, organizationId) {
106
107
  }
107
108
  }
108
109
  async function ensureKeyingCheckpointValidationTables(input) {
109
- await ensureSqlTables(input.execSql, input.policies.length > 0
110
+ await ensureSqlTables(input.execSql, input.policies.length > 0 || (input.authorizationPolicies?.length ?? 0) > 0
110
111
  ? [...principalPolicyTables, ...keyingCheckpointTables]
111
112
  : keyingCheckpointTables);
112
113
  }
@@ -116,6 +117,7 @@ export async function validateKeyingCheckpointsAtomically(input) {
116
117
  const validate = async (tx) => {
117
118
  await validateAccessAdvances(tx, input.access);
118
119
  await validatePolicyAdvances(tx, input.policies);
120
+ await validatePrincipalAuthorizationCheckpoints(tx, input.authorizationPolicies ?? []);
119
121
  };
120
122
  const runtime = getClientSQLitePersistenceRuntime(input.execSql);
121
123
  if (input.stillCurrent) {
@@ -139,6 +141,7 @@ export async function advanceKeyingCheckpointsAtomically(input) {
139
141
  const advance = async (tx) => {
140
142
  const access = await validateAccessAdvances(tx, input.access);
141
143
  const policies = await validatePolicyAdvances(tx, input.policies);
144
+ await validatePrincipalAuthorizationCheckpoints(tx, input.authorizationPolicies ?? []);
142
145
  await writeAccessCheckpoints(tx, access, updatedAt);
143
146
  await writePolicyCheckpoints(tx, policies, updatedAt, input.organizationId);
144
147
  if (input.documentPurgeCheckpoint) {
@@ -1 +1 @@
1
- {"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAIvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAEL,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,wCAAwC,EAAE,MAAM,4BAA4B,CAAC;AACtF,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAClC,mCAAmC,EACnC,kBAAkB,EAClB,2CAA2C,EAC3C,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,yBAAyB,EAAE,MAAM,uCAAuC,CAAC;AAClF,OAAO,EACL,8CAA8C,EAC9C,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AA2BpF,SAAS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,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { assertContainerNotRetired } from \"./principalGrantRetirementPersistence\";\nimport {\n assertPrincipalPolicyBundleStoredInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\ninterface VerifiedPrincipalPolicyBundleEntry {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n\n for (const advance of advances) {\n await assertContainerNotRetired(tx, advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const localCheckpoint = await loadStoredAccessManifestCheckpoint(\n tx,\n advance.head.checkpoint,\n );\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\nasync function validatePolicyAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n for (const { checkpoint } of pending.values()) {\n await upsertAccessManifestCheckpointInTransaction(\n tx,\n checkpoint,\n updatedAt,\n );\n }\n}\n\nasync function writePolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n for (const policy of pending.values()) {\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n policy.checkpoint,\n updatedAt,\n organizationId,\n );\n }\n}\n\nasync function ensureKeyingCheckpointValidationTables(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n await ensureSqlTables(\n input.execSql,\n input.policies.length > 0\n ? [...principalPolicyTables, ...keyingCheckpointTables]\n : keyingCheckpointTables,\n );\n}\n\n/** Re-checks verified candidates against durable pins without advancing them. */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n await ensureKeyingCheckpointValidationTables(input);\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePolicyAdvances(tx, input.policies);\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(input: {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly policies: readonly CheckpointPolicy[];\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n await ensureKeyingCheckpointValidationTables(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePolicyAdvances(tx, input.policies);\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePolicyCheckpoints(tx, policies, updatedAt, input.organizationId);\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n\n/**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\nexport async function persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n const seen = new Set<string>();\n for (const entry of input.entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `verified policy bundle batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const persist = async (tx: ClientSQLiteTransactionScope) => {\n const policies = await validatePolicyAdvances(\n tx,\n input.entries.map((entry) => entry.policy),\n );\n for (const entry of input.entries) {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);\n }\n await writePolicyCheckpoints(\n tx,\n policies,\n input.updatedAt,\n input.organizationId,\n );\n for (const policy of policies.values()) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (\n !checkpoint ||\n checkpoint.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n ) {\n throw new Error(\n \"Verified principal policy checkpoint was not persisted\",\n );\n }\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(persist, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(persist, { behavior: \"immediate\" });\n}\n"]}
1
+ {"version":3,"file":"keyingCheckpointAdvancePersistence.js","sourceRoot":"","sources":["keyingCheckpointAdvancePersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,uBAAuB,EAKvB,mCAAmC,EACnC,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EAEL,yCAAyC,GAC1C,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EAAE,wCAAwC,EAAE,MAAM,4BAA4B,CAAC;AACtF,OAAO,EACL,uBAAuB,EACvB,kCAAkC,EAClC,mCAAmC,EACnC,kBAAkB,EAClB,2CAA2C,EAC3C,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AAChG,OAAO,EAAE,yBAAyB,EAAE,MAAM,uCAAuC,CAAC;AAClF,OAAO,EACL,8CAA8C,EAC9C,uCAAuC,GACxC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AA8BpF,SAAS,qBAAqB,CAC5B,OAAwC,EACxC,eAAgD;IAEhD,MAAM,OAAO,GAAG;QACd,GAAG,OAAO,CAAC,IAAI,CAAC,UAAU;QAC1B,oBAAoB,EAAE,O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AW;SACtB,CAAC,CAAC;QACH,OAAO;IACT,CAAC;IACD,MAAM,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE,EAAE,QAAQ,EAAE,WAAW,EAAE,CAAC,CAAC;AAChE,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n type AnyVerifiedPrincipalPolicy,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedPrincipalPolicy,\n type VerifiedPrincipalPolicyCurrent,\n type VerifiedPrincipalPolicySelection,\n verifyAccessManifestLocalCheckpoint,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n type DocumentPurgeCheckpoint,\n storeDocumentPurgeCheckpointInTransaction,\n} from \"./documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"./keyingCheckpointEvidence\";\nimport {\n accessManifestObjectKey,\n loadStoredAccessManifestCheckpoint,\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertAccessManifestCheckpointInTransaction,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { validatePrincipalAuthorizationCheckpoints } from \"./principalAuthorizationCheckpoints\";\nimport { assertContainerNotRetired } from \"./principalGrantRetirementPersistence\";\nimport {\n assertPrincipalPolicyBundleStoredInTransaction,\n writePrincipalPolicyBundleInTransaction,\n} from \"./principalPolicyPersistence\";\nimport { assertBundleMatchesVerifiedPolicy } from \"./verifiedPrincipalPolicyBundle\";\n\nexport interface AccessManifestCheckpointAdvance {\n readonly head: VerifiedAccessManifestCheckpointEvidence;\n readonly predecessors: readonly VerifiedAccessManifestCheckpointEvidence[];\n}\n\ntype CheckpointPolicy =\n | AnyVerifiedPrincipalPolicy\n | VerifiedPrincipalPolicyCurrent;\n\ninterface KeyingCheckpointValidationInput {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly execSql: ExecSql;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}\n\ninterface VerifiedPrincipalPolicyBundleEntry {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\ninterface PendingAccessCheckpoint {\n readonly checkpoint: AccessManifestCheckpoint;\n}\n\nfunction validateAccessAdvance(\n advance: AccessManifestCheckpointAdvance,\n localCheckpoint: AccessManifestCheckpoint | null,\n): PendingAccessCheckpoint {\n const current = {\n ...advance.head.checkpoint,\n previousManifestHash: advance.head.manifest.previousManifestHash,\n };\n const predecessors = [...advance.predecessors].sort(\n (left, right) => left.checkpoint.epoch - right.checkpoint.epoch,\n );\n\n if (localCheckpoint && current.epoch <= localCheckpoint.epoch) {\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: undefined,\n });\n }\n\n validateAccessManifestCheckpointEvidence({\n head: advance.head,\n predecessors,\n localCheckpoint,\n });\n\n verifyAccessManifestLocalCheckpoint({\n current,\n localCheckpoint,\n checkpointPredecessors: predecessors.filter(\n (manifest) =>\n localCheckpoint !== null &&\n manifest.checkpoint.epoch > localCheckpoint.epoch &&\n manifest.checkpoint.epoch < current.epoch,\n ),\n });\n\n return {\n checkpoint: advance.head.checkpoint,\n };\n}\n\nasync function validateAccessAdvances(\n tx: ClientSQLiteTransactionScope,\n advances: readonly AccessManifestCheckpointAdvance[],\n): Promise<Map<string, PendingAccessCheckpoint>> {\n const pending = new Map<string, PendingAccessCheckpoint>();\n\n for (const advance of advances) {\n await assertContainerNotRetired(tx, advance.head.checkpoint);\n const key = accessManifestObjectKey(advance.head.checkpoint);\n if (pending.has(key)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `projection declares multiple access checkpoint heads for ${key}`,\n );\n }\n const localCheckpoint = await loadStoredAccessManifestCheckpoint(\n tx,\n advance.head.checkpoint,\n );\n pending.set(key, validateAccessAdvance(advance, localCheckpoint));\n }\n\n return pending;\n}\n\nfunction extendsObservedPolicy(\n head: CheckpointPolicy,\n candidate: CheckpointPolicy,\n): boolean {\n const history =\n \"retainedHistory\" in head ? head.retainedHistory : head.history;\n return (\n history?.some(\n ({ state }) =>\n state.principalType === candidate.principalType &&\n state.principalId === candidate.principalId &&\n state.version === candidate.version &&\n state.stateHash === candidate.stateHash,\n ) ?? false\n );\n}\n\nasync function validatePolicyAdvances(\n tx: ClientSQLiteTransactionScope,\n policies: readonly CheckpointPolicy[],\n): Promise<Map<string, CheckpointPolicy>> {\n const policiesByPrincipal = new Map<string, CheckpointPolicy[]>();\n for (const policy of policies) {\n const key = principalPolicyKey(policy);\n const candidates = policiesByPrincipal.get(key) ?? [];\n candidates.push(policy);\n policiesByPrincipal.set(key, candidates);\n }\n\n const pending = new Map<string, CheckpointPolicy>();\n for (const key of [...policiesByPrincipal.keys()].sort()) {\n const candidates = policiesByPrincipal.get(key) ?? [];\n const maxVersion = Math.max(...candidates.map((policy) => policy.version));\n const heads = candidates.filter((policy) => policy.version === maxVersion);\n const head = heads[0];\n if (!head) {\n continue;\n }\n if (heads.some((candidate) => candidate.stateHash !== head.stateHash)) {\n throw new KeyingVerificationError(\n \"equivocation\",\n `principal policy declares conflicting heads for ${key}`,\n );\n }\n for (const candidate of candidates) {\n if (candidate.version === head.version) {\n continue;\n }\n if (!extendsObservedPolicy(head, candidate)) {\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n `principal policy head does not extend observed state for ${key}`,\n );\n }\n }\n\n const localCheckpoint = await loadStoredPrincipalPolicyCheckpoint(tx, head);\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in head ? head.retainedHistory : (head.history ?? []),\n currentState: head.state,\n localCheckpoint,\n });\n pending.set(key, head);\n }\n\n return pending;\n}\n\nasync function writeAccessCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, PendingAccessCheckpoint>,\n updatedAt: string,\n): Promise<void> {\n for (const { checkpoint } of pending.values()) {\n await upsertAccessManifestCheckpointInTransaction(\n tx,\n checkpoint,\n updatedAt,\n );\n }\n}\n\nasync function writePolicyCheckpoints(\n tx: ClientSQLiteTransactionScope,\n pending: ReadonlyMap<string, CheckpointPolicy>,\n updatedAt: string,\n organizationId?: string | undefined,\n): Promise<void> {\n for (const policy of pending.values()) {\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n policy.checkpoint,\n updatedAt,\n organizationId,\n );\n }\n}\n\nasync function ensureKeyingCheckpointValidationTables(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n await ensureSqlTables(\n input.execSql,\n input.policies.length > 0 || (input.authorizationPolicies?.length ?? 0) > 0\n ? [...principalPolicyTables, ...keyingCheckpointTables]\n : keyingCheckpointTables,\n );\n}\n\n/** Re-checks verified candidates against durable pins without advancing them. */\nexport async function validateKeyingCheckpointsAtomically(\n input: KeyingCheckpointValidationInput,\n): Promise<void> {\n await ensureKeyingCheckpointValidationTables(input);\n const validate = async (tx: ClientSQLiteTransactionScope) => {\n await validateAccessAdvances(tx, input.access);\n await validatePolicyAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n };\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n if (input.stillCurrent) {\n await runtime.guardedTransaction(validate, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(validate, { behavior: \"immediate\" });\n}\n\n/**\n * Re-check every verified projection candidate against the latest durable pins\n * and advance the complete batch atomically. Signature verification and remote\n * fetching happen before this short transaction; only checkpoint comparison\n * and persistence are serialized here.\n */\nexport async function advanceKeyingCheckpointsAtomically(input: {\n readonly access: readonly AccessManifestCheckpointAdvance[];\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly policies: readonly CheckpointPolicy[];\n readonly authorizationPolicies?:\n | readonly VerifiedPrincipalPolicySelection[]\n | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<void> {\n await ensureKeyingCheckpointValidationTables(input);\n const updatedAt = new Date().toISOString();\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const advance = async (tx: ClientSQLiteTransactionScope) => {\n const access = await validateAccessAdvances(tx, input.access);\n const policies = await validatePolicyAdvances(tx, input.policies);\n await validatePrincipalAuthorizationCheckpoints(\n tx,\n input.authorizationPolicies ?? [],\n );\n\n await writeAccessCheckpoints(tx, access, updatedAt);\n await writePolicyCheckpoints(tx, policies, updatedAt, input.organizationId);\n if (input.documentPurgeCheckpoint) {\n await storeDocumentPurgeCheckpointInTransaction(\n tx,\n input.documentPurgeCheckpoint,\n updatedAt,\n );\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(advance, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(advance, { behavior: \"immediate\" });\n}\n\n/**\n * Persists each verified full policy bundle together with its durable head.\n * This prevents a crash or bundle-write failure from leaving a checkpoint\n * without the exact same-head payload and member-envelope evidence.\n */\nexport async function persistVerifiedPrincipalPolicyBundlesAtomically(input: {\n readonly entries: readonly VerifiedPrincipalPolicyBundleEntry[];\n readonly execSql: ExecSql;\n readonly organizationId?: string | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly updatedAt: string;\n}): Promise<void> {\n const seen = new Set<string>();\n for (const entry of input.entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key)) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `verified policy bundle batch repeats ${key}`,\n );\n }\n seen.add(key);\n }\n await Promise.all(\n input.entries.map((entry) => assertBundleMatchesVerifiedPolicy(entry)),\n );\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const persist = async (tx: ClientSQLiteTransactionScope) => {\n const policies = await validatePolicyAdvances(\n tx,\n input.entries.map((entry) => entry.policy),\n );\n for (const entry of input.entries) {\n await writePrincipalPolicyBundleInTransaction(\n tx,\n entry.bundle,\n input.updatedAt,\n input.organizationId,\n );\n await assertPrincipalPolicyBundleStoredInTransaction(tx, entry.bundle);\n }\n await writePolicyCheckpoints(\n tx,\n policies,\n input.updatedAt,\n input.organizationId,\n );\n for (const policy of policies.values()) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (\n !checkpoint ||\n checkpoint.version !== policy.version ||\n checkpoint.stateHash !== policy.stateHash\n ) {\n throw new Error(\n \"Verified principal policy checkpoint was not persisted\",\n );\n }\n }\n };\n if (input.stillCurrent) {\n await runtime.guardedTransaction(persist, input.stillCurrent, {\n behavior: \"immediate\",\n });\n return;\n }\n await runtime.transaction(persist, { behavior: \"immediate\" });\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { KeyingVerificationError } from "../../internal/crypto/index.js";
1
+ import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
2
  import { eq } from "drizzle-orm";
3
- import { principalPolicyEvidenceEntries, } from "../principals/principalPolicyEvidence.js";
3
+ import { principalPolicyEvidenceEntries } from "../principals/principalPolicyEvidence.js";
4
4
  import { organizationFounders } from "../sqlite/organizationFounderSchema.js";
5
5
  import { keyingCheckpointTables } from "../sqlite/schema.js";
6
6
  import { getClientSQLitePersistenceRuntime } from "../sqlite/sqlitePersistenceRuntime.js";
@@ -1 +1 @@
1
- {"version":3,"file":"organizationFounderPersistence.js","sourceRoot":"","sources":["organizationFounderPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAA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CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport {\n type PrincipalPolicyCheckpointEvidence,\n principalPolicyEvidenceEntries,\n} from \"../principals/principalPolicyEvidence\";\nimport { organizationFounders } from \"../sqlite/organizationFounderSchema\";\nimport { keyingCheckpointTables } from \"../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nfunction assertSameFounder(\n stored: typeof organizationFounders.$inferSelect,\n founder: typeof organizationFounders.$inferInsert,\n): void {\n if (\n stored.userId !== founder.userId ||\n stored.signingKeyFingerprint !== founder.signingKeyFingerprint ||\n stored.genesisStateHash !== founder.genesisStateHash\n )\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Organization founder conflicts with its durable genesis binding\",\n );\n}\n\nexport async function loadOrganizationFounder(\n execSql: ExecSql,\n organizationId: string,\n): Promise<typeof organizationFounders.$inferSelect | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const [stored] = await runtime.db\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, organizationId))\n .limit(1);\n return stored ?? null;\n}\n\n/** Pin verified genesis, never a later administrator or a folder's creator. */\nexport async function rememberOrganizationFounder(input: {\n readonly execSql: ExecSql;\n readonly organization: PrincipalPolicyCheckpointEvidence;\n}): Promise<void> {\n const genesis = principalPolicyEvidenceEntries(input.organization).find(\n ({ state }) => state.version === 1,\n )?.state;\n if (\n genesis?.principalType !== \"organization\" ||\n genesis.prevStateHash !== null\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization founder requires verified genesis\",\n );\n const founder = {\n organizationId: genesis.principalId,\n userId: genesis.signerUserId,\n signingKeyFingerprint: genesis.signerUserKeyFingerprint,\n genesisStateHash: genesis.stateHash,\n };\n const held = await loadOrganizationFounder(\n input.execSql,\n founder.organizationId,\n );\n if (held) {\n assertSameFounder(held, founder);\n return;\n }\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n await runtime.transaction(\n async (tx) => {\n const [stored] = await tx\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, founder.organizationId))\n .limit(1);\n if (stored) {\n assertSameFounder(stored, founder);\n return;\n }\n await tx\n .insert(organizationFounders)\n .values(founder)\n .onConflictDoNothing()\n .run();\n },\n { behavior: \"immediate\" },\n );\n}\n"]}
1
+ {"version":3,"file":"organizationFounderPersistence.js","sourceRoot":"","sources":["organizationFounderPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,8BAA8B,EAAE,MAAM,uCAAuC,CAAC;AACvF,OAAO,EAAE,oBAAoB,EAAE,MAAM,qCAAqC,CAAC;AAC3E,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AAC1D,OAAO,EAAE,iCAAiC,EAAE,MAAM,oCAAoC,CAAC;AACvF,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AAEpE,SAAS,iBAAiB,CACxB,MAAgD,EAChD,OAAiD;IAEjD,IACE,MAAM,CAAC,MAAM,KAAK,OAAO,CAAC,MAAM;QAChC,MAAM,CAAC,qBAAqB,KAAK,OAAO,CAAC,qBAAqB;QAC9D,MAAM,CAAC,gBAAgB,KAAK,OAAO,CAAC,gBAAgB;QAEpD,MAAM,IAAI,uBAAuB,CAC/B,cAAc,EACd,iEAAiE,CAClE,CAAC;AACN,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,OAAgB,EAChB,cAAsB;IAEtB,MAAM,eAAe,CAAC,OAAO,EAAE,sBAAsB,CAAC,CAAC;IACvD,MAAM,OAAO,GAAG,iCAAiC,CAAC,OAAO,CA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AE;aACtB,MAAM,EAAE;aACR,IAAI,CAAC,oBAAoB,CAAC;aAC1B,KAAK,CAAC,EAAE,CAAC,oBAAoB,CAAC,cAAc,EAAE,OAAO,CAAC,cAAc,CAAC,CAAC;aACtE,KAAK,CAAC,CAAC,CAAC,CAAC;QACZ,IAAI,MAAM,EAAE,CAAC;YACX,iBAAiB,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;YACnC,OAAO;QACT,CAAC;QACD,MAAM,EAAE;aACL,MAAM,CAAC,oBAAoB,CAAC;aAC5B,MAAM,CAAC,OAAO,CAAC;aACf,mBAAmB,EAAE;aACrB,GAAG,EAAE,CAAC;IACX,CAAC,EACD,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { principalPolicyEvidenceEntries } from \"../principals/principalPolicyEvidence\";\nimport { organizationFounders } from \"../sqlite/organizationFounderSchema\";\nimport { keyingCheckpointTables } from \"../sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\n\nfunction assertSameFounder(\n stored: typeof organizationFounders.$inferSelect,\n founder: typeof organizationFounders.$inferInsert,\n): void {\n if (\n stored.userId !== founder.userId ||\n stored.signingKeyFingerprint !== founder.signingKeyFingerprint ||\n stored.genesisStateHash !== founder.genesisStateHash\n )\n throw new KeyingVerificationError(\n \"equivocation\",\n \"Organization founder conflicts with its durable genesis binding\",\n );\n}\n\nexport async function loadOrganizationFounder(\n execSql: ExecSql,\n organizationId: string,\n): Promise<typeof organizationFounders.$inferSelect | null> {\n await ensureSqlTables(execSql, keyingCheckpointTables);\n const runtime = getClientSQLitePersistenceRuntime(execSql);\n const [stored] = await runtime.db\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, organizationId))\n .limit(1);\n return stored ?? null;\n}\n\n/** Pin verified genesis, never a later administrator or a folder's creator. */\nexport async function rememberOrganizationFounder(input: {\n readonly execSql: ExecSql;\n readonly organization: PrincipalPolicyAuthorization;\n}): Promise<void> {\n const genesis = principalPolicyEvidenceEntries(input.organization).find(\n ({ state }) => state.version === 1,\n )?.state;\n if (\n genesis?.principalType !== \"organization\" ||\n genesis.prevStateHash !== null\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Organization founder requires verified genesis\",\n );\n const founder = {\n organizationId: genesis.principalId,\n userId: genesis.signerUserId,\n signingKeyFingerprint: genesis.signerUserKeyFingerprint,\n genesisStateHash: genesis.stateHash,\n };\n const held = await loadOrganizationFounder(\n input.execSql,\n founder.organizationId,\n );\n if (held) {\n assertSameFounder(held, founder);\n return;\n }\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n await runtime.transaction(\n async (tx) => {\n const [stored] = await tx\n .select()\n .from(organizationFounders)\n .where(eq(organizationFounders.organizationId, founder.organizationId))\n .limit(1);\n if (stored) {\n assertSameFounder(stored, founder);\n return;\n }\n await tx\n .insert(organizationFounders)\n .values(founder)\n .onConflictDoNothing()\n .run();\n },\n { behavior: \"immediate\" },\n );\n}\n"]}
@@ -0,0 +1,29 @@
1
+ import { KeyingVerificationError, verifyPrincipalPolicyCheckpoint, } from "../../internal/crypto/index.js";
2
+ import { loadStoredPrincipalPolicyCheckpoint } from "./keyingCheckpointPersistence.js";
3
+ export class PrincipalAuthorizationCheckpointUnavailableError extends KeyingVerificationError {
4
+ constructor() {
5
+ super("missing_dependency", "Public authorization cannot connect to the latest durable checkpoint");
6
+ }
7
+ }
8
+ /** Historical capabilities validate trust but never advance current-policy pins. */
9
+ export async function validatePrincipalAuthorizationCheckpoints(tx, policies) {
10
+ for (const policy of policies) {
11
+ const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);
12
+ if (!checkpoint)
13
+ continue;
14
+ const matchingHead = policies.filter((other) => other.principalType === policy.principalType &&
15
+ other.principalId === policy.principalId &&
16
+ other.stateHash === policy.stateHash);
17
+ const chain = matchingHead.flatMap((other) => other.retainedHistory);
18
+ if (checkpoint.version > policy.version ||
19
+ (checkpoint.version < policy.version &&
20
+ !chain.some(({ state }) => state.version === checkpoint.version)))
21
+ throw new PrincipalAuthorizationCheckpointUnavailableError();
22
+ verifyPrincipalPolicyCheckpoint({
23
+ chain,
24
+ currentState: policy.state,
25
+ localCheckpoint: checkpoint,
26
+ });
27
+ }
28
+ }
29
+ //# sourceMappingURL=principalAuthorizationCheckpoints.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalAuthorizationCheckpoints.js","sourceRoot":"","sources":["principalAuthorizationCheckpoints.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAEpF,MAAM,OAAO,gDAAiD,SAAQ,uBAAuB;IAC3F;QACE,KAAK,CACH,oBAAoB,EACpB,sEAAsE,CACvE,CAAC;IACJ,CAAC;CACF;AAED,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,yCAAyC,CAC7D,EAAgC,EAChC,QAAqD;IAErD,KAAK,MAAM,MAAM,IAAI,QAAQ,EAAE,CAAC;QAC9B,MAAM,UAAU,GAAG,MAAM,mCAAmC,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;QACzE,IAAI,CAAC,UAAU;YAAE,SAAS;QAC1B,MAAM,YAAY,GAAG,QAAQ,CAAC,MAAM,CAClC,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,aAAa,KAAK,MAAM,CAAC,aAAa;YAC5C,KAAK,CAAC,WAAW,KAAK,MAAM,CAAC,WAAW;YACxC,KAAK,CAAC,SAAS,KAAK,MAAM,CAAC,SAAS,CACvC,CAAC;QACF,MAAM,KAAK,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,eAAe,CAAC,CAAC;QACrE,IACE,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;YACnC,CAAC,UAAU,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO;gBAClC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,CAAC,CAAC;YAEnE,MAAM,IAAI,gDAAgD,EAAE,CAAC;QAC/D,+BAA+B,CAAC;YAC9B,KAAK;YACL,YAAY,EAAE,MAAM,CAAC,KAAK;YAC1B,eAAe,EAAE,UAAU;SAC5B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicySelection,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport type { ClientSQLiteTransactionScope } from \"../sqlite/sqlitePersistenceRuntime\";\nimport { loadStoredPrincipalPolicyCheckpoint } from \"./keyingCheckpointPersistence\";\n\nexport class PrincipalAuthorizationCheckpointUnavailableError extends KeyingVerificationError {\n constructor() {\n super(\n \"missing_dependency\",\n \"Public authorization cannot connect to the latest durable checkpoint\",\n );\n }\n}\n\n/** Historical capabilities validate trust but never advance current-policy pins. */\nexport async function validatePrincipalAuthorizationCheckpoints(\n tx: ClientSQLiteTransactionScope,\n policies: readonly VerifiedPrincipalPolicySelection[],\n): Promise<void> {\n for (const policy of policies) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, policy);\n if (!checkpoint) continue;\n const matchingHead = policies.filter(\n (other) =>\n other.principalType === policy.principalType &&\n other.principalId === policy.principalId &&\n other.stateHash === policy.stateHash,\n );\n const chain = matchingHead.flatMap((other) => other.retainedHistory);\n if (\n checkpoint.version > policy.version ||\n (checkpoint.version < policy.version &&\n !chain.some(({ state }) => state.version === checkpoint.version))\n )\n throw new PrincipalAuthorizationCheckpointUnavailableError();\n verifyPrincipalPolicyCheckpoint({\n chain,\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n }\n}\n"]}
@@ -0,0 +1,27 @@
1
+ import { type VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
2
+ import { type ExecSql } from "../sqlite/sqlSchema.js";
3
+ import { type PrincipalHistoryEvidencePage } from "./principalHistoryEvidencePersistence.js";
4
+ import type { PrincipalHistoryPrefix } from "./principalHistoryPrefixPersistence.js";
5
+ import type { PrincipalHistoryStage } from "./principalHistoryStagePersistence.js";
6
+ /** Owned output of authenticated prefix extension and exact receipt verification. */
7
+ export interface AcknowledgedPrincipalCurrentPublication {
8
+ readonly policy: VerifiedPrincipalPolicyCurrent;
9
+ readonly prefix: PrincipalHistoryPrefix;
10
+ readonly previousPrefixProgress: string;
11
+ readonly stage: PrincipalHistoryStage;
12
+ readonly predecessorStage: PrincipalHistoryStage;
13
+ readonly evidence: PrincipalHistoryEvidencePage;
14
+ }
15
+ export interface AcknowledgedPrincipalCurrentRetirement {
16
+ readonly principalId: string;
17
+ readonly principalType: VerifiedPrincipalPolicyCurrent["principalType"];
18
+ readonly containerIds: readonly string[];
19
+ }
20
+ /** Store current artifacts and resumable progress in the same transaction as their pins. */
21
+ export declare function persistAcknowledgedPrincipalCurrents(input: {
22
+ readonly execSql: ExecSql;
23
+ readonly organizationId: string;
24
+ readonly entries: readonly AcknowledgedPrincipalCurrentPublication[];
25
+ readonly retirements?: readonly AcknowledgedPrincipalCurrentRetirement[] | undefined;
26
+ readonly stillCurrent: () => boolean;
27
+ }): Promise<void>;
@@ -0,0 +1,109 @@
1
+ import { KeyingVerificationError, verifyPrincipalPolicyCheckpoint, } from "../../internal/crypto/index.js";
2
+ import { eq } from "drizzle-orm";
3
+ import { assertProjectionVerificationCurrent } from "../keyingProjectionVerification/types.js";
4
+ import { principalHistoryPrefixes } from "../sqlite/principalHistoryEvidenceSchema.js";
5
+ import { principalHistoryStages } from "../sqlite/principalHistoryStageSchema.js";
6
+ import { keyingCheckpointTables, principalPolicyTables, } from "../sqlite/schema.js";
7
+ import { getClientSQLitePersistenceRuntime, } from "../sqlite/sqlitePersistenceRuntime.js";
8
+ import { ensureSqlTables } from "../sqlite/sqlSchema.js";
9
+ import { loadStoredPrincipalPolicyCheckpoint, principalPolicyKey, upsertPrincipalPolicyCheckpointInTransaction, } from "./keyingCheckpointPersistence.js";
10
+ import { storePrincipalGrantRetirements } from "./principalGrantRetirementPersistence.js";
11
+ import { writePrincipalHistoryEvidencePage, } from "./principalHistoryEvidencePersistence.js";
12
+ function assertPublicationScope(entries, organizationId) {
13
+ const seen = new Set();
14
+ for (const entry of entries) {
15
+ const key = principalPolicyKey(entry.policy);
16
+ if (seen.has(key))
17
+ throw new KeyingVerificationError("duplicate_entry", "Acknowledged current batch repeats a principal");
18
+ seen.add(key);
19
+ if (entry.prefix.organizationId !== organizationId ||
20
+ entry.stage.organizationId !== organizationId ||
21
+ entry.predecessorStage.organizationId !== organizationId ||
22
+ !entry.predecessorStage.complete ||
23
+ entry.predecessorStage.afterVersion !== entry.policy.version - 2 ||
24
+ entry.evidence.organizationId !== organizationId ||
25
+ entry.prefix.scopeId !== entry.evidence.scopeId ||
26
+ entry.prefix.version !== entry.policy.version ||
27
+ entry.stage.afterVersion !== entry.policy.version - 1 ||
28
+ !entry.stage.complete ||
29
+ entry.stage.currentJson !== entry.prefix.currentJson)
30
+ throw new KeyingVerificationError("object_mismatch", "Acknowledged current publication is outside its scope");
31
+ }
32
+ }
33
+ async function validatePublication(tx, entry) {
34
+ const checkpoint = await loadStoredPrincipalPolicyCheckpoint(tx, entry.policy);
35
+ verifyPrincipalPolicyCheckpoint({
36
+ chain: entry.policy.retainedHistory,
37
+ currentState: entry.policy.state,
38
+ localCheckpoint: checkpoint,
39
+ });
40
+ if (!checkpoint || entry.policy.version > checkpoint.version + 1)
41
+ throw new KeyingVerificationError("stale_predecessor", "Acknowledged current policy must directly extend its durable checkpoint");
42
+ const [prefix] = await tx
43
+ .select()
44
+ .from(principalHistoryPrefixes)
45
+ .where(eq(principalHistoryPrefixes.scopeId, entry.prefix.scopeId))
46
+ .limit(1);
47
+ if (prefix?.progress !== entry.previousPrefixProgress)
48
+ throw new KeyingVerificationError("stale_predecessor", "Authenticated principal prefix changed before acknowledgement");
49
+ }
50
+ /** Store current artifacts and resumable progress in the same transaction as their pins. */
51
+ export async function persistAcknowledgedPrincipalCurrents(input) {
52
+ const entries = structuredClone(input.entries);
53
+ const retirements = structuredClone(input.retirements ?? []);
54
+ const organizationId = input.organizationId;
55
+ const stillCurrent = input.stillCurrent;
56
+ assertPublicationScope(entries, organizationId);
57
+ assertProjectionVerificationCurrent(stillCurrent);
58
+ await ensureSqlTables(input.execSql, [
59
+ ...principalPolicyTables,
60
+ ...keyingCheckpointTables,
61
+ ]);
62
+ const runtime = getClientSQLitePersistenceRuntime(input.execSql);
63
+ const stored = await runtime.guardedTransaction(async (tx) => {
64
+ for (const entry of entries)
65
+ await validatePublication(tx, entry);
66
+ for (const retirement of retirements) {
67
+ const policy = entries.find((entry) => entry.policy.principalId === retirement.principalId &&
68
+ entry.policy.principalType === retirement.principalType)?.policy;
69
+ if (!policy)
70
+ throw new KeyingVerificationError("object_mismatch", "Retirement must accompany its acknowledged principal");
71
+ await storePrincipalGrantRetirements(tx, { ...retirement, policy, organizationId }, entries.map((entry) => entry.policy), organizationId);
72
+ }
73
+ for (const entry of entries) {
74
+ await writePrincipalHistoryEvidencePage(tx, entry.evidence);
75
+ // A prefix-only predecessor must keep its encrypted key envelopes
76
+ // before its reusable slot is replaced by the acknowledged successor.
77
+ await tx
78
+ .insert(principalHistoryStages)
79
+ .values(entry.predecessorStage)
80
+ .onConflictDoUpdate({
81
+ target: principalHistoryStages.id,
82
+ set: entry.predecessorStage,
83
+ setWhere: eq(principalHistoryStages.complete, false),
84
+ })
85
+ .run();
86
+ // A fully authenticated publication supersedes an in-flight stage for
87
+ // this exact head. Its other writer fails its progress CAS and resumes.
88
+ await tx
89
+ .insert(principalHistoryStages)
90
+ .values(entry.stage)
91
+ .onConflictDoUpdate({
92
+ target: principalHistoryStages.id,
93
+ set: entry.stage,
94
+ })
95
+ .run();
96
+ await tx
97
+ .insert(principalHistoryPrefixes)
98
+ .values(entry.prefix)
99
+ .onConflictDoUpdate({
100
+ target: principalHistoryPrefixes.scopeId,
101
+ set: entry.prefix,
102
+ })
103
+ .run();
104
+ await upsertPrincipalPolicyCheckpointInTransaction(tx, entry.policy.checkpoint, new Date().toISOString(), organizationId);
105
+ }
106
+ }, stillCurrent, { behavior: "immediate" });
107
+ assertProjectionVerificationCurrent(() => stored.committed);
108
+ }
109
+ //# sourceMappingURL=principalCurrentAcknowledgementPersistence.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalCurrentAcknowledgementPersistence.js","sourceRoot":"","sources":["principalCurrentAcknowledgementPersistence.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAEvB,+BAA+B,GAChC,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,EAAE,EAAE,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,mCAAmC,EAAE,MAAM,uCAAuC,CAAC;AAC5F,OAAO,EAAE,wBAAwB,EAAE,MAAM,0CAA0C,CAAC;AACpF,OAAO,EAAE,sBAAsB,EAAE,MAAM,uCAAuC,CAAC;AAC/E,OAAO,EACL,sBAAsB,EACtB,qBAAqB,GACtB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAEL,iCAAiC,GAClC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAgB,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EACL,mCAAmC,EACnC,kBAAkB,EAClB,4CAA4C,GAC7C,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,8BAA8B,EAAE,MAAM,uCAAuC,CAAC;AACvF,OAAO,EAEL,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAoB/C,SAAS,sBAAsB,CAC7B,OAA2D,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rD,CAAC;iBACD,GAAG,EAAE,CAAC;YACT,sEAAsE;YACtE,wEAAwE;YACxE,MAAM,EAAE;iBACL,MAAM,CAAC,sBAAsB,CAAC;iBAC9B,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC;iBACnB,kBAAkB,CAAC;gBAClB,MAAM,EAAE,sBAAsB,CAAC,EAAE;gBACjC,GAAG,EAAE,KAAK,CAAC,KAAK;aACjB,CAAC;iBACD,GAAG,EAAE,CAAC;YACT,MAAM,EAAE;iBACL,MAAM,CAAC,wBAAwB,CAAC;iBAChC,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC;iBACpB,kBAAkB,CAAC;gBAClB,MAAM,EAAE,wBAAwB,CAAC,OAAO;gBACxC,GAAG,EAAE,KAAK,CAAC,MAAM;aAClB,CAAC;iBACD,GAAG,EAAE,CAAC;YACT,MAAM,4CAA4C,CAChD,EAAE,EACF,KAAK,CAAC,MAAM,CAAC,UAAU,EACvB,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACxB,cAAc,CACf,CAAC;QACJ,CAAC;IACH,CAAC,EACD,YAAY,EACZ,EAAE,QAAQ,EAAE,WAAW,EAAE,CAC1B,CAAC;IACF,mCAAmC,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { eq } from \"drizzle-orm\";\nimport { assertProjectionVerificationCurrent } from \"../keyingProjectionVerification/types\";\nimport { principalHistoryPrefixes } from \"../sqlite/principalHistoryEvidenceSchema\";\nimport { principalHistoryStages } from \"../sqlite/principalHistoryStageSchema\";\nimport {\n keyingCheckpointTables,\n principalPolicyTables,\n} from \"../sqlite/schema\";\nimport {\n type ClientSQLiteTransactionScope,\n getClientSQLitePersistenceRuntime,\n} from \"../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, ensureSqlTables } from \"../sqlite/sqlSchema\";\nimport {\n loadStoredPrincipalPolicyCheckpoint,\n principalPolicyKey,\n upsertPrincipalPolicyCheckpointInTransaction,\n} from \"./keyingCheckpointPersistence\";\nimport { storePrincipalGrantRetirements } from \"./principalGrantRetirementPersistence\";\nimport {\n type PrincipalHistoryEvidencePage,\n writePrincipalHistoryEvidencePage,\n} from \"./principalHistoryEvidencePersistence\";\nimport type { PrincipalHistoryPrefix } from \"./principalHistoryPrefixPersistence\";\nimport type { PrincipalHistoryStage } from \"./principalHistoryStagePersistence\";\n\n/** Owned output of authenticated prefix extension and exact receipt verification. */\nexport interface AcknowledgedPrincipalCurrentPublication {\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly prefix: PrincipalHistoryPrefix;\n readonly previousPrefixProgress: string;\n readonly stage: PrincipalHistoryStage;\n readonly predecessorStage: PrincipalHistoryStage;\n readonly evidence: PrincipalHistoryEvidencePage;\n}\n\nexport interface AcknowledgedPrincipalCurrentRetirement {\n readonly principalId: string;\n readonly principalType: VerifiedPrincipalPolicyCurrent[\"principalType\"];\n readonly containerIds: readonly string[];\n}\n\nfunction assertPublicationScope(\n entries: readonly AcknowledgedPrincipalCurrentPublication[],\n organizationId: string,\n) {\n const seen = new Set<string>();\n for (const entry of entries) {\n const key = principalPolicyKey(entry.policy);\n if (seen.has(key))\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n \"Acknowledged current batch repeats a principal\",\n );\n seen.add(key);\n if (\n entry.prefix.organizationId !== organizationId ||\n entry.stage.organizationId !== organizationId ||\n entry.predecessorStage.organizationId !== organizationId ||\n !entry.predecessorStage.complete ||\n entry.predecessorStage.afterVersion !== entry.policy.version - 2 ||\n entry.evidence.organizationId !== organizationId ||\n entry.prefix.scopeId !== entry.evidence.scopeId ||\n entry.prefix.version !== entry.policy.version ||\n entry.stage.afterVersion !== entry.policy.version - 1 ||\n !entry.stage.complete ||\n entry.stage.currentJson !== entry.prefix.currentJson\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledged current publication is outside its scope\",\n );\n }\n}\n\nasync function validatePublication(\n tx: ClientSQLiteTransactionScope,\n entry: AcknowledgedPrincipalCurrentPublication,\n) {\n const checkpoint = await loadStoredPrincipalPolicyCheckpoint(\n tx,\n entry.policy,\n );\n verifyPrincipalPolicyCheckpoint({\n chain: entry.policy.retainedHistory,\n currentState: entry.policy.state,\n localCheckpoint: checkpoint,\n });\n if (!checkpoint || entry.policy.version > checkpoint.version + 1)\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Acknowledged current policy must directly extend its durable checkpoint\",\n );\n const [prefix] = await tx\n .select()\n .from(principalHistoryPrefixes)\n .where(eq(principalHistoryPrefixes.scopeId, entry.prefix.scopeId))\n .limit(1);\n if (prefix?.progress !== entry.previousPrefixProgress)\n throw new KeyingVerificationError(\n \"stale_predecessor\",\n \"Authenticated principal prefix changed before acknowledgement\",\n );\n}\n\n/** Store current artifacts and resumable progress in the same transaction as their pins. */\nexport async function persistAcknowledgedPrincipalCurrents(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentPublication[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const entries = structuredClone(input.entries);\n const retirements = structuredClone(input.retirements ?? []);\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n assertPublicationScope(entries, organizationId);\n assertProjectionVerificationCurrent(stillCurrent);\n await ensureSqlTables(input.execSql, [\n ...principalPolicyTables,\n ...keyingCheckpointTables,\n ]);\n const runtime = getClientSQLitePersistenceRuntime(input.execSql);\n const stored = await runtime.guardedTransaction(\n async (tx) => {\n for (const entry of entries) await validatePublication(tx, entry);\n for (const retirement of retirements) {\n const policy = entries.find(\n (entry) =>\n entry.policy.principalId === retirement.principalId &&\n entry.policy.principalType === retirement.principalType,\n )?.policy;\n if (!policy)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Retirement must accompany its acknowledged principal\",\n );\n await storePrincipalGrantRetirements(\n tx,\n { ...retirement, policy, organizationId },\n entries.map((entry) => entry.policy),\n organizationId,\n );\n }\n for (const entry of entries) {\n await writePrincipalHistoryEvidencePage(tx, entry.evidence);\n // A prefix-only predecessor must keep its encrypted key envelopes\n // before its reusable slot is replaced by the acknowledged successor.\n await tx\n .insert(principalHistoryStages)\n .values(entry.predecessorStage)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: entry.predecessorStage,\n setWhere: eq(principalHistoryStages.complete, false),\n })\n .run();\n // A fully authenticated publication supersedes an in-flight stage for\n // this exact head. Its other writer fails its progress CAS and resumes.\n await tx\n .insert(principalHistoryStages)\n .values(entry.stage)\n .onConflictDoUpdate({\n target: principalHistoryStages.id,\n set: entry.stage,\n })\n .run();\n await tx\n .insert(principalHistoryPrefixes)\n .values(entry.prefix)\n .onConflictDoUpdate({\n target: principalHistoryPrefixes.scopeId,\n set: entry.prefix,\n })\n .run();\n await upsertPrincipalPolicyCheckpointInTransaction(\n tx,\n entry.policy.checkpoint,\n new Date().toISOString(),\n organizationId,\n );\n }\n },\n stillCurrent,\n { behavior: \"immediate\" },\n );\n assertProjectionVerificationCurrent(() => stored.committed);\n}\n"]}