@tearleads/client-sdk 0.1.57 → 0.1.59

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 (414) hide show
  1. package/Tearleads.d.ts +2 -2
  2. package/Tearleads.js +1 -1
  3. package/Tearleads.js.map +1 -1
  4. package/client/blobs.d.ts +1 -1
  5. package/client/blobs.js.map +1 -1
  6. package/client/deviceFirst.js.map +1 -1
  7. package/client/identity.js +1 -1
  8. package/client/identity.js.map +1 -1
  9. package/client/index.d.ts +1 -1
  10. package/client/index.js +1 -1
  11. package/client/index.js.map +1 -1
  12. package/client/organizations/organizationAccessRestoration.js.map +1 -1
  13. package/client/organizations/organizationDataUsage.js.map +1 -1
  14. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  15. package/client/organizations/organizationMetadataProfileSync.js +1 -1
  16. package/client/organizations/organizationMetadataProfileSync.js.map +1 -1
  17. package/client/organizations/organizationReadModels.js.map +1 -1
  18. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  19. package/client/rootContainerAdoption.js.map +1 -1
  20. package/client/securityIncidents.d.ts +1 -1
  21. package/client/securityIncidents.js.map +1 -1
  22. package/client/session/sessionLoginRefusal.js.map +1 -1
  23. package/client/session/sessionRootAuthority.js.map +1 -1
  24. package/client/session/sessionTypes.d.ts +1 -1
  25. package/client/session/sessionTypes.js.map +1 -1
  26. package/client/userIdentities.d.ts +1 -1
  27. package/client/userIdentities.js.map +1 -1
  28. package/client/workflowRuntime.d.ts +2 -2
  29. package/client/workflowRuntime.js.map +1 -1
  30. package/data/blobs/createBlobStore.d.ts +1 -1
  31. package/data/blobs/createBlobStore.js.map +1 -1
  32. package/data/blobs/encryptedBlobByteSource.js +1 -1
  33. package/data/blobs/encryptedBlobByteSource.js.map +1 -1
  34. package/data/blobs/encryptedBlobEnvelope.d.ts +1 -1
  35. package/data/blobs/encryptedBlobEnvelope.js +2 -2
  36. package/data/blobs/encryptedBlobEnvelope.js.map +1 -1
  37. package/data/blobs/encryptedBlobStore.d.ts +1 -1
  38. package/data/blobs/encryptedBlobStore.js +1 -1
  39. package/data/blobs/encryptedBlobStore.js.map +1 -1
  40. package/data/blobs/memoryBlobStore.d.ts +1 -1
  41. package/data/blobs/memoryBlobStore.js +1 -1
  42. package/data/blobs/memoryBlobStore.js.map +1 -1
  43. package/data/blobs/opfsBlobStore.d.ts +1 -1
  44. package/data/blobs/opfsBlobStore.js +1 -1
  45. package/data/blobs/opfsBlobStore.js.map +1 -1
  46. package/data/containers/containerMetadataDocument.js +1 -1
  47. package/data/containers/containerMetadataDocument.js.map +1 -1
  48. package/data/containers/shared/events.js +1 -1
  49. package/data/containers/shared/events.js.map +1 -1
  50. package/data/containers/shared/heldContainerHeads.js +1 -1
  51. package/data/containers/shared/heldContainerHeads.js.map +1 -1
  52. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  53. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  54. package/data/containers/shared/principalPolicies.js +1 -1
  55. package/data/containers/shared/principalPolicies.js.map +1 -1
  56. package/data/containers/shared/readers.js +2 -2
  57. package/data/containers/shared/readers.js.map +1 -1
  58. package/data/documents/attachmentContentIdentity.js +1 -1
  59. package/data/documents/attachmentContentIdentity.js.map +1 -1
  60. package/data/documents/blob/shared/blobEnvelopeStream.js.map +1 -1
  61. package/data/documents/blob/shared/blobSourceSnapshot.d.ts +1 -1
  62. package/data/documents/blob/shared/blobSourceSnapshot.js.map +1 -1
  63. package/data/documents/blob/shared/chunkedBlobCrypto.js.map +1 -1
  64. package/data/documents/blob/shared/encryptedUploadParts.js.map +1 -1
  65. package/data/documents/blob/shared/events.js +1 -1
  66. package/data/documents/blob/shared/events.js.map +1 -1
  67. package/data/documents/blob/shared/types.d.ts +2 -2
  68. package/data/documents/blob/shared/types.js.map +1 -1
  69. package/data/documents/shared/containerKekPathHistory.js +1 -1
  70. package/data/documents/shared/containerKekPathHistory.js.map +1 -1
  71. package/data/documents/shared/containerKekPathVerification.d.ts +1 -1
  72. package/data/documents/shared/containerKekPathVerification.js +1 -1
  73. package/data/documents/shared/events.js +1 -1
  74. package/data/documents/shared/events.js.map +1 -1
  75. package/data/documents/shared/manifestBundleReaders.js +2 -2
  76. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  77. package/data/documents/shared/projection.d.ts +1 -1
  78. package/data/documents/shared/projection.js +2 -2
  79. package/data/documents/shared/projection.js.map +1 -1
  80. package/data/documents/shared/projectionContentKeys.d.ts +1 -1
  81. package/data/documents/shared/readers.js +3 -3
  82. package/data/documents/shared/readers.js.map +1 -1
  83. package/data/documents/shared/stableDocumentId.js +1 -1
  84. package/data/documents/shared/stableDocumentId.js.map +1 -1
  85. package/data/documents/shared/types.d.ts +1 -1
  86. package/data/documents/shared/types.js +1 -1
  87. package/data/{keyingCanonicalJson.js → keying/canonicalJson.js} +3 -3
  88. package/data/keying/canonicalJson.js.map +1 -0
  89. package/data/keyingProjectionVerification/bundleVerification.js +1 -1
  90. package/data/keyingProjectionVerification/bundleVerification.js.map +1 -1
  91. package/data/keyingProjectionVerification/containerAncestorCitations.js +1 -1
  92. package/data/keyingProjectionVerification/containerAncestorCitations.js.map +1 -1
  93. package/data/keyingProjectionVerification/containerManifestVerification.js +1 -1
  94. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  95. package/data/keyingProjectionVerification/documentManifestVerification.js +1 -1
  96. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  97. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js +1 -1
  98. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +1 -1
  99. package/data/keyingProjectionVerification/error.js +1 -1
  100. package/data/keyingProjectionVerification/error.js.map +1 -1
  101. package/data/keyingProjectionVerification/index.d.ts +9 -0
  102. package/data/{keyingProjectionVerification.js → keyingProjectionVerification/index.js} +8 -8
  103. package/data/keyingProjectionVerification/index.js.map +1 -0
  104. package/data/keyingProjectionVerification/principalPolicyCache.js +1 -1
  105. package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
  106. package/data/keyingProjectionVerification/principalPolicyVerification.js +1 -1
  107. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
  108. package/data/keyingProjectionVerification/readers.d.ts +1 -1
  109. package/data/keyingProjectionVerification/readers.js +3 -3
  110. package/data/keyingProjectionVerification/readers.js.map +1 -1
  111. package/data/keyingProjectionVerification/userKeyResolver.d.ts +1 -1
  112. package/data/keyingProjectionVerification/userKeyResolver.js.map +1 -1
  113. package/data/persistence/containers/containerPersistence.js +1 -1
  114. package/data/persistence/containers/containerPersistence.js.map +1 -1
  115. package/data/persistence/documents/documentDiscoveryCandidate.js +1 -1
  116. package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
  117. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +1 -1
  118. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  119. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  120. package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
  121. package/data/persistence/documents/internal/documentRows.js +1 -1
  122. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  123. package/data/persistence/principalPolicyBundleIntegrity.js +1 -1
  124. package/data/persistence/principalPolicyBundleIntegrity.js.map +1 -1
  125. package/data/persistence/principalPolicyReferenceCheckpoint.js +1 -1
  126. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +1 -1
  127. package/data/persistence/principalPolicyReferenceIndexPersistence.js +1 -1
  128. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +1 -1
  129. package/data/persistence/principalPolicyReferencePersistence.js +1 -1
  130. package/data/persistence/principalPolicyReferencePersistence.js.map +1 -1
  131. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  132. package/data/persistence/verifiedPrincipalPolicyBundle.js +1 -1
  133. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
  134. package/data/persistence/verifiedPrincipalPolicyCurrent.js +1 -1
  135. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -1
  136. package/data/principals/principalMutationJournal.js +1 -1
  137. package/data/principals/principalMutationJournal.js.map +1 -1
  138. package/data/{securityIncidents.d.ts → shared/securityIncidents.d.ts} +1 -1
  139. package/data/sqlite/documentRecordPersistence.js +1 -1
  140. package/data/sqlite/documentRecordPersistence.js.map +1 -1
  141. package/data/sync/crdtPeerSeed.d.ts +18 -0
  142. package/data/sync/originatedDocuments.d.ts +1 -1
  143. package/data/sync/originatedDocuments.js.map +1 -1
  144. package/data/sync/syncCoordinator.d.ts +1 -1
  145. package/data/sync/syncCoordinator.js.map +1 -1
  146. package/index.d.ts +4 -4
  147. package/index.js +2 -2
  148. package/index.js.map +1 -1
  149. package/package.json +1 -1
  150. package/stores/container-contents/backgroundHydration.js +1 -1
  151. package/stores/container-contents/backgroundHydration.js.map +1 -1
  152. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  153. package/stores/container-contents/containerContentsStore.js.map +1 -1
  154. package/stores/container-contents/localRefresh.js +1 -1
  155. package/stores/container-contents/localRefresh.js.map +1 -1
  156. package/stores/container-contents/remoteContainerIngestion.js +1 -1
  157. package/stores/container-contents/remoteContainerIngestion.js.map +1 -1
  158. package/stores/container-contents/remoteWriteQueue.js +1 -1
  159. package/stores/container-contents/remoteWriteQueue.js.map +1 -1
  160. package/stores/container-contents/systemContainerHydration.js +1 -1
  161. package/stores/container-contents/systemContainerHydration.js.map +1 -1
  162. package/stores/container-contents/utils.js +1 -1
  163. package/stores/container-contents/utils.js.map +1 -1
  164. package/stores/documents/documentStore/attachmentIntents.js +1 -1
  165. package/stores/documents/documentStore/attachmentIntents.js.map +1 -1
  166. package/stores/documents/documentStore/attachmentSourceUpload.js.map +1 -1
  167. package/stores/documents/documentStore/attachmentStaging.js +1 -1
  168. package/stores/documents/documentStore/attachmentStaging.js.map +1 -1
  169. package/stores/documents/documentStore/attachmentUploadLane.js.map +1 -1
  170. package/stores/documents/documentStore/persistence.js +2 -2
  171. package/stores/documents/documentStore/persistence.js.map +1 -1
  172. package/stores/documents/documentStore/state.js +1 -1
  173. package/stores/documents/documentStore/state.js.map +1 -1
  174. package/stores/documents/documentStore/storedDocument.js +1 -1
  175. package/stores/documents/documentStore/storedDocument.js.map +1 -1
  176. package/stores/documents/documentStore/syncAttachments.js.map +1 -1
  177. package/stores/documents/documentStore.d.ts +1 -1
  178. package/stores/documents/documentStore.js.map +1 -1
  179. package/stores/documents/registry.d.ts +1 -1
  180. package/stores/documents/registry.js.map +1 -1
  181. package/stores/documents/types.d.ts +1 -1
  182. package/stores/documents/types.js.map +1 -1
  183. package/stores/local-projection/registry.d.ts +1 -1
  184. package/stores/local-projection/registry.js.map +1 -1
  185. package/sync/reconciliation/serviceTypes.d.ts +1 -1
  186. package/sync/reconciliation/serviceTypes.js.map +1 -1
  187. package/sync/reconciliation/triggers.d.ts +1 -1
  188. package/sync/reconciliation/triggers.js.map +1 -1
  189. package/workflows/blobs/attachmentBindingVerification.js +2 -2
  190. package/workflows/blobs/attachmentBindingVerification.js.map +1 -1
  191. package/workflows/blobs/blobChunkDecryption.js.map +1 -1
  192. package/workflows/blobs/decrypt.d.ts +1 -1
  193. package/workflows/blobs/decrypt.js +2 -2
  194. package/workflows/blobs/decrypt.js.map +1 -1
  195. package/workflows/blobs/detach.js +2 -2
  196. package/workflows/blobs/detach.js.map +1 -1
  197. package/workflows/blobs/hydrate.d.ts +3 -3
  198. package/workflows/blobs/hydrate.js +1 -1
  199. package/workflows/blobs/hydrate.js.map +1 -1
  200. package/workflows/blobs/hydrationResults.js.map +1 -1
  201. package/workflows/blobs/index.d.ts +2 -2
  202. package/workflows/blobs/index.js +1 -1
  203. package/workflows/blobs/index.js.map +1 -1
  204. package/workflows/blobs/multipartFirstParts.js.map +1 -1
  205. package/workflows/blobs/retainedAttachmentVerification.js +1 -1
  206. package/workflows/blobs/upload.js +3 -3
  207. package/workflows/blobs/upload.js.map +1 -1
  208. package/workflows/container-contents/container-state/createAdoption.js +1 -1
  209. package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
  210. package/workflows/container-contents/container-state/createChild.js +1 -1
  211. package/workflows/container-contents/container-state/createChild.js.map +1 -1
  212. package/workflows/container-contents/container-state/createIntentSync.js +1 -1
  213. package/workflows/container-contents/container-state/createIntentSync.js.map +1 -1
  214. package/workflows/container-contents/container-state/groupGrantVerification.js +1 -1
  215. package/workflows/container-contents/container-state/moveIntentSync.js +1 -1
  216. package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
  217. package/workflows/container-contents/container-state/purgeTreeScope.js +1 -1
  218. package/workflows/container-contents/container-state/purgeTreeScope.js.map +1 -1
  219. package/workflows/container-contents/container-state/share.js +1 -1
  220. package/workflows/container-contents/documentDiscoveryInputs.js +1 -1
  221. package/workflows/container-contents/documentDiscoveryInputs.js.map +1 -1
  222. package/workflows/container-contents/documentInfo.d.ts +1 -1
  223. package/workflows/container-contents/documentInfo.js.map +1 -1
  224. package/workflows/container-contents/documentLinks.d.ts +1 -1
  225. package/workflows/container-contents/documentLinks.js +1 -1
  226. package/workflows/container-contents/documentLinks.js.map +1 -1
  227. package/workflows/container-contents/documentMoveIntentSync.js +1 -1
  228. package/workflows/container-contents/documentMoveIntentSync.js.map +1 -1
  229. package/workflows/container-contents/documentPurge.d.ts +1 -1
  230. package/workflows/container-contents/documentPurge.js +1 -1
  231. package/workflows/container-contents/documentPurge.js.map +1 -1
  232. package/workflows/container-contents/documentQueries/rows.js +1 -1
  233. package/workflows/container-contents/documentQueries/rows.js.map +1 -1
  234. package/workflows/container-contents/metadata.d.ts +1 -1
  235. package/workflows/container-contents/metadataMutationPreparation.js +1 -1
  236. package/workflows/container-contents/metadataMutationPreparation.js.map +1 -1
  237. package/workflows/container-contents/metadataRemoteSync.d.ts +1 -1
  238. package/workflows/container-contents/metadataSyncErrors.js.map +1 -1
  239. package/workflows/container-contents/projectionKeys.d.ts +1 -1
  240. package/workflows/container-contents/syncLane.d.ts +1 -1
  241. package/workflows/container-contents/syncLane.js.map +1 -1
  242. package/workflows/containers/child/carriedDescendantRekeys.js +1 -1
  243. package/workflows/containers/child/create.d.ts +1 -1
  244. package/workflows/containers/child/create.js +2 -2
  245. package/workflows/containers/child/create.js.map +1 -1
  246. package/workflows/containers/child/createProjection.js +1 -1
  247. package/workflows/containers/child/createProjection.js.map +1 -1
  248. package/workflows/containers/child/createSubmission.d.ts +2 -2
  249. package/workflows/containers/child/createSubmission.js.map +1 -1
  250. package/workflows/containers/child/move.d.ts +2 -2
  251. package/workflows/containers/child/move.js +2 -2
  252. package/workflows/containers/child/move.js.map +1 -1
  253. package/workflows/containers/child/moveWraps.js +1 -1
  254. package/workflows/containers/child/mutationRequestCore.js +1 -1
  255. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  256. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  257. package/workflows/containers/child/recite.js.map +1 -1
  258. package/workflows/containers/child/recitePlan.js +1 -1
  259. package/workflows/containers/child/recitePlan.js.map +1 -1
  260. package/workflows/containers/child/rekey.d.ts +1 -1
  261. package/workflows/containers/child/rekey.js +2 -2
  262. package/workflows/containers/child/rekey.js.map +1 -1
  263. package/workflows/containers/child/rekeyProjection.js +1 -1
  264. package/workflows/containers/child/rekeyProjection.js.map +1 -1
  265. package/workflows/containers/child/rekeyRemote.d.ts +2 -2
  266. package/workflows/containers/child/rekeyRemote.js.map +1 -1
  267. package/workflows/containers/child/revoke.d.ts +2 -2
  268. package/workflows/containers/child/revoke.js +2 -2
  269. package/workflows/containers/child/revoke.js.map +1 -1
  270. package/workflows/containers/child/rotationPrincipalPolicies.js +1 -1
  271. package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
  272. package/workflows/containers/child/share.d.ts +2 -2
  273. package/workflows/containers/child/share.js +1 -1
  274. package/workflows/containers/child/share.js.map +1 -1
  275. package/workflows/containers/child/shareAncestorRepair.js.map +1 -1
  276. package/workflows/containers/child/shareMaterialization.d.ts +1 -1
  277. package/workflows/containers/child/sharePlanCore.d.ts +1 -1
  278. package/workflows/containers/child/sharePlanCore.js +1 -1
  279. package/workflows/containers/root/create.js +1 -1
  280. package/workflows/containers/root/create.js.map +1 -1
  281. package/workflows/containers/root/initialGroupPolicy.js +1 -1
  282. package/workflows/containers/root/initialGroupPolicy.js.map +1 -1
  283. package/workflows/documents/create.d.ts +1 -1
  284. package/workflows/documents/create.js +1 -1
  285. package/workflows/documents/documentMutationPreparation.js +1 -1
  286. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  287. package/workflows/documents/historyContent.js +1 -1
  288. package/workflows/documents/historyContent.js.map +1 -1
  289. package/workflows/documents/linkSet.js +1 -1
  290. package/workflows/documents/linkSet.js.map +1 -1
  291. package/workflows/documents/linkSetAuthority.js +1 -1
  292. package/workflows/documents/linkSetBlobRewraps.js +2 -2
  293. package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
  294. package/workflows/documents/linkSetRemote.d.ts +1 -1
  295. package/workflows/documents/linkSetRemote.js +1 -1
  296. package/workflows/documents/orphanBlobReclaims.js +1 -1
  297. package/workflows/documents/orphanBlobReclaims.js.map +1 -1
  298. package/workflows/documents/projectionKeys.d.ts +1 -1
  299. package/workflows/documents/purge.d.ts +1 -1
  300. package/workflows/documents/purge.js +2 -2
  301. package/workflows/documents/purge.js.map +1 -1
  302. package/workflows/documents/readOnlySync.d.ts +1 -1
  303. package/workflows/documents/readOnlySync.js +1 -1
  304. package/workflows/documents/readOnlySync.js.map +1 -1
  305. package/workflows/documents/sync.js +1 -1
  306. package/workflows/documents/syncContainerRekeyPreparation.js +1 -1
  307. package/workflows/documents/syncLane.d.ts +1 -1
  308. package/workflows/documents/syncLane.js.map +1 -1
  309. package/workflows/documents/syncPlanIdentity.js +1 -1
  310. package/workflows/documents/syncPlanIdentity.js.map +1 -1
  311. package/workflows/documents/syncRepairAccess.js +1 -1
  312. package/workflows/documents/syncSubmittedResult.js +1 -1
  313. package/workflows/organizations/authoredPrincipalPolicyWarmer.js +1 -1
  314. package/workflows/organizations/authoredPrincipalPolicyWarmer.js.map +1 -1
  315. package/workflows/organizations/containerGrantRevocation.d.ts +2 -2
  316. package/workflows/organizations/containerGrantRevocation.js.map +1 -1
  317. package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -1
  318. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
  319. package/workflows/organizations/currentOrganizationMutationRetention.js +1 -1
  320. package/workflows/organizations/currentOrganizationMutationRetention.js.map +1 -1
  321. package/workflows/organizations/currentPolicyMutationAcknowledgement.js +1 -1
  322. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -1
  323. package/workflows/organizations/groupCreation.d.ts +1 -1
  324. package/workflows/organizations/groupCreation.js.map +1 -1
  325. package/workflows/organizations/groupMetadataAccess.d.ts +1 -1
  326. package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
  327. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  328. package/workflows/organizations/groupNameUniqueness.js.map +1 -1
  329. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -1
  330. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  331. package/workflows/organizations/groupPolicyRequests.js.map +1 -1
  332. package/workflows/organizations/index.d.ts +0 -1
  333. package/workflows/organizations/index.js +0 -1
  334. package/workflows/organizations/index.js.map +1 -1
  335. package/workflows/organizations/loadPolicyHistoryDetails.js.map +1 -1
  336. package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
  337. package/workflows/organizations/organizationProfile.js +1 -1
  338. package/workflows/organizations/organizationProfile.js.map +1 -1
  339. package/workflows/organizations/policyHistoryCache.js.map +1 -1
  340. package/workflows/organizations/principalContainerRematerialization.js +1 -1
  341. package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
  342. package/workflows/organizations/principalMutationJournalManagement.js +1 -1
  343. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -1
  344. package/workflows/organizations/principalMutationReceipt.js +1 -1
  345. package/workflows/organizations/principalMutationReceipt.js.map +1 -1
  346. package/workflows/organizations/principalPolicy.d.ts +1 -1
  347. package/workflows/organizations/principalPolicy.js.map +1 -1
  348. package/workflows/organizations/principalPolicyReceiptArtifacts.js +1 -1
  349. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -1
  350. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +4 -24
  351. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +13 -133
  352. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
  353. package/workflows/organizations/rosterProfileContainer.js +1 -1
  354. package/workflows/organizations/rosterProfileContainer.js.map +1 -1
  355. package/workflows/organizations/runtimeCurrentGroupMutation.js +1 -1
  356. package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -1
  357. package/workflows/principals/acknowledgedPrincipalCurrents.d.ts +33 -0
  358. package/workflows/principals/acknowledgedPrincipalCurrents.js +140 -0
  359. package/workflows/principals/acknowledgedPrincipalCurrents.js.map +1 -0
  360. package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.d.ts +1 -1
  361. package/workflows/{organizations → principals}/acknowledgedPrincipalPredecessor.js +1 -1
  362. package/workflows/principals/acknowledgedPrincipalPredecessor.js.map +1 -0
  363. package/workflows/principals/index.d.ts +1 -0
  364. package/workflows/principals/index.js +1 -0
  365. package/workflows/principals/index.js.map +1 -1
  366. package/workflows/{organizations → principals}/initialPrincipalCurrentPublication.js +5 -7
  367. package/workflows/principals/initialPrincipalCurrentPublication.js.map +1 -0
  368. package/workflows/principals/policyCache.d.ts +1 -1
  369. package/workflows/principals/policyCache.js +2 -2
  370. package/workflows/principals/policyCache.js.map +1 -1
  371. package/workflows/principals/principalAcknowledgementChecks.d.ts +30 -0
  372. package/workflows/principals/principalAcknowledgementChecks.js +2 -0
  373. package/workflows/principals/principalAcknowledgementChecks.js.map +1 -0
  374. package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js.map +1 -1
  375. package/workflows/{organizations → principals}/reconcileAcknowledgedPrincipalCurrent.js +2 -2
  376. package/workflows/principals/reconcileAcknowledgedPrincipalCurrent.js.map +1 -0
  377. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  378. package/workflows/principals/runtimePolicyWarmer.js +1 -1
  379. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  380. package/workflows/registration/persistRegistrationBootstrap.js +1 -1
  381. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  382. package/workflows/runtimeInput.d.ts +3 -3
  383. package/workflows/runtimeInput.js.map +1 -1
  384. package/workflows/sync/index.d.ts +2 -1
  385. package/workflows/sync/index.js +2 -1
  386. package/workflows/sync/index.js.map +1 -1
  387. package/data/keyingCanonicalJson.js.map +0 -1
  388. package/data/keyingProjectionVerification.d.ts +0 -9
  389. package/data/keyingProjectionVerification.js.map +0 -1
  390. package/workflows/organizations/acknowledgedPrincipalPredecessor.js.map +0 -1
  391. package/workflows/organizations/initialPrincipalCurrentPublication.js.map +0 -1
  392. package/workflows/organizations/reconcileAcknowledgedPrincipalCurrent.js.map +0 -1
  393. /package/data/{blobContracts.d.ts → blobs/blobContracts.d.ts} +0 -0
  394. /package/data/{blobContracts.js → blobs/blobContracts.js} +0 -0
  395. /package/data/{blobContracts.js.map → blobs/blobContracts.js.map} +0 -0
  396. /package/data/{accessLevel.js → keying/accessLevel.js} +0 -0
  397. /package/data/{accessLevel.js.map → keying/accessLevel.js.map} +0 -0
  398. /package/data/{stableUuid.js → keying/stableUuid.js} +0 -0
  399. /package/data/{stableUuid.js.map → keying/stableUuid.js.map} +0 -0
  400. /package/data/{principalPolicyStates.js → principals/principalPolicyStates.js} +0 -0
  401. /package/data/{principalPolicyStates.js.map → principals/principalPolicyStates.js.map} +0 -0
  402. /package/data/{domainScope.d.ts → shared/domainScope.d.ts} +0 -0
  403. /package/data/{domainScope.js → shared/domainScope.js} +0 -0
  404. /package/data/{domainScope.js.map → shared/domainScope.js.map} +0 -0
  405. /package/data/{errorMessage.js → shared/errorMessage.js} +0 -0
  406. /package/data/{errorMessage.js.map → shared/errorMessage.js.map} +0 -0
  407. /package/data/{recordReaders.d.ts → shared/recordReaders.d.ts} +0 -0
  408. /package/data/{recordReaders.js → shared/recordReaders.js} +0 -0
  409. /package/data/{recordReaders.js.map → shared/recordReaders.js.map} +0 -0
  410. /package/data/{securityIncidents.js → shared/securityIncidents.js} +0 -0
  411. /package/data/{securityIncidents.js.map → shared/securityIncidents.js.map} +0 -0
  412. /package/data/{crdtPeerSeed.js → sync/crdtPeerSeed.js} +0 -0
  413. /package/data/{crdtPeerSeed.js.map → sync/crdtPeerSeed.js.map} +0 -0
  414. /package/workflows/{organizations → principals}/principalCurrentPublicationSeal.js +0 -0
@@ -1,9 +1,9 @@
1
1
  import { bytesToBase64 } from "../../internal/encoding/index.js";
2
2
  import { createDocument, exportAllUpdates } from "../../internal/loro/index.js";
3
3
  export { deriveOrganizationMetadataContainerSystemSlot, deriveOrganizationRosterProfileContainerSystemSlot, } from "../../internal/validators/containerSystemSlot.js";
4
- import { getScopedPeerSeed } from "../../data/crdtPeerSeed.js";
5
4
  import { initializeStoredDocumentKind, writeStoredDocumentFields, } from "../../data/documents/documentKinds.js";
6
5
  import { DOCUMENTS_APP_KIND } from "../../data/persistence/documents/documentsPersistence.js";
6
+ import { getScopedPeerSeed } from "../../data/sync/crdtPeerSeed.js";
7
7
  export const ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME = "Roster Profiles";
8
8
  export const ROSTER_PROFILE_DOCUMENT_KIND = "contact";
9
9
  // Dedicated container for org-wide public metadata (the organization display
@@ -1 +1 @@
1
- {"version":3,"file":"rosterProfileContainer.js","sourceRoot":"","sources":["rosterProfileContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnE,OAAO,EACL,6CAA6C,EAC7C,kDAAkD,GACnD,MAAM,2CAA2C,CAA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EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACxD,CAAC,CAAC;IAEH,MAAM,aAAa,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAE5C,OAAO;QACL,aAAa;QACb,QAAQ,EAAE,aAAa,CAAC,aAAa,CAAC;KACvC,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport { createDocument, exportAllUpdates } from \"@tearleads/loro\";\n\nexport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n} from \"@tearleads/validators/containerSystemSlot\";\n\nimport { getScopedPeerSeed } from \"../../data/crdtPeerSeed\";\nimport {\n initializeStoredDocumentKind,\n writeStoredDocumentFields,\n} from \"../../data/documents/documentKinds\";\nimport { DOCUMENTS_APP_KIND } from \"../../data/persistence/documents/documentsPersistence\";\n\nexport const ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME = \"Roster Profiles\";\nexport const ROSTER_PROFILE_DOCUMENT_KIND = \"contact\";\n\n// Dedicated container for org-wide public metadata (the organization display\n// name today; logo/color later). Distinct from the Admins-scoped roster profile\n// container so it can be granted read to the reserved Members group without\n// exposing the founder's private roster PII.\nexport const ORGANIZATION_METADATA_CONTAINER_NAME = \"Organization Metadata\";\n\n// The self roster-profile nickname seeded at registration when the caller does\n// not override it. The demo host passes each pane's peer-labeled self name\n// instead (e.g. \"Peer 1 (You)\").\nexport const DEFAULT_ROSTER_PROFILE_SELF_NICKNAME = \"You\";\n\nexport function getRosterProfileDocumentLocalId(input: {\n readonly organizationId: string;\n readonly userId: string;\n}): string {\n return `org-profile:${input.organizationId}:${input.userId}`;\n}\n\nexport function buildRosterProfileDocumentPatch(input: {\n readonly encapsulationPublicKey: string;\n readonly isSelf: boolean;\n readonly userId: string;\n}): Record<string, string | undefined> {\n return {\n encapsulationPublicKey: input.encapsulationPublicKey,\n isSelf: input.isSelf ? \"1\" : \"0\",\n userId: input.userId,\n };\n}\n\nexport async function createInitializedRosterProfileDocument(input: {\n readonly encapsulationPublicKey: string;\n readonly isSelf: boolean;\n readonly nickname?: string | undefined;\n readonly userId: string;\n}): Promise<{\n readonly initialUpdate: Uint8Array;\n readonly snapshot: string;\n}> {\n const doc = await createDocument(await getScopedPeerSeed(DOCUMENTS_APP_KIND));\n initializeStoredDocumentKind(doc, ROSTER_PROFILE_DOCUMENT_KIND);\n writeStoredDocumentFields(doc, ROSTER_PROFILE_DOCUMENT_KIND, {\n ...buildRosterProfileDocumentPatch(input),\n ...(input.nickname ? { nickname: input.nickname } : {}),\n });\n\n const initialUpdate = exportAllUpdates(doc);\n\n return {\n initialUpdate,\n snapshot: bytesToBase64(initialUpdate),\n };\n}\n"]}
1
+ {"version":3,"file":"rosterProfileContainer.js","sourceRoot":"","sources":["rosterProfileContainer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnE,OAAO,EACL,6CAA6C,EAC7C,kDAAkD,GACnD,MAAM,2CAA2C,CAAC;AAEnD,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uDAAuD,CAAC;AAC3F,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEjE,MAAM,CAAC,MAAM,0CAA0C,GAAG,iBAAiB,CAAC;AAC5E,MAAM,CAAC,MAAM,4BAA4B,GAAG,SAAS,CAAC;AAEtD,6EAA6E;AAC7E,gFAAgF;AAChF,4EAA4E;AAC5E,6CAA6C;AAC7C,MAAM,CAAC,MAAM,oCAAoC,GAAG,uBAAuB,CAAC;AAE5E,+EAA+E;AAC/E,2EAA2E;AAC3E,iCAAiC;AACjC,MAAM,CAAC,MAAM,oCAAoC,GAAG,KAAK,CAAC;AAE1D,MAAM,UAAU,+BAA+B,CAAC,KAG/C;IACC,OAAO,eAAe,KAAK,CAAC,cAAc,IAAI,KAAK,CAAC,MAAM,EAAE,CAAC;AAC/D,CAAC;AAED,MAAM,UAAU,+BAA+B,CAAC,KAI/C;IACC,OAAO;QACL,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;QACpD,MAAM,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG;QAChC,MAAM,EAAE,KAAK,CAAC,MAAM;KACrB,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAAC,KAK5D;IAIC,MAAM,GAAG,GAAG,MAAM,cAAc,CAAC,MAAM,iBAAiB,CAAC,kBAAkB,CAAC,CAAC,CAAC;IAC9E,4BAA4B,CAAC,GAAG,EAAE,4BAA4B,CAAC,CAAC;IAChE,yBAAyB,CAAC,GAAG,EAAE,4BAA4B,EAAE;QAC3D,GAAG,+BAA+B,CAAC,KAAK,CAAC;QACzC,GAAG,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;KACxD,CAAC,CAAC;IAEH,MAAM,aAAa,GAAG,gBAAgB,CAAC,GAAG,CAAC,CAAC;IAE5C,OAAO;QACL,aAAa;QACb,QAAQ,EAAE,aAAa,CAAC,aAAa,CAAC;KACvC,CAAC;AACJ,CAAC","sourcesContent":["import { bytesToBase64 } from \"@tearleads/encoding\";\nimport { createDocument, exportAllUpdates } from \"@tearleads/loro\";\n\nexport {\n deriveOrganizationMetadataContainerSystemSlot,\n deriveOrganizationRosterProfileContainerSystemSlot,\n} from \"@tearleads/validators/containerSystemSlot\";\n\nimport {\n initializeStoredDocumentKind,\n writeStoredDocumentFields,\n} from \"../../data/documents/documentKinds\";\nimport { DOCUMENTS_APP_KIND } from \"../../data/persistence/documents/documentsPersistence\";\nimport { getScopedPeerSeed } from \"../../data/sync/crdtPeerSeed\";\n\nexport const ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME = \"Roster Profiles\";\nexport const ROSTER_PROFILE_DOCUMENT_KIND = \"contact\";\n\n// Dedicated container for org-wide public metadata (the organization display\n// name today; logo/color later). Distinct from the Admins-scoped roster profile\n// container so it can be granted read to the reserved Members group without\n// exposing the founder's private roster PII.\nexport const ORGANIZATION_METADATA_CONTAINER_NAME = \"Organization Metadata\";\n\n// The self roster-profile nickname seeded at registration when the caller does\n// not override it. The demo host passes each pane's peer-labeled self name\n// instead (e.g. \"Peer 1 (You)\").\nexport const DEFAULT_ROSTER_PROFILE_SELF_NICKNAME = \"You\";\n\nexport function getRosterProfileDocumentLocalId(input: {\n readonly organizationId: string;\n readonly userId: string;\n}): string {\n return `org-profile:${input.organizationId}:${input.userId}`;\n}\n\nexport function buildRosterProfileDocumentPatch(input: {\n readonly encapsulationPublicKey: string;\n readonly isSelf: boolean;\n readonly userId: string;\n}): Record<string, string | undefined> {\n return {\n encapsulationPublicKey: input.encapsulationPublicKey,\n isSelf: input.isSelf ? \"1\" : \"0\",\n userId: input.userId,\n };\n}\n\nexport async function createInitializedRosterProfileDocument(input: {\n readonly encapsulationPublicKey: string;\n readonly isSelf: boolean;\n readonly nickname?: string | undefined;\n readonly userId: string;\n}): Promise<{\n readonly initialUpdate: Uint8Array;\n readonly snapshot: string;\n}> {\n const doc = await createDocument(await getScopedPeerSeed(DOCUMENTS_APP_KIND));\n initializeStoredDocumentKind(doc, ROSTER_PROFILE_DOCUMENT_KIND);\n writeStoredDocumentFields(doc, ROSTER_PROFILE_DOCUMENT_KIND, {\n ...buildRosterProfileDocumentPatch(input),\n ...(input.nickname ? { nickname: input.nickname } : {}),\n });\n\n const initialUpdate = exportAllUpdates(doc);\n\n return {\n initialUpdate,\n snapshot: bytesToBase64(initialUpdate),\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
2
2
  import { scopedGroupHistoryProtection } from "../../data/principals/principalHistoryScopeProtection.js";
3
3
  import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
4
- import { captureAcknowledgedPrincipalPredecessor } from "./acknowledgedPrincipalPredecessor.js";
4
+ import { captureAcknowledgedPrincipalPredecessor } from "../principals/acknowledgedPrincipalPredecessor.js";
5
5
  import { resolveCurrentGroupMutationReferences } from "./currentGroupMutationReferences.js";
6
6
  import { loadCurrentGroupPolicyMutationContext } from "./currentGroupPolicyMutationContext.js";
7
7
  import { createCurrentPrincipalMutationLease } from "./currentPrincipalMutationLease.js";
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeCurrentGroupMutation.js","sourceRoot":"","sources":["runtimeCurrentGroupMutation.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,4BAA4B,EAAE,MAAM,uDAAuD,CAAC;AACrG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAGvG,OAAO,EAAE,uCAAuC,EAAE,MAAM,oCAAoC,CAAC;AAC7F,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EAAE,qCAAqC,EAAE,MAAM,qCAAqC,CAAC;AAC5F,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AAEtF,OAAO,EAEL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AA4C/C,sFAAsF;AACtF,MAAM,UAAU,iCAAiC,CAAC,OAAwB;IACxE,MAAM,KAAK,GAAG,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC3D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,EACV,KAAoB,EACpB,IAAiE,EACrD,EAAE;QACd,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;QACrB,OAAO,KAAK,CACV,KAAK,CAAC,YAAY,EAClB,K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c,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO,EAAE;gBACP,GAAG,CAAC,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC;gBACnC;oBACE,QAAQ,EAAE,aAAa;oBACvB,WAAW,EAAE,gBAAgB;oBAC7B,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,WAAW;iBACvC;gBACD;oBACE,QAAQ,EAAE,iBAAiB;oBAC3B,WAAW,EAAE,oBAAoB;oBACjC,OAAO,EAAE,OAAO,CAAC,mBAAmB;oBACpC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,kBAAkB;iBAC9C;aACF;YACD,WAAW,EAAE;gBACX,GAAG,CAAC,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;oBAClD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;oBAC5C,aAAa,EAAE,OAAgB;oBAC/B,YAAY,EAAE,KAAK,CAAC,mBAAmB,IAAI,EAAE;iBAC9C,CAAC,CAAC;gBACH;oBACE,WAAW,EAAE,KAAK,CAAC,OAAO;oBAC1B,aAAa,EAAE,OAAO;oBACtB,YAAY,EAAE,OAAO,CAAC,mBAAmB,IAAI,EAAE;iBAChD;aACF;YACD,YAAY,EAAE,OAAO,CAAC,YAAY;SACnC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO;QACL,cAAc,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE;QAC1E,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { CurrentPolicyReferenceResolver } from \"../../data/principals/currentPolicyReferenceResolver\";\nimport { scopedGroupHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyPageReader } from \"../principals/principalPolicyHistoryReader\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../principals/runtimePolicyRecovery\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"./acknowledgedPrincipalPredecessor\";\nimport { resolveCurrentGroupMutationReferences } from \"./currentGroupMutationReferences\";\nimport { loadCurrentGroupPolicyMutationContext } from \"./currentGroupPolicyMutationContext\";\nimport { createCurrentPrincipalMutationLease } from \"./currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\ntype MutationRuntime = PrincipalPolicyRecoveryRuntime & {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] &\n Pick<PrincipalMutationRecoveryApi, \"recoverPendingPrincipalMutation\">;\n};\n\ntype CurrentMutationContext = Awaited<\n ReturnType<typeof loadCurrentGroupPolicyMutationContext>\n>;\n\nexport type RuntimeCurrentGroupMutationContext = CurrentMutationContext & {\n readonly resolveAuthoredPolicyReferences: CurrentPolicyReferenceResolver;\n readonly loadGroup: (\n groupId: string,\n ) => Promise<RuntimeCurrentGroupMutationContext>;\n readonly groupRetention: Pick<\n AcknowledgedPrincipalCurrentInput,\n \"recovery\" | \"predecessor\"\n >;\n readonly retainAcknowledged: (\n receipt: CurrentMutationReceipt,\n ) => Promise<void>;\n};\n\ninterface CurrentMutationReceipt {\n readonly additionalGroups?:\n | readonly (AcknowledgedPrincipalCurrentInput & {\n readonly retiredContainerIds?: readonly string[] | undefined;\n })[]\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly response: CommitOrganizationGroupPolicyResponse;\n readonly retiredContainerIds?: readonly string[] | undefined;\n}\n\ninterface MutationInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/** Keep private prefix custody inside the entire mutation and its acknowledgement. */\nexport function createRuntimeCurrentGroupMutation(runtime: MutationRuntime) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: MutationInput,\n work: (context: RuntimeCurrentGroupMutationContext) => Promise<T>,\n ): Promise<T> => {\n input = { ...input };\n return lease(\n input.stillCurrent,\n async ({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery,\n }) => {\n const loadGroup = async (\n groupId: string,\n ): Promise<RuntimeCurrentGroupMutationContext> => {\n const context = await loadCurrentGroupPolicyMutationContext({\n ...input,\n groupId,\n execSql: runtime.infra.execSql,\n resolveCurrentPolicy,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n stillCurrent,\n });\n const retention = await createCurrentMutationRetention(\n runtime,\n { ...input, groupId },\n context,\n protection,\n historyReader,\n directoryRecovery(context.organizationCurrent.current),\n );\n return {\n ...context,\n ...retention,\n loadGroup,\n resolveAuthoredPolicyReferences: (current, references) =>\n resolveCurrentGroupMutationReferences({\n current,\n predecessor: context.verifiedCurrentPolicy,\n references,\n readPredecessorReference: context.readPredecessorReference,\n stillCurrent: context.stillCurrent,\n }),\n };\n };\n const context = await loadGroup(input.groupId);\n const result = await work(context);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function createCurrentMutationRetention(\n runtime: MutationRuntime,\n input: MutationInput,\n context: CurrentMutationContext,\n protection: PrincipalPolicyHistoryProgressOptions,\n historyReader: PrincipalPolicyPageReader,\n directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"],\n) {\n const common = {\n historyReader,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n const groupRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"] = {\n ...common,\n expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),\n protection: context.isOrganizationAdminsGroup\n ? protection\n : scopedGroupHistoryProtection(\n protection,\n input.organizationId,\n context.adminGroupId,\n ),\n historyVerification: context.isOrganizationAdminsGroup\n ? \"direct-admins\"\n : \"standard\",\n ...(context.isOrganizationAdminsGroup\n ? {}\n : { loadExternalAuthority: async () => context.externalAuthority }),\n };\n const capture = (recovery: AcknowledgedPrincipalCurrentInput[\"recovery\"]) =>\n captureAcknowledgedPrincipalPredecessor({\n ...recovery,\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: context.stillCurrent,\n });\n const groupPredecessor = await capture(groupRecovery);\n const directoryPredecessor = await capture(directoryRecovery);\n const retainAcknowledged = async (\n receipt: CurrentMutationReceipt,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(context.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n entries: [\n ...(receipt.additionalGroups ?? []),\n {\n recovery: groupRecovery,\n predecessor: groupPredecessor,\n request: receipt.request,\n response: receipt.response.groupPolicy,\n },\n {\n recovery: directoryRecovery,\n predecessor: directoryPredecessor,\n request: receipt.organizationRequest,\n response: receipt.response.organizationPolicy,\n },\n ],\n retirements: [\n ...(receipt.additionalGroups ?? []).map((entry) => ({\n principalId: entry.request.state.principalId,\n principalType: \"group\" as const,\n containerIds: entry.retiredContainerIds ?? [],\n })),\n {\n principalId: input.groupId,\n principalType: \"group\",\n containerIds: receipt.retiredContainerIds ?? [],\n },\n ],\n stillCurrent: context.stillCurrent,\n });\n };\n return {\n groupRetention: { recovery: groupRecovery, predecessor: groupPredecessor },\n retainAcknowledged,\n };\n}\n"]}
1
+ {"version":3,"file":"runtimeCurrentGroupMutation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AAW,EAAE;gBACX,GAAG,CAAC,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;oBAClD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;oBAC5C,aAAa,EAAE,OAAgB;oBAC/B,YAAY,EAAE,KAAK,CAAC,mBAAmB,IAAI,EAAE;iBAC9C,CAAC,CAAC;gBACH;oBACE,WAAW,EAAE,KAAK,CAAC,OAAO;oBAC1B,aAAa,EAAE,OAAO;oBACtB,YAAY,EAAE,OAAO,CAAC,mBAAmB,IAAI,EAAE;iBAChD;aACF;YACD,YAAY,EAAE,OAAO,CAAC,YAAY;SACnC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO;QACL,cAAc,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE;QAC1E,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { CurrentPolicyReferenceResolver } from \"../../data/principals/currentPolicyReferenceResolver\";\nimport { scopedGroupHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"../principals/acknowledgedPrincipalPredecessor\";\nimport type { PrincipalPolicyPageReader } from \"../principals/principalPolicyHistoryReader\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../principals/runtimePolicyRecovery\";\nimport { resolveCurrentGroupMutationReferences } from \"./currentGroupMutationReferences\";\nimport { loadCurrentGroupPolicyMutationContext } from \"./currentGroupPolicyMutationContext\";\nimport { createCurrentPrincipalMutationLease } from \"./currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\ntype MutationRuntime = PrincipalPolicyRecoveryRuntime & {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] &\n Pick<PrincipalMutationRecoveryApi, \"recoverPendingPrincipalMutation\">;\n};\n\ntype CurrentMutationContext = Awaited<\n ReturnType<typeof loadCurrentGroupPolicyMutationContext>\n>;\n\nexport type RuntimeCurrentGroupMutationContext = CurrentMutationContext & {\n readonly resolveAuthoredPolicyReferences: CurrentPolicyReferenceResolver;\n readonly loadGroup: (\n groupId: string,\n ) => Promise<RuntimeCurrentGroupMutationContext>;\n readonly groupRetention: Pick<\n AcknowledgedPrincipalCurrentInput,\n \"recovery\" | \"predecessor\"\n >;\n readonly retainAcknowledged: (\n receipt: CurrentMutationReceipt,\n ) => Promise<void>;\n};\n\ninterface CurrentMutationReceipt {\n readonly additionalGroups?:\n | readonly (AcknowledgedPrincipalCurrentInput & {\n readonly retiredContainerIds?: readonly string[] | undefined;\n })[]\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly response: CommitOrganizationGroupPolicyResponse;\n readonly retiredContainerIds?: readonly string[] | undefined;\n}\n\ninterface MutationInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/** Keep private prefix custody inside the entire mutation and its acknowledgement. */\nexport function createRuntimeCurrentGroupMutation(runtime: MutationRuntime) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: MutationInput,\n work: (context: RuntimeCurrentGroupMutationContext) => Promise<T>,\n ): Promise<T> => {\n input = { ...input };\n return lease(\n input.stillCurrent,\n async ({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery,\n }) => {\n const loadGroup = async (\n groupId: string,\n ): Promise<RuntimeCurrentGroupMutationContext> => {\n const context = await loadCurrentGroupPolicyMutationContext({\n ...input,\n groupId,\n execSql: runtime.infra.execSql,\n resolveCurrentPolicy,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n stillCurrent,\n });\n const retention = await createCurrentMutationRetention(\n runtime,\n { ...input, groupId },\n context,\n protection,\n historyReader,\n directoryRecovery(context.organizationCurrent.current),\n );\n return {\n ...context,\n ...retention,\n loadGroup,\n resolveAuthoredPolicyReferences: (current, references) =>\n resolveCurrentGroupMutationReferences({\n current,\n predecessor: context.verifiedCurrentPolicy,\n references,\n readPredecessorReference: context.readPredecessorReference,\n stillCurrent: context.stillCurrent,\n }),\n };\n };\n const context = await loadGroup(input.groupId);\n const result = await work(context);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function createCurrentMutationRetention(\n runtime: MutationRuntime,\n input: MutationInput,\n context: CurrentMutationContext,\n protection: PrincipalPolicyHistoryProgressOptions,\n historyReader: PrincipalPolicyPageReader,\n directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"],\n) {\n const common = {\n historyReader,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n const groupRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"] = {\n ...common,\n expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),\n protection: context.isOrganizationAdminsGroup\n ? protection\n : scopedGroupHistoryProtection(\n protection,\n input.organizationId,\n context.adminGroupId,\n ),\n historyVerification: context.isOrganizationAdminsGroup\n ? \"direct-admins\"\n : \"standard\",\n ...(context.isOrganizationAdminsGroup\n ? {}\n : { loadExternalAuthority: async () => context.externalAuthority }),\n };\n const capture = (recovery: AcknowledgedPrincipalCurrentInput[\"recovery\"]) =>\n captureAcknowledgedPrincipalPredecessor({\n ...recovery,\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: context.stillCurrent,\n });\n const groupPredecessor = await capture(groupRecovery);\n const directoryPredecessor = await capture(directoryRecovery);\n const retainAcknowledged = async (\n receipt: CurrentMutationReceipt,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(context.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n entries: [\n ...(receipt.additionalGroups ?? []),\n {\n recovery: groupRecovery,\n predecessor: groupPredecessor,\n request: receipt.request,\n response: receipt.response.groupPolicy,\n },\n {\n recovery: directoryRecovery,\n predecessor: directoryPredecessor,\n request: receipt.organizationRequest,\n response: receipt.response.organizationPolicy,\n },\n ],\n retirements: [\n ...(receipt.additionalGroups ?? []).map((entry) => ({\n principalId: entry.request.state.principalId,\n principalType: \"group\" as const,\n containerIds: entry.retiredContainerIds ?? [],\n })),\n {\n principalId: input.groupId,\n principalType: \"group\",\n containerIds: receipt.retiredContainerIds ?? [],\n },\n ],\n stillCurrent: context.stillCurrent,\n });\n };\n return {\n groupRetention: { recovery: groupRecovery, predecessor: groupPredecessor },\n retainAcknowledged,\n };\n}\n"]}
@@ -0,0 +1,33 @@
1
+ import { type VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
2
+ import type { PutPrincipalPolicyRequest } from "../../internal/validators/request/index.js";
3
+ import type { PrincipalPolicyMutationResponse } from "../../internal/validators/response/index.js";
4
+ import { type AcknowledgedPrincipalCurrentRetirement } from "../../data/persistence/principalCurrentAcknowledgementPersistence.js";
5
+ import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
6
+ import { type AcknowledgedPrincipalPredecessor } from "./acknowledgedPrincipalPredecessor.js";
7
+ import type { PrincipalAcknowledgementChecks } from "./principalAcknowledgementChecks.js";
8
+ import type { RecoverPrincipalPolicyHistoryOptions } from "./principalHistoryRecoveryTypes.js";
9
+ export interface AcknowledgedPrincipalCurrentInput {
10
+ /** Capture before submitting the mutation; null only for a new group. */
11
+ readonly predecessor: AcknowledgedPrincipalPredecessor | null;
12
+ /** Only a newly authored group at version one; never skips a predecessor. */
13
+ readonly initialGroup?: boolean | undefined;
14
+ /** The same scoped protection and verification mode used to recover the predecessor. */
15
+ readonly recovery: Omit<RecoverPrincipalPolicyHistoryOptions, "execSql" | "organizationId" | "stillCurrent">;
16
+ readonly request: PutPrincipalPolicyRequest;
17
+ readonly response: PrincipalPolicyMutationResponse;
18
+ }
19
+ /** The acknowledged currents of one mutation, recorded together. */
20
+ export interface AcknowledgedPrincipalCurrentBatch {
21
+ readonly execSql: ExecSql;
22
+ readonly organizationId: string;
23
+ readonly entries: readonly AcknowledgedPrincipalCurrentInput[];
24
+ readonly retirements?: readonly AcknowledgedPrincipalCurrentRetirement[] | undefined;
25
+ readonly stillCurrent: () => boolean;
26
+ }
27
+ /**
28
+ * Extend authenticated local progress and retain exact acknowledged artifacts
29
+ * atomically with pins, once `checks` accept each acknowledgement.
30
+ */
31
+ export declare function recordAcknowledgedPrincipalCurrents(input: AcknowledgedPrincipalCurrentBatch & {
32
+ readonly checks: PrincipalAcknowledgementChecks;
33
+ }): Promise<VerifiedPrincipalPolicyCurrent[]>;
@@ -0,0 +1,140 @@
1
+ import { KeyingVerificationError, } from "../../internal/crypto/index.js";
2
+ import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
3
+ import { PrincipalAcknowledgementChangedError, persistAcknowledgedPrincipalCurrents, } from "../../data/persistence/principalCurrentAcknowledgementPersistence.js";
4
+ import { preparePrincipalHistoryEvidencePage } from "../../data/persistence/principalHistoryEvidencePersistence.js";
5
+ import { ownPrincipalHistoryProtection } from "../../data/principals/principalHistoryProtection.js";
6
+ import { restoreAcknowledgedPrincipalPredecessor, } from "./acknowledgedPrincipalPredecessor.js";
7
+ import { prepareInitialGroupCurrentPublication } from "./initialPrincipalCurrentPublication.js";
8
+ import { collectPrincipalPolicySignerPublicKeys } from "./policyVerification.js";
9
+ import { sealPrincipalCurrentPublication, sealPrincipalCurrentStage, } from "./principalCurrentPublicationSeal.js";
10
+ import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationContext, } from "./principalHistoryRecoveryVerification.js";
11
+ import { reconcileAcknowledgedPrincipalCurrent } from "./reconcileAcknowledgedPrincipalCurrent.js";
12
+ async function preparePublication(options, request, response, predecessor, checks) {
13
+ options = {
14
+ ...options,
15
+ protection: {
16
+ ...options.protection,
17
+ context: principalHistoryVerificationContext(options),
18
+ },
19
+ };
20
+ const current = () => !options.signal?.aborted && options.stillCurrent();
21
+ assertProjectionVerificationCurrent(current);
22
+ const { scopeId, saved, artifacts, verifier, previous, predecessorIndexRootHash, } = await restoreAcknowledgedPrincipalPredecessor(options, predecessor);
23
+ const expectedHead = await checks.authoredHead(request);
24
+ checks.assertReceipt({ expectedHead, request, response });
25
+ const keys = await collectPrincipalPolicySignerPublicKeys({
26
+ bundle: { currentState: response.currentState, previousStates: [] },
27
+ resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,
28
+ });
29
+ assertProjectionVerificationCurrent(current);
30
+ if ("error" in keys)
31
+ throw new KeyingVerificationError(keys.error === "not-found" ? "missing_dependency" : "signer_mismatch", "Acknowledged principal signer could not be authenticated");
32
+ const externalAuthority = await options.loadExternalAuthority?.(request.state.externalAuthority ? [request.state.externalAuthority] : []);
33
+ assertProjectionVerificationCurrent(current);
34
+ const policy = await checks.acknowledgeSuccessor({
35
+ verifiedCurrentPolicy: previous,
36
+ expectedHead,
37
+ request,
38
+ response: response.currentState,
39
+ signerPublicKeys: keys.signerPublicKeys,
40
+ externalAuthority,
41
+ stillCurrent: current,
42
+ });
43
+ const entry = {
44
+ state: response.currentState,
45
+ projection: response.currentProjection,
46
+ grants: response.currentGrants,
47
+ };
48
+ assertPrincipalHistoryVerificationMode(options, [entry]);
49
+ const predecessorStage = await sealPrincipalCurrentStage(options, previous.state, verifier, artifacts);
50
+ const appended = await verifier.append({
51
+ entries: [entry],
52
+ signerPublicKeys: keys.signerPublicKeys,
53
+ ...(externalAuthority ? { externalAuthority } : {}),
54
+ });
55
+ if (!appended.ok)
56
+ throw appended.error;
57
+ const sealed = await sealPrincipalCurrentPublication(options, scopeId, expectedHead, verifier, response);
58
+ assertProjectionVerificationCurrent(current);
59
+ return {
60
+ policy,
61
+ previousPrefixProgress: saved.progress,
62
+ predecessorStage,
63
+ predecessorIndexRootHash,
64
+ ...sealed,
65
+ evidence: await preparePrincipalHistoryEvidencePage({
66
+ indexRootHash: appended.value.indexRootHash,
67
+ scopeId,
68
+ organizationId: options.organizationId,
69
+ entries: [entry],
70
+ nodes: appended.value.indexNodes,
71
+ }),
72
+ };
73
+ }
74
+ /**
75
+ * Extend authenticated local progress and retain exact acknowledged artifacts
76
+ * atomically with pins, once `checks` accept each acknowledgement.
77
+ */
78
+ export async function recordAcknowledgedPrincipalCurrents(input) {
79
+ const checks = input.checks;
80
+ const execSql = input.execSql;
81
+ const organizationId = input.organizationId;
82
+ const stillCurrent = input.stillCurrent;
83
+ const retirements = structuredClone(input.retirements ?? []);
84
+ const entries = [];
85
+ try {
86
+ assertProjectionVerificationCurrent(stillCurrent);
87
+ for (const entry of input.entries)
88
+ entries.push({
89
+ initialGroup: entry.initialGroup === true,
90
+ predecessor: structuredClone(entry.predecessor),
91
+ request: structuredClone(entry.request),
92
+ response: structuredClone(entry.response),
93
+ options: {
94
+ ...entry.recovery,
95
+ expectedHead: structuredClone(entry.recovery.expectedHead),
96
+ protection: ownPrincipalHistoryProtection(entry.recovery.protection),
97
+ execSql,
98
+ organizationId,
99
+ stillCurrent,
100
+ },
101
+ });
102
+ const publications = [];
103
+ for (const entry of entries)
104
+ publications.push(await (entry.initialGroup
105
+ ? prepareInitialGroupCurrentPublication
106
+ : preparePublication)(entry.options, entry.request, entry.response, entry.predecessor, checks));
107
+ checks.assertDirectoryBindings(organizationId, entries.map(({ response }) => response));
108
+ for (let attempt = 0;; attempt += 1) {
109
+ const reconciled = [];
110
+ for (const [index, publication] of publications.entries()) {
111
+ const entry = entries[index];
112
+ if (!entry)
113
+ throw new Error("Missing acknowledgement entry");
114
+ reconciled.push(await reconcileAcknowledgedPrincipalCurrent(entry.options, publication));
115
+ }
116
+ try {
117
+ await persistAcknowledgedPrincipalCurrents({
118
+ execSql,
119
+ organizationId,
120
+ entries: reconciled,
121
+ retirements,
122
+ stillCurrent: () => stillCurrent() &&
123
+ entries.every((entry) => !entry.options.signal?.aborted),
124
+ });
125
+ break;
126
+ }
127
+ catch (error) {
128
+ if (!(error instanceof PrincipalAcknowledgementChangedError) ||
129
+ attempt >= 7)
130
+ throw error;
131
+ }
132
+ }
133
+ return publications.map(({ policy }) => policy);
134
+ }
135
+ finally {
136
+ for (const entry of entries)
137
+ entry.options.protection.localKey.fill(0);
138
+ }
139
+ }
140
+ //# sourceMappingURL=acknowledgedPrincipalCurrents.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"acknowledgedPrincipalCurrents.js","sourceRoot":"","sources":["acknowledgedPrincipalCurrents.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAGL,oCAAoC,EACpC,oCAAoC,GACrC,MAAM,mEAAmE,CAAC;AAC3E,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AAEjG,OAAO,EAEL,uCAAuC,GACxC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,qCAAqC,EAAE,MAAM,sCAAsC,CAAC;AAC7F,OAAO,EAAE,sCAAsC,EAAE,MAAM,sBAAsB,CAAC;AAE9E,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,GAC1B,MAAM,mCAAmC,CAAC;AAE3C,OAAO,EACL,sCAAsC,EACtC,mCAAmC,GACpC,MAAM,wCAAwC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,CAAC;iBAC3D,CAAC,CAAC;gBACH,MAAM;YACR,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,IACE,CAAC,CAAC,KAAK,YAAY,oCAAoC,CAAC;oBACxD,OAAO,IAAI,CAAC;oBAEZ,MAAM,KAAK,CAAC;YAChB,CAAC;QACH,CAAC;QACD,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC;YAAS,CAAC;QACT,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n PrincipalAcknowledgementChangedError,\n persistAcknowledgedPrincipalCurrents,\n} from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n type AcknowledgedPrincipalPredecessor,\n restoreAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgedPrincipalPredecessor\";\nimport { prepareInitialGroupCurrentPublication } from \"./initialPrincipalCurrentPublication\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\nimport { reconcileAcknowledgedPrincipalCurrent } from \"./reconcileAcknowledgedPrincipalCurrent\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** Capture before submitting the mutation; null only for a new group. */\n readonly predecessor: AcknowledgedPrincipalPredecessor | null;\n /** Only a newly authored group at version one; never skips a predecessor. */\n readonly initialGroup?: boolean | undefined;\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const {\n scopeId,\n saved,\n artifacts,\n verifier,\n previous,\n predecessorIndexRootHash,\n } = await restoreAcknowledgedPrincipalPredecessor(options, predecessor);\n const expectedHead = await checks.authoredHead(request);\n checks.assertReceipt({ expectedHead, request, response });\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { currentState: response.currentState, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(current);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(current);\n const policy = await checks.acknowledgeSuccessor({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: response.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent: current,\n });\n const entry = {\n state: response.currentState,\n projection: response.currentProjection,\n grants: response.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n response,\n );\n assertProjectionVerificationCurrent(current);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n predecessorIndexRootHash,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** The acknowledged currents of one mutation, recorded together. */\nexport interface AcknowledgedPrincipalCurrentBatch {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/**\n * Extend authenticated local progress and retain exact acknowledged artifacts\n * atomically with pins, once `checks` accept each acknowledgement.\n */\nexport async function recordAcknowledgedPrincipalCurrents(\n input: AcknowledgedPrincipalCurrentBatch & {\n readonly checks: PrincipalAcknowledgementChecks;\n },\n): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const checks = input.checks;\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: {\n initialGroup: boolean;\n request: PutPrincipalPolicyRequest;\n response: PrincipalPolicyMutationResponse;\n options: RecoverPrincipalPolicyHistoryOptions;\n predecessor: AcknowledgedPrincipalPredecessor | null;\n }[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n for (const entry of input.entries)\n entries.push({\n initialGroup: entry.initialGroup === true,\n predecessor: structuredClone(entry.predecessor),\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const entry of entries)\n publications.push(\n await (entry.initialGroup\n ? prepareInitialGroupCurrentPublication\n : preparePublication)(\n entry.options,\n entry.request,\n entry.response,\n entry.predecessor,\n checks,\n ),\n );\n checks.assertDirectoryBindings(\n organizationId,\n entries.map(({ response }) => response),\n );\n for (let attempt = 0; ; attempt += 1) {\n const reconciled = [];\n for (const [index, publication] of publications.entries()) {\n const entry = entries[index];\n if (!entry) throw new Error(\"Missing acknowledgement entry\");\n reconciled.push(\n await reconcileAcknowledgedPrincipalCurrent(\n entry.options,\n publication,\n ),\n );\n }\n try {\n await persistAcknowledgedPrincipalCurrents({\n execSql,\n organizationId,\n entries: reconciled,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n break;\n } catch (error) {\n if (\n !(error instanceof PrincipalAcknowledgementChangedError) ||\n attempt >= 7\n )\n throw error;\n }\n }\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { type PrincipalHistoryPrefix } from "../../data/persistence/principalHistoryPrefixPersistence.js";
2
- import type { RecoverPrincipalPolicyHistoryOptions } from "../principals/principalHistoryRecoveryTypes.js";
2
+ import type { RecoverPrincipalPolicyHistoryOptions } from "./principalHistoryRecoveryTypes.js";
3
3
  /** Sealed predecessor evidence, owned by a mutation before its request is sent. */
4
4
  export type AcknowledgedPrincipalPredecessor = Readonly<PrincipalHistoryPrefix>;
5
5
  /** Authenticate the entire prefix, including its scope and current artifacts. */
@@ -6,7 +6,7 @@ import { principalHistoryEvidenceScopeId, principalHistoryPrefixProtection, } fr
6
6
  import { ownPrincipalHistoryProtection } from "../../data/principals/principalHistoryProtection.js";
7
7
  import { parsePrincipalHistoryStageCurrent } from "../../data/principals/principalHistoryStageProtection.js";
8
8
  import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
9
- import { principalHistoryVerificationContext } from "../principals/principalHistoryRecoveryVerification.js";
9
+ import { principalHistoryVerificationContext } from "./principalHistoryRecoveryVerification.js";
10
10
  /** Authenticate the entire prefix, including its scope and current artifacts. */
11
11
  export async function restoreAcknowledgedPrincipalPrefix(options, saved) {
12
12
  const scopeId = await principalHistoryEvidenceScopeId({
@@ -0,0 +1 @@
1
+ {"version":3,"file":"acknowledgedPrincipalPredecessor.js","sourceRoot":"","sources":["acknowledgedPrincipalPredecessor.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,qCAAqC,EACrC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,0BAA0B,GAE3B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,6BAA6B,EAAE,MAAM,kDAAkD,CAAC;AACjG,OAAO,EAAE,iCAAiC,EAAE,MAAM,uDAAuD,CAAC;AAC1G,OA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D,CAAC;QACF,mCAAmC,CAAC,OAAO,CAAC,CAAC;QAC7C,IACE,CAAC,6BAA6B,CAC5B,QAAQ,CAAC,QAAQ,CAAC,KAAK,EACvB,OAAO,CAAC,YAAY,CACrB;YAED,MAAM,IAAI,KAAK,CACb,gEAAgE,CACjE,CAAC;QACJ,OAAO,eAAe,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzC,CAAC;YAAS,CAAC;QACT,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAC9B,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,uCAAuC,CAC3D,OAA6C,EAC7C,KAA8C;IAE9C,MAAM,QAAQ,GAAG,MAAM,kCAAkC,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC1E,IACE,CAAC,6BAA6B,CAC5B,QAAQ,CAAC,QAAQ,CAAC,KAAK,EACvB,OAAO,CAAC,YAAY,CACrB;QAED,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,iEAAiE,CAClE,CAAC;IACJ,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n loadPrincipalHistoryPrefix,\n type PrincipalHistoryPrefix,\n} from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { parsePrincipalHistoryStageCurrent } from \"../../data/principals/principalHistoryStageProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\nimport { principalHistoryVerificationContext } from \"./principalHistoryRecoveryVerification\";\n\n/** Sealed predecessor evidence, owned by a mutation before its request is sent. */\nexport type AcknowledgedPrincipalPredecessor = Readonly<PrincipalHistoryPrefix>;\n\n/** Authenticate the entire prefix, including its scope and current artifacts. */\nexport async function restoreAcknowledgedPrincipalPrefix(\n options: RecoverPrincipalPolicyHistoryOptions,\n saved: AcknowledgedPrincipalPredecessor | null,\n) {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n if (\n !saved ||\n saved.scopeId !== scopeId ||\n saved.organizationId !== options.organizationId\n )\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledgement requires its authenticated predecessor prefix\",\n );\n const restored = await restorePrincipalPolicyHistoryVerifier(\n {\n principalId: options.expectedHead.principalId,\n principalType: options.expectedHead.principalType,\n },\n saved.progress,\n await principalHistoryPrefixProtection(options.protection, saved),\n );\n if (!restored.ok) throw restored.error;\n const artifacts = parsePrincipalHistoryStageCurrent({\n currentJson: saved.currentJson,\n afterVersion: saved.version - 1,\n });\n if (!artifacts)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Acknowledged predecessor artifacts are malformed\",\n );\n const history = restored.value.finish(\n principalPolicyReferenceFromBundle(artifacts),\n );\n if (!history.ok) throw history.error;\n const previous = await verifyPrincipalPolicyCurrent({\n current: artifacts,\n history: history.value,\n });\n if (!previous.ok) throw previous.error;\n return {\n scopeId,\n saved,\n artifacts,\n verifier: restored.value,\n previous: previous.value,\n history: history.value,\n predecessorIndexRootHash: history.value.indexRootHash,\n };\n}\n\n/** Capture exact predecessor evidence while authoring, before HTTP can commit. */\nexport async function captureAcknowledgedPrincipalPredecessor(\n input: RecoverPrincipalPolicyHistoryOptions,\n): Promise<AcknowledgedPrincipalPredecessor> {\n const protection = ownPrincipalHistoryProtection(input.protection);\n const options = {\n ...input,\n expectedHead: structuredClone(input.expectedHead),\n protection: {\n ...protection,\n context: principalHistoryVerificationContext(input),\n },\n };\n const current = () => !options.signal?.aborted && options.stillCurrent();\n try {\n assertProjectionVerificationCurrent(current);\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n const restored = await restoreAcknowledgedPrincipalPrefix(\n options,\n await loadPrincipalHistoryPrefix(options.execSql, scopeId),\n );\n assertProjectionVerificationCurrent(current);\n if (\n !principalHeadMatchesReference(\n restored.previous.state,\n options.expectedHead,\n )\n )\n throw new Error(\n \"Principal policy changed before submission; retry the mutation\",\n );\n return structuredClone(restored.saved);\n } finally {\n protection.localKey.fill(0);\n }\n}\n\nexport async function restoreAcknowledgedPrincipalPredecessor(\n options: RecoverPrincipalPolicyHistoryOptions,\n saved: AcknowledgedPrincipalPredecessor | null,\n) {\n const restored = await restoreAcknowledgedPrincipalPrefix(options, saved);\n if (\n !principalHeadMatchesReference(\n restored.previous.state,\n options.expectedHead,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Acknowledgement predecessor does not match the authored request\",\n );\n return restored;\n}\n"]}
@@ -1,4 +1,5 @@
1
1
  export type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
2
+ export { type AcknowledgedPrincipalPredecessor, captureAcknowledgedPrincipalPredecessor, } from "./acknowledgedPrincipalPredecessor.js";
2
3
  export { type CachePrincipalPolicyBundlesOptions, type CacheReferencedPrincipalPoliciesOptions, cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
3
4
  export { PrincipalPolicyHistoryReadError, type RecoveredPrincipalPolicyHistory, type RecoverPrincipalPolicyHistoryOptions, } from "./principalHistoryRecoveryTypes.js";
4
5
  export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
@@ -1,3 +1,4 @@
1
+ export { captureAcknowledgedPrincipalPredecessor, } from "./acknowledgedPrincipalPredecessor.js";
1
2
  export { cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache.js";
2
3
  export { PrincipalPolicyHistoryReadError, } from "./principalHistoryRecoveryTypes.js";
3
4
  export { recoverPrincipalPolicyHistory } from "./recoverPrincipalPolicyHistory.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAEL,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAGL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC","sourcesContent":["export type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nexport {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\nexport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./recoverProjectionPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,uCAAuC,GACxC,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EACL,+BAA+B,GAGhC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,6BAA6B,EAAE,MAAM,iCAAiC,CAAC;AAChF,OAAO,EAEL,8BAA8B,GAC/B,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAGL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC","sourcesContent":["export type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nexport {\n type AcknowledgedPrincipalPredecessor,\n captureAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgedPrincipalPredecessor\";\nexport {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./recoverPrincipalPolicyHistory\";\nexport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./recoverProjectionPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./recoverScopedPrincipalPolicyHistory\";\n"]}
@@ -3,23 +3,21 @@ import { assertProjectionVerificationCurrent } from "../../data/keyingProjection
3
3
  import { preparePrincipalHistoryEvidencePage } from "../../data/persistence/principalHistoryEvidencePersistence.js";
4
4
  import { principalHeadMatchesReference } from "../../data/principals/organizationAuthorityDescriptor.js";
5
5
  import { principalHistoryEvidenceScopeId } from "../../data/principals/principalHistoryPrefixProtection.js";
6
- import { collectPrincipalPolicySignerPublicKeys } from "../principals/policyVerification.js";
7
- import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationContext, } from "../principals/principalHistoryRecoveryVerification.js";
8
- import { groupPolicyMutationHead } from "./groupPolicyMutationHead.js";
6
+ import { collectPrincipalPolicySignerPublicKeys } from "./policyVerification.js";
9
7
  import { sealPrincipalCurrentPublication } from "./principalCurrentPublicationSeal.js";
10
- import { assertPrincipalPolicyReceiptArtifacts } from "./principalPolicyReceiptArtifacts.js";
8
+ import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationContext, } from "./principalHistoryRecoveryVerification.js";
11
9
  /** Verify a newly authored group from genesis before its atomic directory publication. */
12
- export async function prepareInitialGroupCurrentPublication(input, request, response, predecessor) {
10
+ export async function prepareInitialGroupCurrentPublication(input, request, response, predecessor, checks) {
13
11
  const current = () => !input.signal?.aborted && input.stillCurrent();
14
12
  assertProjectionVerificationCurrent(current);
15
- const expectedHead = await groupPolicyMutationHead(request);
13
+ const expectedHead = await checks.authoredHead(request);
16
14
  if (predecessor !== null ||
17
15
  request.state.principalType !== "group" ||
18
16
  request.state.version !== 1 ||
19
17
  request.state.prevStateHash !== null ||
20
18
  !principalHeadMatchesReference(expectedHead, input.expectedHead))
21
19
  throw new KeyingVerificationError("object_mismatch", "Initial group publication must begin at its exact genesis");
22
- assertPrincipalPolicyReceiptArtifacts({ expectedHead, request, response });
20
+ checks.assertReceipt({ expectedHead, request, response });
23
21
  const keys = await collectPrincipalPolicySignerPublicKeys({
24
22
  bundle: { currentState: response.currentState, previousStates: [] },
25
23
  resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initialPrincipalCurrentPublication.js","sourceRoot":"","sources":["initialPrincipalCurrentPublication.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,EACpC,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAEpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EAAE,6BAA6B,EAAE,MA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;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACnC,MAAM,OAAO,GAAG;QACd,GAAG,KAAK;QACR,UAAU,EAAE;YACV,GAAG,KAAK,CAAC,UAAU;YACnB,OAAO,EAAE,mCAAmC,CAAC,KAAK,CAAC;SACpD;KACF,CAAC;IACF,MAAM,OAAO,GAAG,MAAM,+BAA+B,CAAC;QACpD,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,IAAI,EAAE,YAAY;QAClB,UAAU,EAAE,OAAO,CAAC,UAAU;KAC/B,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,MAAM,+BAA+B,CAClD,OAAO,EACP,OAAO,EACP,YAAY,EACZ,QAAQ,EACR,QAAQ,CACT,CAAC;IACF,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC7C,OAAO;QACL,GAAG,MAAM;QACT,MAAM,EAAE,MAAM,CAAC,KAAK;QACpB,gBAAgB,EAAE,IAAI;QACtB,wBAAwB,EAAE,IAAI;QAC9B,sBAAsB,EAAE,IAAI;QAC5B,QAAQ,EAAE,MAAM,mCAAmC,CAAC;YAClD,aAAa,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;YAC3C,OAAO;YACP,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO,EAAE,CAAC,KAAK,CAAC;YAChB,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;SACjC,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n createPrincipalPolicyHistoryVerifier,\n KeyingVerificationError,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { AcknowledgedPrincipalCurrentPublication } from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { principalHeadMatchesReference } from \"../../data/principals/organizationAuthorityDescriptor\";\nimport { principalHistoryEvidenceScopeId } from \"../../data/principals/principalHistoryPrefixProtection\";\nimport type { AcknowledgedPrincipalPredecessor } from \"./acknowledgedPrincipalPredecessor\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"./policyVerification\";\nimport type { PrincipalAcknowledgementChecks } from \"./principalAcknowledgementChecks\";\nimport { sealPrincipalCurrentPublication } from \"./principalCurrentPublicationSeal\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"./principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"./principalHistoryRecoveryVerification\";\n\n/** Verify a newly authored group from genesis before its atomic directory publication. */\nexport async function prepareInitialGroupCurrentPublication(\n input: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n predecessor: AcknowledgedPrincipalPredecessor | null,\n checks: PrincipalAcknowledgementChecks,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n const current = () => !input.signal?.aborted && input.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const expectedHead = await checks.authoredHead(request);\n if (\n predecessor !== null ||\n request.state.principalType !== \"group\" ||\n request.state.version !== 1 ||\n request.state.prevStateHash !== null ||\n !principalHeadMatchesReference(expectedHead, input.expectedHead)\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Initial group publication must begin at its exact genesis\",\n );\n checks.assertReceipt({ expectedHead, request, response });\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { currentState: response.currentState, previousStates: [] },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"Initial group signer could not be authenticated\",\n );\n const externalAuthority = await input.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(current);\n const verifier = createPrincipalPolicyHistoryVerifier({\n principalType: \"group\",\n principalId: expectedHead.principalId,\n });\n const entry = {\n state: response.currentState,\n projection: response.currentProjection,\n grants: response.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(input, [entry]);\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const history = verifier.finish(expectedHead);\n if (!history.ok) throw history.error;\n const policy = await verifyPrincipalPolicyCurrent({\n current: response,\n history: history.value,\n });\n if (!policy.ok) throw policy.error;\n const options = {\n ...input,\n protection: {\n ...input.protection,\n context: principalHistoryVerificationContext(input),\n },\n };\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: input.organizationId,\n head: expectedHead,\n protection: options.protection,\n });\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n response,\n );\n assertProjectionVerificationCurrent(current);\n return {\n ...sealed,\n policy: policy.value,\n predecessorStage: null,\n predecessorIndexRootHash: null,\n previousPrefixProgress: null,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId,\n organizationId: input.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { PrincipalPolicyBundleResponse, ReferencedPrincipalStateResponse } from "../../internal/validators/response/index.js";
2
- import type { SecurityIncidentReporter } from "../../data/securityIncidents.js";
2
+ import type { SecurityIncidentReporter } from "../../data/shared/securityIncidents.js";
3
3
  import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
4
4
  import type { TrustedUserIdentityResolver } from "../../data/trustedUserIdentity/index.js";
5
5
  import type { CurrentPrincipalPolicyReader } from "./currentPrincipalPolicyReader.js";
@@ -1,11 +1,11 @@
1
- import { errorMessage } from "../../data/errorMessage.js";
2
- import { isProjectionVerificationCancelledError } from "../../data/keyingProjectionVerification.js";
1
+ import { isProjectionVerificationCancelledError } from "../../data/keyingProjectionVerification/index.js";
3
2
  import { reportAndRethrowKeyingVerificationError, rethrowKeyingVerificationError, } from "../../data/keyingProjectionVerification/error.js";
4
3
  import { dedupeReferencedPrincipalStates } from "../../data/keyingProjectionVerification/principalPolicyCache.js";
5
4
  import { loadPrincipalPolicyCheckpoint } from "../../data/persistence/keyingCheckpointPersistence.js";
6
5
  import { ensurePrincipalPolicyTables } from "../../data/persistence/principalPolicyPersistence.js";
7
6
  import { loadPrincipalPolicyBundleForReference } from "../../data/persistence/principalPolicyReferencePersistence.js";
8
7
  import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
8
+ import { errorMessage } from "../../data/shared/errorMessage.js";
9
9
  import { externalAdminPolicyPersistenceEntries, loadOrganizationExternalAdminPolicy, } from "./externalAdminPolicy.js";
10
10
  import { persistPrincipalPolicyCacheEntries, retryPrincipalPolicyCacheAdvance, } from "./principalPolicyCacheAdvance.js";
11
11
  import { scopeReferencedPolicyForCache } from "./principalPolicyCacheScope.js";
@@ -1 +1 @@
1
- {"version":3,"file":"policyCache.js","sourceRoot":"","sources":["policyCache.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,sCAAsC,EAAE,MAAM,yCAAyC,CAAC;AACjG,OAAO,EACL,uCAAuC,EACvC,8BAA8B,GAC/B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,8DAA8D,CAAC;AAC/G,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,2BAA2B,EAAE,MAAM,mDAAmD,CAAC;AAChG,OAAO,EAAE,qCAAqC,EAAE,MAAM,4DAA4D,CAAC;AACnH,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AAKvG,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,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EAC1B,YAAY,GACuB;IACnC,MAAM,uBAAuB,CAAC;QAC5B,SAAS,EAAE,CAAC,MAAM,EAAE,uBAAuB,EAAE,aAAa,EAAE,EAAE,CAC5D,0BAA0B,CAAC;YACzB,MAAM;YACN,OAAO;YACP,uBAAuB;YACvB,aAAa;YACb,GAAG;YACH,cAAc;YACd,0BAA0B;YAC1B,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { errorMessage } from \"../../data/errorMessage\";\nimport { isProjectionVerificationCancelledError } from \"../../data/keyingProjectionVerification\";\nimport {\n reportAndRethrowKeyingVerificationError,\n rethrowKeyingVerificationError,\n} from \"../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { ensurePrincipalPolicyTables } from \"../../data/persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../data/persistence/principalPolicyReferencePersistence\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"./currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"./externalAdminPolicy\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await loadPrincipalPolicyBundleForReference(\n execSql,\n reference,\n localCheckpoint,\n );\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle, policy: validation.policy },\n ],\n execSql,\n organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await ensurePrincipalPolicyTables(input.execSql);\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () =>\n (reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input))\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
1
+ {"version":3,"file":"policyCache.js","sourceRoot":"","sources":["policyCache.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,sCAAsC,EAAE,MAAM,yCAAyC,CAAC;AACjG,OAAO,EACL,uCAAuC,EACvC,8BAA8B,GAC/B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,+BAA+B,EAAE,MAAM,8DAA8D,CAAC;AAC/G,OAAO,EAAE,6BAA6B,EAAE,MAAM,oDAAoD,CAAC;AACnG,OAAO,EAAE,2BAA2B,EAAE,MAAM,mDAAmD,CAAC;AAChG,OAAO,EAAE,qCAAqC,EAAE,MAAM,4DAA4D,CAAC;AACnH,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAK9D,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,kCAAkC,EAClC,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,6BAA6B,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EACL,2BAA2B,EAC3B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,YAAY;SACb,CAAC;QACJ,mBAAmB;QACnB,MAAM,EAAE,4BAA4B;QACpC,OAAO;QACP,OAAO,EAAE,qBAAqB;QAC9B,KAAK,EAAE,OAAO;QACd,GAAG;QACH,cAAc;QAEd,sBAAsB;QACtB,0BAA0B;QAC1B,YAAY;KACb,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { VerifiedPrincipalPolicy } from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport { isProjectionVerificationCancelledError } from \"../../data/keyingProjectionVerification\";\nimport {\n reportAndRethrowKeyingVerificationError,\n rethrowKeyingVerificationError,\n} from \"../../data/keyingProjectionVerification/error\";\nimport { dedupeReferencedPrincipalStates } from \"../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../data/persistence/keyingCheckpointPersistence\";\nimport { ensurePrincipalPolicyTables } from \"../../data/persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../data/persistence/principalPolicyReferencePersistence\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"./currentPrincipalPolicyReader\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"./externalAdminPolicy\";\nimport {\n persistPrincipalPolicyCacheEntries,\n retryPrincipalPolicyCacheAdvance,\n} from \"./principalPolicyCacheAdvance\";\nimport { scopeReferencedPolicyForCache } from \"./principalPolicyCacheScope\";\nimport { validatePrincipalPolicyBundleForCache } from \"./principalPolicyCacheValidation\";\nimport {\n createPolicyDirectoryLoader,\n directoryBindsGroupReference,\n type PolicyDirectoryLoader,\n type VerifiedPolicyDirectory,\n} from \"./principalPolicyOrganizationScope\";\n\nexport interface CacheReferencedPrincipalPoliciesOptions {\n currentPolicyReader: CurrentPrincipalPolicyReader;\n execSql: ExecSql;\n log?: (message: string) => void;\n organizationId: string;\n reportSecurityIncident: SecurityIncidentReporter;\n references: ReadonlyArray<ReferencedPrincipalStateResponse> | undefined;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}\n\nexport interface CachePrincipalPolicyBundlesOptions\n extends Omit<CacheReferencedPrincipalPoliciesOptions, \"references\"> {\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse> | undefined;\n}\n\nfunction getReferencedPrincipalKey(\n reference: ReferencedPrincipalStateResponse,\n): string {\n return `${reference.principalType}:${reference.principalId}`;\n}\n\nfunction getBundlePrincipalKey(bundle: PrincipalPolicyBundleResponse): string {\n return `${bundle.currentState.principalType}:${bundle.currentState.principalId}`;\n}\n\nfunction dedupePrincipalPolicyBundles(\n bundles: ReadonlyArray<PrincipalPolicyBundleResponse>,\n): PrincipalPolicyBundleResponse[] {\n const bundlesByPrincipal = new Map<string, PrincipalPolicyBundleResponse>();\n\n for (const bundle of bundles) {\n const key = getBundlePrincipalKey(bundle);\n const previous = bundlesByPrincipal.get(key);\n if (\n !previous ||\n bundle.currentState.version > previous.currentState.version\n ) {\n bundlesByPrincipal.set(key, bundle);\n }\n }\n\n return Array.from(bundlesByPrincipal.values());\n}\n\nasync function cacheReferencedPrincipalPolicy(\n execSql: ExecSql,\n reader: CurrentPrincipalPolicyReader,\n reference: ReferencedPrincipalStateResponse,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n log: ((message: string) => void) | undefined,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n organizationId: string,\n stillCurrent: (() => boolean) | undefined,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n): Promise<VerifiedPrincipalPolicy[]> {\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n reference.principalType,\n reference.principalId,\n );\n // Only null is a recoverable local miss. Integrity failures remain typed and\n // must escape rather than being hidden by a canonical network retry.\n const cachedBundle = fresh\n ? null\n : await loadPrincipalPolicyBundleForReference(\n execSql,\n reference,\n localCheckpoint,\n );\n let bundle =\n cachedBundle ??\n (await reader.getCurrentPrincipalPolicy(\n reference.principalType,\n reference.principalId,\n ));\n if (!bundle) {\n log?.(\n `Principal policy cache: failed to fetch ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n\n let validation = await validatePrincipalPolicyBundleForCache({\n bundle,\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n const scoped = await scopeReferencedPolicyForCache({\n bundle,\n validation,\n validationInput: {\n loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity,\n },\n loadDirectory,\n organizationId,\n reloadBundle: cachedBundle\n ? () => reader.getCurrentPrincipalPolicy(\"group\", reference.principalId)\n : null,\n });\n if (!scoped) {\n log?.(\n `Principal policy cache: signed organization directory does not cover ${getReferencedPrincipalKey(reference)}`,\n );\n return [];\n }\n bundle = scoped.bundle;\n validation = scoped.validation;\n const directory = scoped.directory;\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle, policy: validation.policy },\n ],\n execSql,\n organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function cachePrincipalPolicyBundle(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly log: ((message: string) => void) | undefined;\n readonly loadDirectory: PolicyDirectoryLoader;\n readonly organizationId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const reference = principalPolicyReferenceFromBundle(input.bundle);\n // The API supplied this bundle after rejecting a write, but local storage is\n // only updated after normal signature, signer, and checkpoint verification.\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n reference.principalType,\n reference.principalId,\n );\n const validation = await validatePrincipalPolicyBundleForCache({\n bundle: input.bundle,\n loadExternalAdminPolicy: input.loadExternalAdminPolicy,\n localCheckpoint,\n reference,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (!validation.ok) {\n throw validation.error;\n }\n\n let directory: VerifiedPolicyDirectory | null = null;\n if (reference.principalType === \"group\") {\n directory = await input.loadDirectory(false);\n if (!directoryBindsGroupReference(directory, validation.policy, reference))\n directory = await input.loadDirectory(true);\n if (\n !directoryBindsGroupReference(directory, validation.policy, reference)\n ) {\n input.log?.(\n \"Principal policy cache: signed organization directory does not cover supplied group\",\n );\n return [];\n }\n } else if (reference.principalId !== input.organizationId) {\n return [];\n }\n const externalEntries = validation.externalAdminPolicy\n ? externalAdminPolicyPersistenceEntries(\n validation.externalAdminPolicy,\n ).filter(\n (entry) => !directory || entry.policy.principalType !== \"organization\",\n )\n : [];\n const directoryEntries = directory\n ? [{ bundle: directory.bundle, policy: directory.policy }]\n : [];\n await persistPrincipalPolicyCacheEntries({\n entries: [\n ...externalEntries,\n ...directoryEntries,\n { bundle: input.bundle, policy: validation.policy },\n ],\n execSql: input.execSql,\n organizationId: input.organizationId,\n updatedAt: new Date().toISOString(),\n stillCurrent: input.stillCurrent,\n });\n return [...externalEntries.map(({ policy }) => policy), validation.policy];\n}\n\nasync function runPrincipalPolicyCache<Item, Result>(input: {\n readonly cacheItem: (\n item: Item,\n loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>,\n loadDirectory: PolicyDirectoryLoader,\n fresh: boolean,\n ) => Promise<readonly Result[]>;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly dedupe: (items: ReadonlyArray<Item>) => Item[];\n readonly execSql: ExecSql;\n readonly itemKey: (item: Item) => string;\n readonly items: ReadonlyArray<Item> | undefined;\n readonly log: ((message: string) => void) | undefined;\n readonly organizationId: string;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<Result[]> {\n if (!input.items || input.items.length === 0) {\n return [];\n }\n\n try {\n await ensurePrincipalPolicyTables(input.execSql);\n const uniqueItems = input.dedupe(input.items);\n const loadDirectory = createPolicyDirectoryLoader(input);\n let externalAdminPolicy: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n const loadExternalAdminPolicy = () => {\n externalAdminPolicy ??= loadOrganizationExternalAdminPolicy({\n currentPolicyReader: input.currentPolicyReader,\n execSql: input.execSql,\n organizationId: input.organizationId,\n\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n return externalAdminPolicy;\n };\n\n const results = await Promise.all(\n uniqueItems.map(async (item) => {\n try {\n return await retryPrincipalPolicyCacheAdvance((fresh) => {\n const reloadDirectory = createPolicyDirectoryLoader(input);\n let reloadedAuthority: Promise<VerifiedExternalAdminPolicy | null> | null =\n null;\n return input.cacheItem(\n item,\n fresh\n ? () =>\n (reloadedAuthority ??=\n loadOrganizationExternalAdminPolicy(input))\n : loadExternalAdminPolicy,\n fresh ? () => reloadDirectory(true) : loadDirectory,\n fresh,\n );\n });\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n await reportAndRethrowKeyingVerificationError(\n error,\n input.reportSecurityIncident,\n {\n objectId: input.itemKey(item),\n objectKind: \"principal\",\n operation: \"principal.policy.cache\",\n organizationId: input.organizationId,\n },\n );\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to store ${input.itemKey(item)}: ${message}`,\n );\n return [];\n }\n }),\n );\n return results.flat();\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return [];\n // Per-item verification failures were reported above before reaching this\n // initialization/aggregation boundary.\n rethrowKeyingVerificationError(error);\n const message = errorMessage(error);\n input.log?.(\n `Principal policy cache: failed to initialize cache: ${message}`,\n );\n return [];\n }\n}\n\nasync function loadReferencedPrincipalPolicies({\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n references,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CacheReferencedPrincipalPoliciesOptions): Promise<\n VerifiedPrincipalPolicy[]\n> {\n return runPrincipalPolicyCache({\n cacheItem: (reference, loadExternalAdminPolicy, loadDirectory, fresh) =>\n cacheReferencedPrincipalPolicy(\n execSql,\n currentPolicyReader,\n reference,\n resolveTrustedUserIdentity,\n log,\n loadExternalAdminPolicy,\n organizationId,\n stillCurrent,\n loadDirectory,\n fresh,\n ),\n currentPolicyReader,\n dedupe: dedupeReferencedPrincipalStates,\n execSql,\n itemKey: getReferencedPrincipalKey,\n items: references,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n\nexport async function cacheReferencedPrincipalPolicies(\n input: CacheReferencedPrincipalPoliciesOptions,\n): Promise<void> {\n await loadReferencedPrincipalPolicies(input);\n}\n\nexport async function cachePrincipalPolicyBundles({\n bundles,\n currentPolicyReader,\n execSql,\n log,\n organizationId,\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n}: CachePrincipalPolicyBundlesOptions): Promise<void> {\n await runPrincipalPolicyCache({\n cacheItem: (bundle, loadExternalAdminPolicy, loadDirectory) =>\n cachePrincipalPolicyBundle({\n bundle,\n execSql,\n loadExternalAdminPolicy,\n loadDirectory,\n log,\n organizationId,\n resolveTrustedUserIdentity,\n stillCurrent,\n }),\n currentPolicyReader,\n dedupe: dedupePrincipalPolicyBundles,\n execSql,\n itemKey: getBundlePrincipalKey,\n items: bundles,\n log,\n organizationId,\n\n reportSecurityIncident,\n resolveTrustedUserIdentity,\n stillCurrent,\n });\n}\n"]}
@@ -0,0 +1,30 @@
1
+ import type { PrincipalPolicyExternalAuthority, PrincipalPolicySignerPublicKey, ReferencedPrincipalHead, VerifiedPrincipalPolicyCurrent } from "../../internal/crypto/index.js";
2
+ import type { PutPrincipalPolicyRequest } from "../../internal/validators/request/index.js";
3
+ import type { PrincipalPolicyMutationResponse } from "../../internal/validators/response/index.js";
4
+ /**
5
+ * The checks the code that authored a principal mutation makes on the
6
+ * server's acknowledgement of it. Recovery records an acknowledged current
7
+ * only after these accept it; the organization mutation workflows supply them.
8
+ */
9
+ export interface PrincipalAcknowledgementChecks {
10
+ /** The head an authored request commits to. */
11
+ readonly authoredHead: (request: PutPrincipalPolicyRequest) => Promise<ReferencedPrincipalHead>;
12
+ /** The receipt carries exactly the authored state and artifacts. */
13
+ readonly assertReceipt: (input: {
14
+ readonly expectedHead: ReferencedPrincipalHead;
15
+ readonly request: PutPrincipalPolicyRequest;
16
+ readonly response: PrincipalPolicyMutationResponse;
17
+ }) => void;
18
+ /** The acknowledged state is the authored successor of the verified predecessor. */
19
+ readonly acknowledgeSuccessor: (input: {
20
+ readonly verifiedCurrentPolicy: VerifiedPrincipalPolicyCurrent;
21
+ readonly expectedHead: ReferencedPrincipalHead;
22
+ readonly request: PutPrincipalPolicyRequest;
23
+ readonly response: PrincipalPolicyMutationResponse["currentState"];
24
+ readonly signerPublicKeys: readonly PrincipalPolicySignerPublicKey[];
25
+ readonly externalAuthority?: PrincipalPolicyExternalAuthority | undefined;
26
+ readonly stillCurrent: () => boolean;
27
+ }) => Promise<VerifiedPrincipalPolicyCurrent>;
28
+ /** Acknowledged directory and group heads cite each other. */
29
+ readonly assertDirectoryBindings: (organizationId: string, responses: readonly PrincipalPolicyMutationResponse[]) => void;
30
+ }