@tearleads/client-sdk 0.1.58 → 0.1.60

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 (477) hide show
  1. package/Tearleads.d.ts +17 -17
  2. package/Tearleads.js +15 -15
  3. package/Tearleads.js.map +1 -1
  4. package/client/{blobs.d.ts → blobs/index.d.ts} +1 -1
  5. package/client/{blobs.js → blobs/index.js} +3 -3
  6. package/client/blobs/index.js.map +1 -0
  7. package/client/{containerDocumentDiscovery.js → containerContents/documentDiscovery.js} +11 -11
  8. package/client/containerContents/documentDiscovery.js.map +1 -0
  9. package/client/{containerContents.d.ts → containerContents/index.d.ts} +13 -13
  10. package/client/{containerContents.js → containerContents/index.js} +18 -18
  11. package/client/containerContents/index.js.map +1 -0
  12. package/client/{containerContentsTypes.d.ts → containerContents/types.d.ts} +14 -14
  13. package/client/containerContents/types.js +2 -0
  14. package/client/containerContents/types.js.map +1 -0
  15. package/client/{deviceFirst.d.ts → deviceFirst/index.d.ts} +7 -7
  16. package/client/{deviceFirst.js → deviceFirst/index.js} +11 -11
  17. package/client/deviceFirst/index.js.map +1 -0
  18. package/client/{reconciledDocumentContentPull.js → deviceFirst/reconciledDocumentContentPull.js} +1 -1
  19. package/client/deviceFirst/reconciledDocumentContentPull.js.map +1 -0
  20. package/client/{documents.d.ts → documents/index.d.ts} +5 -5
  21. package/client/{documents.js → documents/index.js} +5 -5
  22. package/client/documents/index.js.map +1 -0
  23. package/client/{identity.d.ts → identity/index.d.ts} +2 -2
  24. package/client/{identity.js → identity/index.js} +5 -5
  25. package/client/identity/index.js.map +1 -0
  26. package/client/{identityKeyPackage.d.ts → identity/keyPackage.d.ts} +1 -1
  27. package/client/{identityKeyPackage.js → identity/keyPackage.js} +4 -4
  28. package/client/identity/keyPackage.js.map +1 -0
  29. package/client/{userIdentities.d.ts → identity/userIdentities.d.ts} +2 -2
  30. package/client/{userIdentities.js → identity/userIdentities.js} +4 -4
  31. package/client/identity/userIdentities.js.map +1 -0
  32. package/client/index.d.ts +18 -18
  33. package/client/index.js +9 -9
  34. package/client/index.js.map +1 -1
  35. package/client/organizations/currentPrincipalMutations.js.map +1 -1
  36. package/client/organizations/index.d.ts +2 -2
  37. package/client/organizations/index.js.map +1 -1
  38. package/client/organizations/organizationAccessRestoration.js.map +1 -1
  39. package/client/organizations/organizationDataUsage.d.ts +1 -1
  40. package/client/organizations/organizationDataUsage.js.map +1 -1
  41. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  42. package/client/organizations/organizationGroupPresentation.d.ts +1 -1
  43. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  44. package/client/organizations/organizationMetadataProfileSync.js +1 -1
  45. package/client/organizations/organizationMetadataProfileSync.js.map +1 -1
  46. package/client/organizations/organizationReadModels.d.ts +1 -1
  47. package/client/organizations/organizationReadModels.js.map +1 -1
  48. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  49. package/client/organizations/organizationsTypes.d.ts +1 -1
  50. package/client/organizations/organizationsTypes.js.map +1 -1
  51. package/client/organizations/principalContainerMutations.js.map +1 -1
  52. package/client/organizations/principalMutationRecovery.d.ts +1 -1
  53. package/client/organizations/principalMutationRecovery.js.map +1 -1
  54. package/client/organizations/principalMutationScope.js.map +1 -1
  55. package/client/organizations/principalMutations.d.ts +2 -2
  56. package/client/organizations/principalMutations.js.map +1 -1
  57. package/client/root/index.d.ts +1 -1
  58. package/client/root/index.js.map +1 -1
  59. package/client/{database.d.ts → runtime/database.d.ts} +1 -1
  60. package/client/{database.js → runtime/database.js} +1 -1
  61. package/client/runtime/database.js.map +1 -0
  62. package/client/{principalHistoryProtection.d.ts → runtime/principalHistoryProtection.d.ts} +1 -1
  63. package/client/{principalHistoryProtection.js → runtime/principalHistoryProtection.js} +2 -2
  64. package/client/runtime/principalHistoryProtection.js.map +1 -0
  65. package/client/{principalMutationApi.d.ts → runtime/principalMutationApi.d.ts} +4 -4
  66. package/client/{principalMutationApi.js → runtime/principalMutationApi.js} +2 -2
  67. package/client/runtime/principalMutationApi.js.map +1 -0
  68. package/client/{principalMutationDispatch.js → runtime/principalMutationDispatch.js} +2 -2
  69. package/client/runtime/principalMutationDispatch.js.map +1 -0
  70. package/client/runtime/rootContainerAdoption.js.map +1 -0
  71. package/client/{workflowRuntime.d.ts → runtime/workflowRuntime.d.ts} +12 -12
  72. package/client/{workflowRuntime.js → runtime/workflowRuntime.js} +5 -5
  73. package/client/runtime/workflowRuntime.js.map +1 -0
  74. package/client/{securityIncidents.d.ts → securityIncidents/index.d.ts} +3 -3
  75. package/client/{securityIncidents.js → securityIncidents/index.js} +5 -5
  76. package/client/securityIncidents/index.js.map +1 -0
  77. package/client/session/index.js +1 -1
  78. package/client/session/index.js.map +1 -1
  79. package/client/session/sessionIdentityTrust.d.ts +1 -1
  80. package/client/session/sessionLoginRefusal.js.map +1 -1
  81. package/client/session/sessionOrganizationCreation.js.map +1 -1
  82. package/client/session/sessionPurgeRecovery.js.map +1 -1
  83. package/client/session/sessionRootAuthority.js.map +1 -1
  84. package/client/session/sessionTypes.d.ts +3 -3
  85. package/client/session/sessionTypes.js.map +1 -1
  86. package/data/blobs/createBlobStore.d.ts +1 -1
  87. package/data/blobs/createBlobStore.js.map +1 -1
  88. package/data/blobs/encryptedBlobByteSource.js +1 -1
  89. package/data/blobs/encryptedBlobByteSource.js.map +1 -1
  90. package/data/blobs/encryptedBlobEnvelope.d.ts +1 -1
  91. package/data/blobs/encryptedBlobEnvelope.js +2 -2
  92. package/data/blobs/encryptedBlobEnvelope.js.map +1 -1
  93. package/data/blobs/encryptedBlobStore.d.ts +1 -1
  94. package/data/blobs/encryptedBlobStore.js +1 -1
  95. package/data/blobs/encryptedBlobStore.js.map +1 -1
  96. package/data/blobs/memoryBlobStore.d.ts +1 -1
  97. package/data/blobs/memoryBlobStore.js +1 -1
  98. package/data/blobs/memoryBlobStore.js.map +1 -1
  99. package/data/blobs/opfsBlobStore.d.ts +1 -1
  100. package/data/blobs/opfsBlobStore.js +1 -1
  101. package/data/blobs/opfsBlobStore.js.map +1 -1
  102. package/data/containers/containerMetadataDocument.js +1 -1
  103. package/data/containers/containerMetadataDocument.js.map +1 -1
  104. package/data/containers/shared/events.js +1 -1
  105. package/data/containers/shared/events.js.map +1 -1
  106. package/data/containers/shared/heldContainerHeads.js +1 -1
  107. package/data/containers/shared/heldContainerHeads.js.map +1 -1
  108. package/data/containers/shared/mutationAcknowledgement.js +1 -1
  109. package/data/containers/shared/mutationAcknowledgement.js.map +1 -1
  110. package/data/containers/shared/principalPolicies.js +1 -1
  111. package/data/containers/shared/principalPolicies.js.map +1 -1
  112. package/data/containers/shared/readers.js +2 -2
  113. package/data/containers/shared/readers.js.map +1 -1
  114. package/data/documents/attachmentContentIdentity.js +1 -1
  115. package/data/documents/attachmentContentIdentity.js.map +1 -1
  116. package/data/documents/blob/shared/blobEnvelopeStream.js.map +1 -1
  117. package/data/documents/blob/shared/blobSourceSnapshot.d.ts +1 -1
  118. package/data/documents/blob/shared/blobSourceSnapshot.js.map +1 -1
  119. package/data/documents/blob/shared/chunkedBlobCrypto.js.map +1 -1
  120. package/data/documents/blob/shared/encryptedUploadParts.js.map +1 -1
  121. package/data/documents/blob/shared/events.js +1 -1
  122. package/data/documents/blob/shared/events.js.map +1 -1
  123. package/data/documents/blob/shared/types.d.ts +2 -2
  124. package/data/documents/blob/shared/types.js.map +1 -1
  125. package/data/documents/shared/containerKekPathHistory.js +1 -1
  126. package/data/documents/shared/containerKekPathHistory.js.map +1 -1
  127. package/data/documents/shared/containerKekPathVerification.d.ts +1 -1
  128. package/data/documents/shared/containerKekPathVerification.js +1 -1
  129. package/data/documents/shared/events.js +1 -1
  130. package/data/documents/shared/events.js.map +1 -1
  131. package/data/documents/shared/manifestBundleReaders.js +2 -2
  132. package/data/documents/shared/manifestBundleReaders.js.map +1 -1
  133. package/data/documents/shared/projection.d.ts +1 -1
  134. package/data/documents/shared/projection.js +2 -2
  135. package/data/documents/shared/projection.js.map +1 -1
  136. package/data/documents/shared/projectionContentKeys.d.ts +1 -1
  137. package/data/documents/shared/readers.js +3 -3
  138. package/data/documents/shared/readers.js.map +1 -1
  139. package/data/documents/shared/stableDocumentId.js +1 -1
  140. package/data/documents/shared/stableDocumentId.js.map +1 -1
  141. package/data/documents/shared/types.d.ts +1 -1
  142. package/data/documents/shared/types.js +1 -1
  143. package/data/{keyingCanonicalJson.js → keying/canonicalJson.js} +3 -3
  144. package/data/keying/canonicalJson.js.map +1 -0
  145. package/data/keyingProjectionVerification/bundleVerification.js +1 -1
  146. package/data/keyingProjectionVerification/bundleVerification.js.map +1 -1
  147. package/data/keyingProjectionVerification/containerAncestorCitations.js +1 -1
  148. package/data/keyingProjectionVerification/containerAncestorCitations.js.map +1 -1
  149. package/data/keyingProjectionVerification/containerManifestVerification.js +1 -1
  150. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  151. package/data/keyingProjectionVerification/documentManifestVerification.js +1 -1
  152. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  153. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js +1 -1
  154. package/data/keyingProjectionVerification/documentPurgeDocumentChainVerification.js.map +1 -1
  155. package/data/keyingProjectionVerification/error.js +1 -1
  156. package/data/keyingProjectionVerification/error.js.map +1 -1
  157. package/data/keyingProjectionVerification/index.d.ts +9 -0
  158. package/data/{keyingProjectionVerification.js → keyingProjectionVerification/index.js} +8 -8
  159. package/data/keyingProjectionVerification/index.js.map +1 -0
  160. package/data/keyingProjectionVerification/principalPolicyCache.js +1 -1
  161. package/data/keyingProjectionVerification/principalPolicyCache.js.map +1 -1
  162. package/data/keyingProjectionVerification/principalPolicyVerification.js +1 -1
  163. package/data/keyingProjectionVerification/principalPolicyVerification.js.map +1 -1
  164. package/data/keyingProjectionVerification/readers.d.ts +1 -1
  165. package/data/keyingProjectionVerification/readers.js +3 -3
  166. package/data/keyingProjectionVerification/readers.js.map +1 -1
  167. package/data/keyingProjectionVerification/userKeyResolver.d.ts +1 -1
  168. package/data/keyingProjectionVerification/userKeyResolver.js.map +1 -1
  169. package/data/persistence/containers/containerPersistence.js +1 -1
  170. package/data/persistence/containers/containerPersistence.js.map +1 -1
  171. package/data/persistence/documents/documentDiscoveryCandidate.js +1 -1
  172. package/data/persistence/documents/documentDiscoveryCandidate.js.map +1 -1
  173. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js +1 -1
  174. package/data/persistence/documents/documentDiscoveryEvidencePersistence.js.map +1 -1
  175. package/data/persistence/documents/internal/documentProjectionRows.js +1 -1
  176. package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
  177. package/data/persistence/documents/internal/documentRows.js +1 -1
  178. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  179. package/data/persistence/principalPolicyBundleIntegrity.js +1 -1
  180. package/data/persistence/principalPolicyBundleIntegrity.js.map +1 -1
  181. package/data/persistence/principalPolicyReferenceCheckpoint.js +1 -1
  182. package/data/persistence/principalPolicyReferenceCheckpoint.js.map +1 -1
  183. package/data/persistence/principalPolicyReferenceIndexPersistence.js +1 -1
  184. package/data/persistence/principalPolicyReferenceIndexPersistence.js.map +1 -1
  185. package/data/persistence/principalPolicyReferencePersistence.js +1 -1
  186. package/data/persistence/principalPolicyReferencePersistence.js.map +1 -1
  187. package/data/persistence/securityIncidentPersistence.js.map +1 -1
  188. package/data/persistence/verifiedPrincipalPolicyBundle.js +1 -1
  189. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
  190. package/data/persistence/verifiedPrincipalPolicyCurrent.js +1 -1
  191. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -1
  192. package/data/principals/principalMutationJournal.js +1 -1
  193. package/data/principals/principalMutationJournal.js.map +1 -1
  194. package/data/{securityIncidents.d.ts → shared/securityIncidents.d.ts} +1 -1
  195. package/data/sqlite/documentRecordPersistence.js +1 -1
  196. package/data/sqlite/documentRecordPersistence.js.map +1 -1
  197. package/data/sync/crdtPeerSeed.d.ts +18 -0
  198. package/data/sync/originatedDocuments.d.ts +1 -1
  199. package/data/sync/originatedDocuments.js.map +1 -1
  200. package/data/sync/syncCoordinator.d.ts +1 -1
  201. package/data/sync/syncCoordinator.js.map +1 -1
  202. package/package.json +1 -1
  203. package/stores/container-contents/backgroundHydration.js +1 -1
  204. package/stores/container-contents/backgroundHydration.js.map +1 -1
  205. package/stores/container-contents/containerContentsStore.d.ts +1 -1
  206. package/stores/container-contents/containerContentsStore.js.map +1 -1
  207. package/stores/container-contents/localRefresh.js +1 -1
  208. package/stores/container-contents/localRefresh.js.map +1 -1
  209. package/stores/container-contents/remoteContainerIngestion.js +1 -1
  210. package/stores/container-contents/remoteContainerIngestion.js.map +1 -1
  211. package/stores/container-contents/remoteWriteQueue.js +1 -1
  212. package/stores/container-contents/remoteWriteQueue.js.map +1 -1
  213. package/stores/container-contents/systemContainerHydration.js +1 -1
  214. package/stores/container-contents/systemContainerHydration.js.map +1 -1
  215. package/stores/container-contents/utils.js +1 -1
  216. package/stores/container-contents/utils.js.map +1 -1
  217. package/stores/documents/documentStore/attachmentIntents.js +1 -1
  218. package/stores/documents/documentStore/attachmentIntents.js.map +1 -1
  219. package/stores/documents/documentStore/attachmentSourceUpload.js.map +1 -1
  220. package/stores/documents/documentStore/attachmentStaging.js +1 -1
  221. package/stores/documents/documentStore/attachmentStaging.js.map +1 -1
  222. package/stores/documents/documentStore/attachmentUploadLane.js.map +1 -1
  223. package/stores/documents/documentStore/persistence.js +2 -2
  224. package/stores/documents/documentStore/persistence.js.map +1 -1
  225. package/stores/documents/documentStore/state.js +1 -1
  226. package/stores/documents/documentStore/state.js.map +1 -1
  227. package/stores/documents/documentStore/storedDocument.js +1 -1
  228. package/stores/documents/documentStore/storedDocument.js.map +1 -1
  229. package/stores/documents/documentStore/syncAttachments.js.map +1 -1
  230. package/stores/documents/documentStore.d.ts +1 -1
  231. package/stores/documents/documentStore.js.map +1 -1
  232. package/stores/documents/registry.d.ts +1 -1
  233. package/stores/documents/registry.js.map +1 -1
  234. package/stores/documents/types.d.ts +1 -1
  235. package/stores/documents/types.js.map +1 -1
  236. package/stores/local-projection/registry.d.ts +1 -1
  237. package/stores/local-projection/registry.js.map +1 -1
  238. package/sync/reconciliation/serviceTypes.d.ts +1 -1
  239. package/sync/reconciliation/serviceTypes.js.map +1 -1
  240. package/sync/reconciliation/triggers.d.ts +1 -1
  241. package/sync/reconciliation/triggers.js.map +1 -1
  242. package/workflows/blobs/attachmentBindingVerification.js +2 -2
  243. package/workflows/blobs/attachmentBindingVerification.js.map +1 -1
  244. package/workflows/blobs/blobChunkDecryption.js.map +1 -1
  245. package/workflows/blobs/decrypt.d.ts +1 -1
  246. package/workflows/blobs/decrypt.js +2 -2
  247. package/workflows/blobs/decrypt.js.map +1 -1
  248. package/workflows/blobs/detach.js +2 -2
  249. package/workflows/blobs/detach.js.map +1 -1
  250. package/workflows/blobs/hydrate.d.ts +3 -3
  251. package/workflows/blobs/hydrate.js +1 -1
  252. package/workflows/blobs/hydrate.js.map +1 -1
  253. package/workflows/blobs/hydrationResults.js.map +1 -1
  254. package/workflows/blobs/index.d.ts +2 -2
  255. package/workflows/blobs/index.js +1 -1
  256. package/workflows/blobs/index.js.map +1 -1
  257. package/workflows/blobs/multipartFirstParts.js.map +1 -1
  258. package/workflows/blobs/retainedAttachmentVerification.js +1 -1
  259. package/workflows/blobs/upload.js +3 -3
  260. package/workflows/blobs/upload.js.map +1 -1
  261. package/workflows/container-contents/container-state/createAdoption.js +1 -1
  262. package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
  263. package/workflows/container-contents/container-state/createChild.js +1 -1
  264. package/workflows/container-contents/container-state/createChild.js.map +1 -1
  265. package/workflows/container-contents/container-state/createIntentSync.js +1 -1
  266. package/workflows/container-contents/container-state/createIntentSync.js.map +1 -1
  267. package/workflows/container-contents/container-state/groupGrantVerification.js +1 -1
  268. package/workflows/container-contents/container-state/moveIntentSync.js +1 -1
  269. package/workflows/container-contents/container-state/moveIntentSync.js.map +1 -1
  270. package/workflows/container-contents/container-state/purgeTreeScope.js +1 -1
  271. package/workflows/container-contents/container-state/purgeTreeScope.js.map +1 -1
  272. package/workflows/container-contents/container-state/share.js +1 -1
  273. package/workflows/container-contents/documentDiscoveryInputs.js +1 -1
  274. package/workflows/container-contents/documentDiscoveryInputs.js.map +1 -1
  275. package/workflows/container-contents/documentInfo.d.ts +1 -1
  276. package/workflows/container-contents/documentInfo.js.map +1 -1
  277. package/workflows/container-contents/documentLinks.d.ts +1 -1
  278. package/workflows/container-contents/documentLinks.js +1 -1
  279. package/workflows/container-contents/documentLinks.js.map +1 -1
  280. package/workflows/container-contents/documentMoveIntentSync.js +1 -1
  281. package/workflows/container-contents/documentMoveIntentSync.js.map +1 -1
  282. package/workflows/container-contents/documentPurge.d.ts +1 -1
  283. package/workflows/container-contents/documentPurge.js +1 -1
  284. package/workflows/container-contents/documentPurge.js.map +1 -1
  285. package/workflows/container-contents/documentQueries/rows.js +1 -1
  286. package/workflows/container-contents/documentQueries/rows.js.map +1 -1
  287. package/workflows/container-contents/metadata.d.ts +1 -1
  288. package/workflows/container-contents/metadataMutationPreparation.js +1 -1
  289. package/workflows/container-contents/metadataMutationPreparation.js.map +1 -1
  290. package/workflows/container-contents/metadataRemoteSync.d.ts +1 -1
  291. package/workflows/container-contents/metadataSyncErrors.js.map +1 -1
  292. package/workflows/container-contents/projectionKeys.d.ts +1 -1
  293. package/workflows/container-contents/syncLane.d.ts +1 -1
  294. package/workflows/container-contents/syncLane.js.map +1 -1
  295. package/workflows/containers/child/carriedDescendantRekeys.js +1 -1
  296. package/workflows/containers/child/create.d.ts +1 -1
  297. package/workflows/containers/child/create.js +2 -2
  298. package/workflows/containers/child/create.js.map +1 -1
  299. package/workflows/containers/child/createProjection.js +1 -1
  300. package/workflows/containers/child/createProjection.js.map +1 -1
  301. package/workflows/containers/child/createSubmission.d.ts +2 -2
  302. package/workflows/containers/child/createSubmission.js.map +1 -1
  303. package/workflows/containers/child/move.d.ts +2 -2
  304. package/workflows/containers/child/move.js +2 -2
  305. package/workflows/containers/child/move.js.map +1 -1
  306. package/workflows/containers/child/moveWraps.js +1 -1
  307. package/workflows/containers/child/mutationRequestCore.js +1 -1
  308. package/workflows/containers/child/mutationRequestCore.js.map +1 -1
  309. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  310. package/workflows/containers/child/recite.js.map +1 -1
  311. package/workflows/containers/child/recitePlan.js +1 -1
  312. package/workflows/containers/child/recitePlan.js.map +1 -1
  313. package/workflows/containers/child/rekey.d.ts +1 -1
  314. package/workflows/containers/child/rekey.js +2 -2
  315. package/workflows/containers/child/rekey.js.map +1 -1
  316. package/workflows/containers/child/rekeyProjection.js +1 -1
  317. package/workflows/containers/child/rekeyProjection.js.map +1 -1
  318. package/workflows/containers/child/rekeyRemote.d.ts +2 -2
  319. package/workflows/containers/child/rekeyRemote.js.map +1 -1
  320. package/workflows/containers/child/revoke.d.ts +2 -2
  321. package/workflows/containers/child/revoke.js +2 -2
  322. package/workflows/containers/child/revoke.js.map +1 -1
  323. package/workflows/containers/child/rotationPrincipalPolicies.js +1 -1
  324. package/workflows/containers/child/runtimeCurrentGroupShare.js +1 -1
  325. package/workflows/containers/child/share.d.ts +2 -2
  326. package/workflows/containers/child/share.js +1 -1
  327. package/workflows/containers/child/share.js.map +1 -1
  328. package/workflows/containers/child/shareAncestorRepair.js.map +1 -1
  329. package/workflows/containers/child/shareMaterialization.d.ts +1 -1
  330. package/workflows/containers/child/sharePlanCore.d.ts +1 -1
  331. package/workflows/containers/child/sharePlanCore.js +1 -1
  332. package/workflows/containers/root/create.js +1 -1
  333. package/workflows/containers/root/create.js.map +1 -1
  334. package/workflows/containers/root/initialGroupPolicy.js +1 -1
  335. package/workflows/containers/root/initialGroupPolicy.js.map +1 -1
  336. package/workflows/documents/create.d.ts +1 -1
  337. package/workflows/documents/create.js +1 -1
  338. package/workflows/documents/documentMutationPreparation.js +1 -1
  339. package/workflows/documents/documentMutationPreparation.js.map +1 -1
  340. package/workflows/documents/historyContent.js +1 -1
  341. package/workflows/documents/historyContent.js.map +1 -1
  342. package/workflows/documents/linkSet.js +1 -1
  343. package/workflows/documents/linkSet.js.map +1 -1
  344. package/workflows/documents/linkSetAuthority.js +1 -1
  345. package/workflows/documents/linkSetBlobRewraps.js +2 -2
  346. package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
  347. package/workflows/documents/linkSetRemote.d.ts +1 -1
  348. package/workflows/documents/linkSetRemote.js +1 -1
  349. package/workflows/documents/orphanBlobReclaims.js +1 -1
  350. package/workflows/documents/orphanBlobReclaims.js.map +1 -1
  351. package/workflows/documents/projectionKeys.d.ts +1 -1
  352. package/workflows/documents/purge.d.ts +1 -1
  353. package/workflows/documents/purge.js +2 -2
  354. package/workflows/documents/purge.js.map +1 -1
  355. package/workflows/documents/readOnlySync.d.ts +1 -1
  356. package/workflows/documents/readOnlySync.js +1 -1
  357. package/workflows/documents/readOnlySync.js.map +1 -1
  358. package/workflows/documents/sync.js +1 -1
  359. package/workflows/documents/syncContainerRekeyPreparation.js +1 -1
  360. package/workflows/documents/syncLane.d.ts +1 -1
  361. package/workflows/documents/syncLane.js.map +1 -1
  362. package/workflows/documents/syncPlanIdentity.js +1 -1
  363. package/workflows/documents/syncPlanIdentity.js.map +1 -1
  364. package/workflows/documents/syncRepairAccess.js +1 -1
  365. package/workflows/documents/syncSubmittedResult.js +1 -1
  366. package/workflows/organizations/authoredPrincipalPolicyWarmer.js +1 -1
  367. package/workflows/organizations/authoredPrincipalPolicyWarmer.js.map +1 -1
  368. package/workflows/organizations/containerGrantRevocation.d.ts +2 -2
  369. package/workflows/organizations/containerGrantRevocation.js.map +1 -1
  370. package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -1
  371. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
  372. package/workflows/organizations/currentPolicyMutationAcknowledgement.js +1 -1
  373. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -1
  374. package/workflows/organizations/groupCreation.d.ts +1 -1
  375. package/workflows/organizations/groupCreation.js.map +1 -1
  376. package/workflows/organizations/groupMetadataAccess.d.ts +1 -1
  377. package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
  378. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  379. package/workflows/organizations/groupNameUniqueness.js.map +1 -1
  380. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -1
  381. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  382. package/workflows/organizations/groupPolicyRequests.js.map +1 -1
  383. package/workflows/organizations/loadPolicyHistoryDetails.js.map +1 -1
  384. package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
  385. package/workflows/organizations/organizationProfile.js +1 -1
  386. package/workflows/organizations/organizationProfile.js.map +1 -1
  387. package/workflows/organizations/policyHistoryCache.js.map +1 -1
  388. package/workflows/organizations/principalContainerRematerialization.js +1 -1
  389. package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
  390. package/workflows/organizations/principalMutationJournalManagement.js +1 -1
  391. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -1
  392. package/workflows/organizations/principalMutationReceipt.js +1 -1
  393. package/workflows/organizations/principalMutationReceipt.js.map +1 -1
  394. package/workflows/organizations/principalPolicy.d.ts +1 -1
  395. package/workflows/organizations/principalPolicy.js.map +1 -1
  396. package/workflows/organizations/principalPolicyReceiptArtifacts.js +1 -1
  397. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -1
  398. package/workflows/organizations/rosterProfileContainer.js +1 -1
  399. package/workflows/organizations/rosterProfileContainer.js.map +1 -1
  400. package/workflows/principals/policyCache.d.ts +1 -1
  401. package/workflows/principals/policyCache.js +2 -2
  402. package/workflows/principals/policyCache.js.map +1 -1
  403. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  404. package/workflows/principals/runtimePolicyWarmer.js +1 -1
  405. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  406. package/workflows/registration/persistRegistrationBootstrap.js +1 -1
  407. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  408. package/workflows/runtimeInput.d.ts +3 -3
  409. package/workflows/runtimeInput.js.map +1 -1
  410. package/workflows/sync/index.d.ts +2 -1
  411. package/workflows/sync/index.js +2 -1
  412. package/workflows/sync/index.js.map +1 -1
  413. package/client/blobs.js.map +0 -1
  414. package/client/containerContents.js.map +0 -1
  415. package/client/containerContentsTypes.js +0 -2
  416. package/client/containerContentsTypes.js.map +0 -1
  417. package/client/containerDocumentDiscovery.js.map +0 -1
  418. package/client/database.js.map +0 -1
  419. package/client/deviceFirst.js.map +0 -1
  420. package/client/documents.js.map +0 -1
  421. package/client/identity.js.map +0 -1
  422. package/client/identityKeyPackage.js.map +0 -1
  423. package/client/principalHistoryProtection.js.map +0 -1
  424. package/client/principalMutationApi.js.map +0 -1
  425. package/client/principalMutationDispatch.js.map +0 -1
  426. package/client/reconciledDocumentContentPull.js.map +0 -1
  427. package/client/rootContainerAdoption.js.map +0 -1
  428. package/client/securityIncidents.js.map +0 -1
  429. package/client/userIdentities.js.map +0 -1
  430. package/client/workflowRuntime.js.map +0 -1
  431. package/data/keyingCanonicalJson.js.map +0 -1
  432. package/data/keyingProjectionVerification.d.ts +0 -9
  433. package/data/keyingProjectionVerification.js.map +0 -1
  434. /package/client/{fileSaver.d.ts → host/fileSaver.d.ts} +0 -0
  435. /package/client/{fileSaver.js → host/fileSaver.js} +0 -0
  436. /package/client/{fileSaver.js.map → host/fileSaver.js.map} +0 -0
  437. /package/client/{logger.d.ts → host/logger.d.ts} +0 -0
  438. /package/client/{logger.js → host/logger.js} +0 -0
  439. /package/client/{logger.js.map → host/logger.js.map} +0 -0
  440. /package/client/{apiVersion.d.ts → runtime/apiVersion.d.ts} +0 -0
  441. /package/client/{apiVersion.js → runtime/apiVersion.js} +0 -0
  442. /package/client/{apiVersion.js.map → runtime/apiVersion.js.map} +0 -0
  443. /package/client/{events.d.ts → runtime/events.d.ts} +0 -0
  444. /package/client/{events.js → runtime/events.js} +0 -0
  445. /package/client/{events.js.map → runtime/events.js.map} +0 -0
  446. /package/client/{listenerSet.js → runtime/listenerSet.js} +0 -0
  447. /package/client/{listenerSet.js.map → runtime/listenerSet.js.map} +0 -0
  448. /package/client/{network.d.ts → runtime/network.d.ts} +0 -0
  449. /package/client/{network.js → runtime/network.js} +0 -0
  450. /package/client/{network.js.map → runtime/network.js.map} +0 -0
  451. /package/client/{principalMutationDeadline.js → runtime/principalMutationDeadline.js} +0 -0
  452. /package/client/{principalMutationDeadline.js.map → runtime/principalMutationDeadline.js.map} +0 -0
  453. /package/client/{rootContainerAdoption.js → runtime/rootContainerAdoption.js} +0 -0
  454. /package/client/{syncBillingGate.d.ts → runtime/syncBillingGate.d.ts} +0 -0
  455. /package/client/{syncBillingGate.js → runtime/syncBillingGate.js} +0 -0
  456. /package/client/{syncBillingGate.js.map → runtime/syncBillingGate.js.map} +0 -0
  457. /package/data/{blobContracts.d.ts → blobs/blobContracts.d.ts} +0 -0
  458. /package/data/{blobContracts.js → blobs/blobContracts.js} +0 -0
  459. /package/data/{blobContracts.js.map → blobs/blobContracts.js.map} +0 -0
  460. /package/data/{accessLevel.js → keying/accessLevel.js} +0 -0
  461. /package/data/{accessLevel.js.map → keying/accessLevel.js.map} +0 -0
  462. /package/data/{stableUuid.js → keying/stableUuid.js} +0 -0
  463. /package/data/{stableUuid.js.map → keying/stableUuid.js.map} +0 -0
  464. /package/data/{principalPolicyStates.js → principals/principalPolicyStates.js} +0 -0
  465. /package/data/{principalPolicyStates.js.map → principals/principalPolicyStates.js.map} +0 -0
  466. /package/data/{domainScope.d.ts → shared/domainScope.d.ts} +0 -0
  467. /package/data/{domainScope.js → shared/domainScope.js} +0 -0
  468. /package/data/{domainScope.js.map → shared/domainScope.js.map} +0 -0
  469. /package/data/{errorMessage.js → shared/errorMessage.js} +0 -0
  470. /package/data/{errorMessage.js.map → shared/errorMessage.js.map} +0 -0
  471. /package/data/{recordReaders.d.ts → shared/recordReaders.d.ts} +0 -0
  472. /package/data/{recordReaders.js → shared/recordReaders.js} +0 -0
  473. /package/data/{recordReaders.js.map → shared/recordReaders.js.map} +0 -0
  474. /package/data/{securityIncidents.js → shared/securityIncidents.js} +0 -0
  475. /package/data/{securityIncidents.js.map → shared/securityIncidents.js.map} +0 -0
  476. /package/data/{crdtPeerSeed.js → sync/crdtPeerSeed.js} +0 -0
  477. /package/data/{crdtPeerSeed.js.map → sync/crdtPeerSeed.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicy.js","sourceRoot":"","sources":["principalPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAoB1D,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAClE,OAAO,EAAE,0BAA0B,EAAE,MAAM,sCAAsC,CAAC;AAClF,OAAO,EACL,gBAAgB,EAChB,yBAAyB,EACzB,8BAA8B,GAE/B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,uBAAuB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EACL,8BAA8B,EAC9B,sCAAsC,EACtC,iCAAiC,EACjC,wCAAwC,GACzC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,4CAA4C,EAC5C,4BAA4B,GAC7B,MAAM,8BAA8B,CAAC;AAEtC,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,iBAAiB,EACjB,6BAA6B,GAC9B,MAAM,4BAA4B,CAAC;AAEpC,OAAO,EAAE,8BAA8B,EAAE,oCAAoC,EAAE,CAAC;AA8ChF,SAAS,+BAA+B,CACtC,eAAyC;IAEzC,IAAI,CAAC,eAAe;QAAE,OAAO,SAAS,CAAC;IACvC,OAAO,GAAG,EAAE;QACV,eAAe,EAAE,CAAC;QAClB,OAAO,IAAI,CAAC;IACd,CAAC,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,8BA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C1B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;QAC5D,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,CAAC,CAAC;IACH,MAAM,YAAY,GAAG,MAAM,6BAA6B,CAAC;QACvD,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;QAC5D,OAAO,EAAE,iBAAiB,CAAC,aAAa,CAAC,aAAa,CAAC,iBAAiB,CAAC;KAC1E,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,MAAM,sCAAsC,CAAC;QAC3D,GAAG,aAAa;QAChB,YAAY;QACZ,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC7C,CAAC,CAAC;IACH,OAAO,iCAAiC,CAAC;QACvC,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,aAAa,EAAE,aAAa,CAAC,aAAa;QAC1C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,iBAAiB,EAAE,aAAa,CAAC,iBAAiB;QAClD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;QAC1D,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,aAAa;QACb,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;KAC7D,CAAC,CAAC;AACL,CAAC","sourcesContent":["export { createOrganizationGroup } from \"./groupCreation\";\n\nimport type {\n PrincipalPolicyExternalAuthority,\n ReferencedPrincipalHead,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n PrincipalPolicyBundleResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport { assertGroupMembershipName } from \"./groupMembershipName\";\nimport { prepareAuthoredGroupPolicy } from \"./groupPolicyMutationAcknowledgement\";\nimport {\n cacheGroupPolicy,\n commitGroupPolicyMutation,\n loadGroupPolicyMutationContext,\n type PrincipalPolicyReadWriteApi,\n} from \"./groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\nimport {\n buildAddGroupUserPolicyRequest,\n buildGroupAccessSetShrinkPolicyRequest,\n buildRemoveGroupUserPolicyRequest,\n buildSetGroupContainerGrantPolicyRequest,\n} from \"./groupPolicyRequests\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"./organizationGroupDirectory\";\nimport type { GroupPolicyNameReader } from \"./principalPolicyRequest\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"./principalPolicyRequest\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"./trustedOrganizationUsers\";\n\nexport { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest };\n\ninterface PreparedGroupContainerMutations {\n readonly retiredContainerIds: readonly string[];\n readonly acknowledge: (\n responses: readonly ContainerMutationResponse[],\n stillCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n /** Sign the descendant rekeys a refused commit named; see `carry` there. */\n readonly carry?:\n | ((\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>)\n | undefined;\n readonly requests: readonly ContainerMutationRequest[];\n}\n\ntype PrepareGroupContainerMutations = (input: {\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly nextPolicy: VerifiedPrincipalPolicy;\n}) => Promise<\n readonly ContainerMutationRequest[] | PreparedGroupContainerMutations\n>;\n\ninterface CommitAndCacheGroupPolicyMutationInput {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly beforePolicyCommit?:\n | ((head: ReferencedPrincipalHead) => void)\n | undefined;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority | undefined;\n readonly groupId: string;\n readonly organizationId: string;\n readonly policyContext: Awaited<\n ReturnType<typeof loadGroupPolicyMutationContext>\n >;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nfunction createPolicyMutationCommitGuard(\n assertCanCommit: (() => void) | undefined,\n): (() => boolean) | undefined {\n if (!assertCanCommit) return undefined;\n return () => {\n assertCanCommit();\n return true;\n };\n}\n\n/**\n * Plan the container mutations the policy change rematerializes and place their\n * requests on the policy request. A bare request list has nothing to\n * acknowledge or carry; a prepared batch does both.\n */\nasync function prepareGroupContainerMutations(\n input: CommitAndCacheGroupPolicyMutationInput,\n expectedHead: ReferencedPrincipalHead,\n): Promise<Partial<PreparedGroupContainerMutations> | null> {\n if (!input.prepareContainerMutations) return null;\n const prepared = await input.prepareContainerMutations({\n currentPolicy: input.currentPolicy,\n nextPolicy: await prepareAuthoredGroupPolicy({\n currentPolicy: input.currentPolicy,\n expectedHead,\n request: input.request,\n }),\n });\n if (\"requests\" in prepared) {\n input.request.containerMutations = [...prepared.requests];\n return prepared;\n }\n input.request.containerMutations = [...prepared];\n return {};\n}\n\nasync function commitAndCacheGroupPolicyMutation(\n input: CommitAndCacheGroupPolicyMutationInput,\n): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const stillCurrent = createPolicyMutationCommitGuard(input.assertCanCommit);\n const expectedHead = await groupPolicyMutationHead(input.request);\n input.beforePolicyCommit?.(expectedHead);\n const containerMutations = await prepareGroupContainerMutations(\n input,\n expectedHead,\n );\n const nextAdminProjection = input.policyContext.isOrganizationAdminsGroup\n ? input.request.projection\n : input.policyContext.adminPolicyBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(nextAdminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection: nextAdminProjection,\n adminUsers,\n currentPolicy: input.policyContext.organizationPolicyBundle,\n descriptor: input.policyContext.organizationDescriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: input.policyContext.organizationDescriptor,\n nextHead: expectedHead,\n }),\n signerUserId: input.policyContext.signerUserId,\n signingFingerprint: input.policyContext.signingFingerprint,\n signingKeyPair: input.policyContext.signingKeyPair,\n });\n input.assertCanCommit?.();\n const acknowledgedBundle = await commitGroupPolicyMutation({\n apiClient: input.apiClient,\n carryDescendantRekeys: containerMutations?.carry,\n retiredContainerIds: () => containerMutations?.retiredContainerIds ?? [],\n currentPolicy: input.currentPolicy,\n execSql: input.execSql,\n expectedHead,\n groupId: input.groupId,\n organizationId: input.organizationId,\n organizationPolicy: input.policyContext.organizationPolicyBundle,\n organizationRequest,\n request: input.request,\n stillCurrent,\n });\n input.assertCanCommit?.();\n if (containerMutations?.acknowledge) {\n await containerMutations.acknowledge(\n acknowledgedBundle.containerMutations,\n stillCurrent,\n );\n }\n input.assertCanCommit?.();\n await input.afterPolicyCommitBeforeCache?.();\n input.assertCanCommit?.();\n await cacheGroupPolicy({\n acknowledgedMemberEnvelopes: acknowledgedBundle.currentMemberEnvelopes,\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedCurrentHead: expectedHead,\n externalAuthority: input.externalAuthority,\n groupId: input.groupId,\n localPolicyCheckpoint: {\n principalId: expectedHead.principalId,\n principalType: expectedHead.principalType,\n stateHash: expectedHead.stateHash,\n version: expectedHead.version,\n },\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n input.assertCanCommit?.();\n return acknowledgedBundle;\n}\n\nexport async function addOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly currentUserSecretKey: Uint8Array;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly reportSecurityIncident?: SecurityIncidentReporter | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly targetUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const identities = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [\n ...projectionUserIds(policyContext.currentPolicy.currentProjection),\n input.targetUserId,\n ],\n });\n const targetUser = identities.find(\n (identity) => identity.userId === input.targetUserId,\n );\n if (!targetUser) {\n throw new Error(\n `User identity could not be loaded for ${input.targetUserId}`,\n );\n }\n const request = await buildAddGroupUserPolicyRequest({\n ...policyContext,\n currentUserSecretKey: input.currentUserSecretKey,\n currentUsers: identities.filter(\n (identity) => identity.userId !== input.targetUserId,\n ),\n reportSecurityIncident: input.reportSecurityIncident,\n targetUser,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\nexport async function removeOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly removedUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const removedKey = input.removedUserId;\n const projection = policyContext.currentPolicy.currentProjection.filter(\n (member) => member.userId !== removedKey,\n );\n if (\n projection.length === policyContext.currentPolicy.currentProjection.length\n ) {\n throw new Error(\"User is not a group member\");\n }\n const remainingUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(projection),\n });\n const request = await buildRemoveGroupUserPolicyRequest({\n ...policyContext,\n remainingUsers,\n removedUserId: input.removedUserId,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * Adds or changes one container in the group's signed complete grant set and\n * commits every resulting container rematerialization in the same request.\n */\nexport async function setOrganizationGroupContainerGrant(input: {\n readonly accessLevel: \"admin\" | \"read\" | \"write\";\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly containerId: string;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const request = await buildSetGroupContainerGrantPolicyRequest({\n ...policyContext,\n accessLevel: input.accessLevel,\n containerId: input.containerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n assertCanCommit: input.assertCanCommit,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * A group losing a container grant rotates its own key in the same request as\n * that container revoke and the rekeys of all remaining grants. This prevents\n * a later member from using the group's still-current key to open a retained\n * wrap from before the revoke.\n */\nexport async function rotateOrganizationGroupForAccessSetShrink(input: {\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly revokedContainerId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const currentUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(policyContext.currentPolicy.currentProjection),\n });\n const request = await buildGroupAccessSetShrinkPolicyRequest({\n ...policyContext,\n currentUsers,\n revokedContainerId: input.revokedContainerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n"]}
1
+ {"version":3,"file":"principalPolicy.js","sourceRoot":"","sources":["principalPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,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,OAAO,EAAE,iBAAiB,CAAC,aAAa,CAAC,aAAa,CAAC,iBAAiB,CAAC;KAC1E,CAAC,CAAC;IACH,MAAM,OAAO,GAAG,MAAM,sCAAsC,CAAC;QAC3D,GAAG,aAAa;QAChB,YAAY;QACZ,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC7C,CAAC,CAAC;IACH,OAAO,iCAAiC,CAAC;QACvC,SAAS,EAAE,KAAK,CAAC,SAAS;QAC1B,aAAa,EAAE,aAAa,CAAC,aAAa;QAC1C,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,iBAAiB,EAAE,aAAa,CAAC,iBAAiB;QAClD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,yBAAyB,EAAE,KAAK,CAAC,yBAAyB;QAC1D,OAAO;QACP,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,aAAa;QACb,0BAA0B,EAAE,KAAK,CAAC,0BAA0B;KAC7D,CAAC,CAAC;AACL,CAAC","sourcesContent":["export { createOrganizationGroup } from \"./groupCreation\";\n\nimport type {\n PrincipalPolicyExternalAuthority,\n ReferencedPrincipalHead,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationRequest,\n PutPrincipalPolicyRequest,\n} from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n PrincipalPolicyBundleResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport { assertGroupMembershipName } from \"./groupMembershipName\";\nimport { prepareAuthoredGroupPolicy } from \"./groupPolicyMutationAcknowledgement\";\nimport {\n cacheGroupPolicy,\n commitGroupPolicyMutation,\n loadGroupPolicyMutationContext,\n type PrincipalPolicyReadWriteApi,\n} from \"./groupPolicyMutationContext\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\nimport {\n buildAddGroupUserPolicyRequest,\n buildGroupAccessSetShrinkPolicyRequest,\n buildRemoveGroupUserPolicyRequest,\n buildSetGroupContainerGrantPolicyRequest,\n} from \"./groupPolicyRequests\";\nimport {\n buildOrganizationGroupDirectoryPolicyRequest,\n replaceOrganizationGroupHead,\n} from \"./organizationGroupDirectory\";\nimport type { GroupPolicyNameReader } from \"./principalPolicyRequest\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"./principalPolicyRequest\";\nimport {\n projectionUserIds,\n resolveRequiredUserIdentities,\n} from \"./trustedOrganizationUsers\";\n\nexport { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest };\n\ninterface PreparedGroupContainerMutations {\n readonly retiredContainerIds: readonly string[];\n readonly acknowledge: (\n responses: readonly ContainerMutationResponse[],\n stillCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n /** Sign the descendant rekeys a refused commit named; see `carry` there. */\n readonly carry?:\n | ((\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>)\n | undefined;\n readonly requests: readonly ContainerMutationRequest[];\n}\n\ntype PrepareGroupContainerMutations = (input: {\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly nextPolicy: VerifiedPrincipalPolicy;\n}) => Promise<\n readonly ContainerMutationRequest[] | PreparedGroupContainerMutations\n>;\n\ninterface CommitAndCacheGroupPolicyMutationInput {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly beforePolicyCommit?:\n | ((head: ReferencedPrincipalHead) => void)\n | undefined;\n readonly currentPolicy: PrincipalPolicyBundleResponse;\n readonly execSql: ExecSql;\n readonly externalAuthority: PrincipalPolicyExternalAuthority | undefined;\n readonly groupId: string;\n readonly organizationId: string;\n readonly policyContext: Awaited<\n ReturnType<typeof loadGroupPolicyMutationContext>\n >;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nfunction createPolicyMutationCommitGuard(\n assertCanCommit: (() => void) | undefined,\n): (() => boolean) | undefined {\n if (!assertCanCommit) return undefined;\n return () => {\n assertCanCommit();\n return true;\n };\n}\n\n/**\n * Plan the container mutations the policy change rematerializes and place their\n * requests on the policy request. A bare request list has nothing to\n * acknowledge or carry; a prepared batch does both.\n */\nasync function prepareGroupContainerMutations(\n input: CommitAndCacheGroupPolicyMutationInput,\n expectedHead: ReferencedPrincipalHead,\n): Promise<Partial<PreparedGroupContainerMutations> | null> {\n if (!input.prepareContainerMutations) return null;\n const prepared = await input.prepareContainerMutations({\n currentPolicy: input.currentPolicy,\n nextPolicy: await prepareAuthoredGroupPolicy({\n currentPolicy: input.currentPolicy,\n expectedHead,\n request: input.request,\n }),\n });\n if (\"requests\" in prepared) {\n input.request.containerMutations = [...prepared.requests];\n return prepared;\n }\n input.request.containerMutations = [...prepared];\n return {};\n}\n\nasync function commitAndCacheGroupPolicyMutation(\n input: CommitAndCacheGroupPolicyMutationInput,\n): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const stillCurrent = createPolicyMutationCommitGuard(input.assertCanCommit);\n const expectedHead = await groupPolicyMutationHead(input.request);\n input.beforePolicyCommit?.(expectedHead);\n const containerMutations = await prepareGroupContainerMutations(\n input,\n expectedHead,\n );\n const nextAdminProjection = input.policyContext.isOrganizationAdminsGroup\n ? input.request.projection\n : input.policyContext.adminPolicyBundle.currentProjection;\n const adminUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(nextAdminProjection),\n });\n const organizationRequest =\n await buildOrganizationGroupDirectoryPolicyRequest({\n adminProjection: nextAdminProjection,\n adminUsers,\n currentPolicy: input.policyContext.organizationPolicyBundle,\n descriptor: input.policyContext.organizationDescriptor,\n groupHeads: replaceOrganizationGroupHead({\n descriptor: input.policyContext.organizationDescriptor,\n nextHead: expectedHead,\n }),\n signerUserId: input.policyContext.signerUserId,\n signingFingerprint: input.policyContext.signingFingerprint,\n signingKeyPair: input.policyContext.signingKeyPair,\n });\n input.assertCanCommit?.();\n const acknowledgedBundle = await commitGroupPolicyMutation({\n apiClient: input.apiClient,\n carryDescendantRekeys: containerMutations?.carry,\n retiredContainerIds: () => containerMutations?.retiredContainerIds ?? [],\n currentPolicy: input.currentPolicy,\n execSql: input.execSql,\n expectedHead,\n groupId: input.groupId,\n organizationId: input.organizationId,\n organizationPolicy: input.policyContext.organizationPolicyBundle,\n organizationRequest,\n request: input.request,\n stillCurrent,\n });\n input.assertCanCommit?.();\n if (containerMutations?.acknowledge) {\n await containerMutations.acknowledge(\n acknowledgedBundle.containerMutations,\n stillCurrent,\n );\n }\n input.assertCanCommit?.();\n await input.afterPolicyCommitBeforeCache?.();\n input.assertCanCommit?.();\n await cacheGroupPolicy({\n acknowledgedMemberEnvelopes: acknowledgedBundle.currentMemberEnvelopes,\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedCurrentHead: expectedHead,\n externalAuthority: input.externalAuthority,\n groupId: input.groupId,\n localPolicyCheckpoint: {\n principalId: expectedHead.principalId,\n principalType: expectedHead.principalType,\n stateHash: expectedHead.stateHash,\n version: expectedHead.version,\n },\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent,\n });\n input.assertCanCommit?.();\n return acknowledgedBundle;\n}\n\nexport async function addOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly currentUserSecretKey: Uint8Array;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly reportSecurityIncident?: SecurityIncidentReporter | undefined;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly targetUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const identities = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: [\n ...projectionUserIds(policyContext.currentPolicy.currentProjection),\n input.targetUserId,\n ],\n });\n const targetUser = identities.find(\n (identity) => identity.userId === input.targetUserId,\n );\n if (!targetUser) {\n throw new Error(\n `User identity could not be loaded for ${input.targetUserId}`,\n );\n }\n const request = await buildAddGroupUserPolicyRequest({\n ...policyContext,\n currentUserSecretKey: input.currentUserSecretKey,\n currentUsers: identities.filter(\n (identity) => identity.userId !== input.targetUserId,\n ),\n reportSecurityIncident: input.reportSecurityIncident,\n targetUser,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\nexport async function removeOrganizationGroupUser(input: {\n readonly afterPolicyCommitBeforeCache?: (() => Promise<void>) | undefined;\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly expectedGroupName: string;\n readonly readEncryptedName?: GroupPolicyNameReader;\n readonly groupId: string;\n readonly organizationId: string;\n readonly removedUserId: string;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly beforePolicyCommit: (\n head: ReferencedPrincipalHead,\n authority: {\n readonly adminGroupId: string;\n readonly memberGroupId: string;\n },\n ) => void;\n readonly prepareContainerMutations?:\n | PrepareGroupContainerMutations\n | undefined;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const policyContext = await loadGroupPolicyMutationContext(input);\n await assertGroupMembershipName(\n policyContext.currentPolicy,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n const removedKey = input.removedUserId;\n const projection = policyContext.currentPolicy.currentProjection.filter(\n (member) => member.userId !== removedKey,\n );\n if (\n projection.length === policyContext.currentPolicy.currentProjection.length\n ) {\n throw new Error(\"User is not a group member\");\n }\n const remainingUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(projection),\n });\n const request = await buildRemoveGroupUserPolicyRequest({\n ...policyContext,\n remainingUsers,\n removedUserId: input.removedUserId,\n });\n return commitAndCacheGroupPolicyMutation({\n afterPolicyCommitBeforeCache: input.afterPolicyCommitBeforeCache,\n apiClient: input.apiClient,\n beforePolicyCommit: (head) =>\n input.beforePolicyCommit(head, {\n adminGroupId: policyContext.adminGroupId,\n memberGroupId: policyContext.memberGroupId,\n }),\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * Adds or changes one container in the group's signed complete grant set and\n * commits every resulting container rematerialization in the same request.\n */\nexport async function setOrganizationGroupContainerGrant(input: {\n readonly accessLevel: \"admin\" | \"read\" | \"write\";\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly assertCanCommit?: (() => void) | undefined;\n readonly containerId: string;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const request = await buildSetGroupContainerGrantPolicyRequest({\n ...policyContext,\n accessLevel: input.accessLevel,\n containerId: input.containerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n assertCanCommit: input.assertCanCommit,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n\n/**\n * A group losing a container grant rotates its own key in the same request as\n * that container revoke and the rekeys of all remaining grants. This prevents\n * a later member from using the group's still-current key to open a retained\n * wrap from before the revoke.\n */\nexport async function rotateOrganizationGroupForAccessSetShrink(input: {\n readonly apiClient: PrincipalPolicyReadWriteApi;\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly revokedContainerId: string;\n readonly prepareContainerMutations: PrepareGroupContainerMutations;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly signerUserId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n}): Promise<PrincipalPolicyBundleResponse & PrincipalPolicyMutationResponse> {\n const policyContext = await loadGroupPolicyMutationContext({\n apiClient: input.apiClient,\n execSql: input.execSql,\n groupId: input.groupId,\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.signerUserId,\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const currentUsers = await resolveRequiredUserIdentities({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n userIds: projectionUserIds(policyContext.currentPolicy.currentProjection),\n });\n const request = await buildGroupAccessSetShrinkPolicyRequest({\n ...policyContext,\n currentUsers,\n revokedContainerId: input.revokedContainerId,\n });\n return commitAndCacheGroupPolicyMutation({\n apiClient: input.apiClient,\n currentPolicy: policyContext.currentPolicy,\n execSql: input.execSql,\n externalAuthority: policyContext.externalAuthority,\n groupId: input.groupId,\n prepareContainerMutations: input.prepareContainerMutations,\n request,\n organizationId: input.organizationId,\n policyContext,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { compareCanonicalStrings, normalizePrincipalContainerGrants, normalizePrincipalProjectionMembers, } from "../../internal/crypto/index.js";
2
- import { canonicalKeyingJsonString } from "../../data/keyingCanonicalJson.js";
2
+ import { canonicalKeyingJsonString } from "../../data/keying/canonicalJson.js";
3
3
  function sortedCanonicalValues(values, label) {
4
4
  return [...values].sort((left, right) => compareCanonicalStrings(canonicalKeyingJsonString(left, label), canonicalKeyingJsonString(right, label)));
5
5
  }
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,iCAAiC,E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KAAK,CAAC,aAAa;QAChD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,SAAS,EAAE,KAAK,CAAC,YAAY,CAAC,SAAS;QACvC,GAAG,KAAK,CAAC,OAAO,CAAC,gBAAgB;KAClC,CAAC;IAEF,IACE,yBAAyB,CACvB,eAAe,EACf,6BAA6B,CAC9B;QACC,yBAAyB,CACvB,eAAe,EACf,+BAA+B,CAChC;QACH,yBAAyB,CACvB,mCAAmC,CAAC,KAAK,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EACrE,gCAAgC,CACjC;YACC,yBAAyB,CACvB,mCAAmC,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,EAC7D,kCAAkC,CACnC;QACH,yBAAyB,CACvB,iCAAiC,CAAC,KAAK,CAAC,QAAQ,CAAC,aAAa,CAAC,EAC/D,4BAA4B,CAC7B;YACC,yBAAyB,CACvB,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EACvD,8BAA8B,CAC/B,EACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAClE,CAAC;IAED,8CAA8C,CAC5C;QACE,aAAa,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,aAAa;QAChD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,SAAS,EAAE,KAAK,CAAC,YAAY,CAAC,SAAS;QACvC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ;QACnC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,eAAe;KACzC,EACD,KAAK,CAAC,QAAQ,CAAC,sBAAsB,CACtC,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../data/keyingCanonicalJson\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\nfunction assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): void {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const expected = {\n body: request.body,\n event: request.event,\n keyEpoch: request.keyEpoch,\n manifest: request.manifest,\n wraps: sortedCanonicalValues(request.wraps, \"authored container wrap\"),\n };\n const observed = {\n body: response.accessManifest.event.body,\n event: response.accessManifest.event.event,\n keyEpoch: response.containerKek.keyEpoch,\n manifest: response.accessManifest.manifest,\n wraps: sortedCanonicalValues(\n response.containerKek.wraps,\n \"stored container wrap\",\n ),\n };\n if (\n canonicalKeyingJsonString(\n observed,\n \"stored group policy container mutation\",\n ) !==\n canonicalKeyingJsonString(\n expected,\n \"authored group policy container mutation\",\n )\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/** Compare receipt artifacts without manufacturing predecessor history or pins. */\nexport function assertPrincipalPolicyReceiptArtifacts(input: {\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): void {\n assertContainerMutationAcknowledgements({\n requests: input.request.containerMutations ?? [],\n responses: input.response.containerMutations,\n });\n const { createdAt: _payloadCreatedAt, ...observedPayload } =\n input.response.currentPayload;\n const expectedPayload = {\n principalType: input.request.state.principalType,\n principalId: input.request.state.principalId,\n stateHash: input.expectedHead.stateHash,\n ...input.request.encryptedPayload,\n };\n\n if (\n canonicalKeyingJsonString(\n observedPayload,\n \"stored group policy payload\",\n ) !==\n canonicalKeyingJsonString(\n expectedPayload,\n \"authored group policy payload\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(input.response.currentProjection),\n \"stored group policy projection\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(input.request.projection),\n \"authored group policy projection\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(input.response.currentGrants),\n \"stored group policy grants\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(input.request.grants),\n \"authored group policy grants\",\n )\n ) {\n throw new Error(\"Group policy bundle acknowledgement mismatch\");\n }\n\n assertGroupPolicyEnvelopesMatchAcknowledgement(\n {\n principalType: input.request.state.principalType,\n principalId: input.request.state.principalId,\n stateHash: input.expectedHead.stateHash,\n epoch: input.request.state.keyEpoch,\n envelopes: input.request.memberEnvelopes,\n },\n input.response.currentMemberEnvelopes,\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyReceiptArtifacts.js","sourceRoot":"","sources":["principalPolicyReceiptArtifacts.ts"],"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AAe,GAAG;QACtB,aAAa,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,aAAa;QAChD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,SAAS,EAAE,KAAK,CAAC,YAAY,CAAC,SAAS;QACvC,GAAG,KAAK,CAAC,OAAO,CAAC,gBAAgB;KAClC,CAAC;IAEF,IACE,yBAAyB,CACvB,eAAe,EACf,6BAA6B,CAC9B;QACC,yBAAyB,CACvB,eAAe,EACf,+BAA+B,CAChC;QACH,yBAAyB,CACvB,mCAAmC,CAAC,KAAK,CAAC,QAAQ,CAAC,iBAAiB,CAAC,EACrE,gCAAgC,CACjC;YACC,yBAAyB,CACvB,mCAAmC,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,EAC7D,kCAAkC,CACnC;QACH,yBAAyB,CACvB,iCAAiC,CAAC,KAAK,CAAC,QAAQ,CAAC,aAAa,CAAC,EAC/D,4BAA4B,CAC7B;YACC,yBAAyB,CACvB,iCAAiC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,EACvD,8BAA8B,CAC/B,EACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,8CAA8C,CAAC,CAAC;IAClE,CAAC;IAED,8CAA8C,CAC5C;QACE,aAAa,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,aAAa;QAChD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;QAC5C,SAAS,EAAE,KAAK,CAAC,YAAY,CAAC,SAAS;QACvC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ;QACnC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC,eAAe;KACzC,EACD,KAAK,CAAC,QAAQ,CAAC,sBAAsB,CACtC,CAAC;AACJ,CAAC","sourcesContent":["import {\n compareCanonicalStrings,\n normalizePrincipalContainerGrants,\n normalizePrincipalProjectionMembers,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n CurrentPrincipalMemberEnvelopesResponse,\n PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../data/keying/canonicalJson\";\n\nfunction sortedCanonicalValues<T>(values: readonly T[], label: string): T[] {\n return [...values].sort((left, right) =>\n compareCanonicalStrings(\n canonicalKeyingJsonString(left, label),\n canonicalKeyingJsonString(right, label),\n ),\n );\n}\n\nexport function assertGroupPolicyEnvelopesMatchAcknowledgement(\n expected: CurrentPrincipalMemberEnvelopesResponse,\n observed: CurrentPrincipalMemberEnvelopesResponse,\n): void {\n const normalized = (value: CurrentPrincipalMemberEnvelopesResponse) => ({\n ...value,\n envelopes: sortedCanonicalValues(\n value.envelopes,\n \"principal member envelope\",\n ),\n });\n if (\n canonicalKeyingJsonString(\n normalized(expected),\n \"acknowledged group member envelopes\",\n ) !==\n canonicalKeyingJsonString(\n normalized(observed),\n \"observed group member envelopes\",\n )\n ) {\n throw new Error(\"Group member envelopes changed after acknowledgement\");\n }\n}\n\nfunction assertContainerMutationAcknowledgements(input: {\n readonly requests: readonly NonNullable<\n PutPrincipalPolicyRequest[\"containerMutations\"]\n >[number][];\n readonly responses: readonly ContainerMutationResponse[] | undefined;\n}): void {\n if (!input.responses || input.responses.length !== input.requests.length) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n for (const [index, request] of input.requests.entries()) {\n const response = input.responses[index];\n if (!response) {\n throw new Error(\n \"Group policy container acknowledgement batch is incomplete\",\n );\n }\n const expected = {\n body: request.body,\n event: request.event,\n keyEpoch: request.keyEpoch,\n manifest: request.manifest,\n wraps: sortedCanonicalValues(request.wraps, \"authored container wrap\"),\n };\n const observed = {\n body: response.accessManifest.event.body,\n event: response.accessManifest.event.event,\n keyEpoch: response.containerKek.keyEpoch,\n manifest: response.accessManifest.manifest,\n wraps: sortedCanonicalValues(\n response.containerKek.wraps,\n \"stored container wrap\",\n ),\n };\n if (\n canonicalKeyingJsonString(\n observed,\n \"stored group policy container mutation\",\n ) !==\n canonicalKeyingJsonString(\n expected,\n \"authored group policy container mutation\",\n )\n ) {\n throw new Error(\"Group policy container acknowledgement mismatch\");\n }\n }\n}\n\n/** Compare receipt artifacts without manufacturing predecessor history or pins. */\nexport function assertPrincipalPolicyReceiptArtifacts(input: {\n readonly expectedHead: ReferencedPrincipalHead;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}): void {\n assertContainerMutationAcknowledgements({\n requests: input.request.containerMutations ?? [],\n responses: input.response.containerMutations,\n });\n const { createdAt: _payloadCreatedAt, ...observedPayload } =\n input.response.currentPayload;\n const expectedPayload = {\n principalType: input.request.state.principalType,\n principalId: input.request.state.principalId,\n stateHash: input.expectedHead.stateHash,\n ...input.request.encryptedPayload,\n };\n\n if (\n canonicalKeyingJsonString(\n observedPayload,\n \"stored group policy payload\",\n ) !==\n canonicalKeyingJsonString(\n expectedPayload,\n \"authored group policy payload\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(input.response.currentProjection),\n \"stored group policy projection\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalProjectionMembers(input.request.projection),\n \"authored group policy projection\",\n ) ||\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(input.response.currentGrants),\n \"stored group policy grants\",\n ) !==\n canonicalKeyingJsonString(\n normalizePrincipalContainerGrants(input.request.grants),\n \"authored group policy grants\",\n )\n ) {\n throw new Error(\"Group policy bundle acknowledgement mismatch\");\n }\n\n assertGroupPolicyEnvelopesMatchAcknowledgement(\n {\n principalType: input.request.state.principalType,\n principalId: input.request.state.principalId,\n stateHash: input.expectedHead.stateHash,\n epoch: input.request.state.keyEpoch,\n envelopes: input.request.memberEnvelopes,\n },\n input.response.currentMemberEnvelopes,\n );\n}\n"]}
@@ -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,CAAC;AAEnD,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EACL,4BAA4B,EAC5B,yBAAyB,GAC1B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,uDAAuD,CAAC;AAE3F,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 { 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
+ {"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AAC,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,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,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,kCAAkC,EAClC,gCAAgC,GACjC,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAE,6BAA6B,EAAE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5D,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,4BAA4B,GAG7B,MAAM,oCAAoC,CAAC;AAkB5C,SAAS,yBAAyB,CAChC,SAA2C;IAE3C,OAAO,GAAG,SAAS,CAAC,aAAa,IAAI,SA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O;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"]}
@@ -1 +1 @@
1
- {"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAIpC,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAKzG,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,oCAAoC,CAAC;AAczF,6FAA6F;AAC7F,MAAM,UAAU,oCAAoC,CAClD,OAAuC,EACvC,UAAqD,EAAE;IAEvD,MAAM,OAAO,GAAG,2CAA2C,CAAC,OAAO,CAAC,CAAC;IACrE,OAAO,OAAO;QACZ,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CACR,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,kBAAkB,EAAE,OAAO,CAAC,kBAAkB,EAAE,CAAC;QACzE,CAAC,CAAC,SAAS,CAAC;AAChB,CAAC;AAiBD,wFAAwF;AACxF,MAAM,UAAU,2CAA2C,CACzD,OAAuC;IAMvC,MAAM,KAAK,GAAG,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACtD,MAAM,aAAa,GAAG,4BAA4B,CAAC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KAAK,YAAY,uBAAuB;oBACvC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;gBAEtC,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACJ,CAAC;AACN,CAAC;AAED,SAAS,wBAAwB,CAAC,KAAoC;IACpE,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO;IAC/B,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC;IAC/C,IACE,CAAC,KAAK,CAAC,SAAS;QAChB,CAAC,MAAM,KAAK,SAAS;YACnB,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;gBAC5B,MAAM,IAAI,CAAC;gBACX,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;QAE1C,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,iEAAiE,CAClE,CAAC;AACN,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyResolveRequest,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport { createPrincipalCurrentRecoveryBatch } from \"./principalCurrentRecoveryBatch\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyHistoryReader,\n} from \"./principalPolicyHistoryReader\";\nimport { recoverWithPrincipalLocalPreference } from \"./principalRecoveryLocalPreference\";\nimport type { ScopedPrincipalPolicyRecovery } from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<PrincipalPolicyHistoryReader>;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: { readonly reportSecurityIncident: SecurityIncidentReporter };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\n/** Keep the private recovery key inside its runtime lease while resolving cited evidence. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n options: { readonly preferLocalCurrent?: boolean } = {},\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const resolve = createRuntimePrincipalPolicyCurrentResolver(runtime);\n return resolve\n ? (input) =>\n resolve({ ...input, preferLocalCurrent: options.preferLocalCurrent })\n : undefined;\n}\n\nexport interface ResolvedPrincipalPolicyCurrent\n extends ResolvedPrincipalPolicyEvidence {\n readonly current: PrincipalPolicyPageCurrent;\n /** Rows end at the selected reference; current/policy may describe a newer recovered head. */\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\ninterface PrincipalPolicyCurrentRequest\n extends Omit<PrincipalPolicyResolveRequest, \"reference\"> {\n readonly reference?: PrincipalPolicyResolveRequest[\"reference\"] | undefined;\n /** A read-model caller has selected this exact signed head; not a freshness read. */\n readonly preferLocalCurrent?: boolean | undefined;\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\n/** Keep current artifacts with their verified evidence and private runtime lifetime. */\nexport function createRuntimePrincipalPolicyCurrentResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n):\n | ((\n input: PrincipalPolicyCurrentRequest,\n ) => Promise<ResolvedPrincipalPolicyCurrent>)\n | undefined {\n const lease = readPrincipalHistoryProtection(runtime);\n const historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);\n if (!lease || !historyReader) return undefined;\n const batches = new WeakMap<\n object,\n ReturnType<typeof createPrincipalCurrentRecoveryBatch>\n >();\n const recoverFor = (batch: object | undefined) => {\n if (!batch) return createPrincipalCurrentRecoveryBatch();\n let recover = batches.get(batch);\n if (!recover) {\n recover = createPrincipalCurrentRecoveryBatch();\n batches.set(batch, recover);\n }\n return recover;\n };\n return (input) =>\n getOrCreatePrincipalPolicyCoordinator(runtime.infra.execSql).queueRecovery(\n input.organizationId,\n () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.reference?.principalId ?? input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n assertHistoryPageRequest(input);\n const offline = runtime.state?.online === false;\n try {\n const options = {\n historyReader,\n execSql: runtime.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n resolveTrustedUserIdentity:\n runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const batch = recoverFor(input.recoveryBatch);\n const result: ScopedPrincipalPolicyRecovery = input.reference\n ? await recoverWithPrincipalLocalPreference(\n batch.recover,\n {\n ...options,\n reference: input.reference,\n historyPage: input.historyPage,\n },\n input.preferLocalCurrent === true ||\n input.preferLocalHistory === true,\n input.preferLocalHistory === true,\n )\n : await batch.discover(options);\n // Reused evidence stays bound to every producer lifetime.\n const resultCurrent = () =>\n stillCurrent() && result.stillCurrent();\n assertProjectionVerificationCurrent(resultCurrent);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\n stillCurrent: resultCurrent,\n };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n error instanceof PrincipalHistoryRecoveryRaceError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n\nfunction assertHistoryPageRequest(input: PrincipalPolicyCurrentRequest) {\n if (!input.historyPage) return;\n const before = input.historyPage.beforeVersion;\n if (\n !input.reference ||\n (before !== undefined &&\n (!Number.isSafeInteger(before) ||\n before <= 1 ||\n before > input.reference.version + 1))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"History display requires a selected head and an in-range cursor\",\n );\n}\n"]}
1
+ {"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAIpC,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AAKzG,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AACtF,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAChC,MAAM,iCAAiC,CAAC;AACzC,OAAO,EACL,4BAA4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urrent } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyResolveRequest,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { RecoveredPrincipalHistoryPage } from \"./loadRecoveredPrincipalHistoryPage\";\nimport { createPrincipalCurrentRecoveryBatch } from \"./principalCurrentRecoveryBatch\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./principalHistoryRecoveryTypes\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyHistoryReader,\n} from \"./principalPolicyHistoryReader\";\nimport { recoverWithPrincipalLocalPreference } from \"./principalRecoveryLocalPreference\";\nimport type { ScopedPrincipalPolicyRecovery } from \"./recoverScopedPrincipalPolicyHistory\";\n\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<PrincipalPolicyHistoryReader>;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: { readonly reportSecurityIncident: SecurityIncidentReporter };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\n/** Keep the private recovery key inside its runtime lease while resolving cited evidence. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n options: { readonly preferLocalCurrent?: boolean } = {},\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const resolve = createRuntimePrincipalPolicyCurrentResolver(runtime);\n return resolve\n ? (input) =>\n resolve({ ...input, preferLocalCurrent: options.preferLocalCurrent })\n : undefined;\n}\n\nexport interface ResolvedPrincipalPolicyCurrent\n extends ResolvedPrincipalPolicyEvidence {\n readonly current: PrincipalPolicyPageCurrent;\n /** Rows end at the selected reference; current/policy may describe a newer recovered head. */\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\ninterface PrincipalPolicyCurrentRequest\n extends Omit<PrincipalPolicyResolveRequest, \"reference\"> {\n readonly reference?: PrincipalPolicyResolveRequest[\"reference\"] | undefined;\n /** A read-model caller has selected this exact signed head; not a freshness read. */\n readonly preferLocalCurrent?: boolean | undefined;\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\n/** Keep current artifacts with their verified evidence and private runtime lifetime. */\nexport function createRuntimePrincipalPolicyCurrentResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n):\n | ((\n input: PrincipalPolicyCurrentRequest,\n ) => Promise<ResolvedPrincipalPolicyCurrent>)\n | undefined {\n const lease = readPrincipalHistoryProtection(runtime);\n const historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);\n if (!lease || !historyReader) return undefined;\n const batches = new WeakMap<\n object,\n ReturnType<typeof createPrincipalCurrentRecoveryBatch>\n >();\n const recoverFor = (batch: object | undefined) => {\n if (!batch) return createPrincipalCurrentRecoveryBatch();\n let recover = batches.get(batch);\n if (!recover) {\n recover = createPrincipalCurrentRecoveryBatch();\n batches.set(batch, recover);\n }\n return recover;\n };\n return (input) =>\n getOrCreatePrincipalPolicyCoordinator(runtime.infra.execSql).queueRecovery(\n input.organizationId,\n () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.reference?.principalId ?? input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n assertHistoryPageRequest(input);\n const offline = runtime.state?.online === false;\n try {\n const options = {\n historyReader,\n execSql: runtime.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n resolveTrustedUserIdentity:\n runtime.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const batch = recoverFor(input.recoveryBatch);\n const result: ScopedPrincipalPolicyRecovery = input.reference\n ? await recoverWithPrincipalLocalPreference(\n batch.recover,\n {\n ...options,\n reference: input.reference,\n historyPage: input.historyPage,\n },\n input.preferLocalCurrent === true ||\n input.preferLocalHistory === true,\n input.preferLocalHistory === true,\n )\n : await batch.discover(options);\n // Reused evidence stays bound to every producer lifetime.\n const resultCurrent = () =>\n stillCurrent() && result.stillCurrent();\n assertProjectionVerificationCurrent(resultCurrent);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\n stillCurrent: resultCurrent,\n };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n error instanceof PrincipalHistoryRecoveryRaceError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n\nfunction assertHistoryPageRequest(input: PrincipalPolicyCurrentRequest) {\n if (!input.historyPage) return;\n const before = input.historyPage.beforeVersion;\n if (\n !input.reference ||\n (before !== undefined &&\n (!Number.isSafeInteger(before) ||\n before <= 1 ||\n before > input.reference.version + 1))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"History display requires a selected head and an in-range cursor\",\n );\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { errorMessage } from "../../data/errorMessage.js";
2
1
  import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
3
2
  import { rethrowKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
4
3
  import { assertProjectionVerificationCurrent, isProjectionVerificationCancelledError, } from "../../data/keyingProjectionVerification/types.js";
4
+ import { errorMessage } from "../../data/shared/errorMessage.js";
5
5
  import { createRuntimePrincipalPolicyResolver, } from "./runtimePolicyRecovery.js";
6
6
  import { createRuntimeProjectionPolicyResolver } from "./runtimeProjectionPolicyRecovery.js";
7
7
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"runtimePolicyWarmer.js","sourceRoot":"","sources":["runtimePolicyWarmer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GAEvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,oCAAoC,GAErC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAW1F;;;;;GAKG;AACH,MAAM,UAAU,kCAAkC,CAChD,OAAmC,EACnC,UAAqD,EAAE;IAEvD,MAAM,OAAO,GAAG,oCAAoC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACvE,MAAM,SAAS,GAAG,EAAE,CAAC;IACrB,MAAM,gBAAgB,GAAmB,KAAK,EAAE,KAAK,EAAE,EAAE;QACvD,IAAI,CAAC,OAAO;YACV,MAAM,IAAI,oCAAoC,CAC5C,mDAAmD,CACpD,CAAC;QACJ,OAAO,OAAO,CAAC;YACb,GAAG,KAAK;YACR,aAAa,EAAE,KAAK,CAAC,aAAa,IAAI,SAAS;SAChD,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO,MAAM,CAAC,MAAM,CAClB,CAAC,KAAqD,EAAE,EAAE,CACxD,kBAAkB,CAAC,OAAO,EAAE,gBAAgB,EAAE,KAAK,CAAC,EACtD;QACE,gBAAgB;QAChB,wBAAwB,EAAE,qCAAqC,CAAC,OAAO,CAAC;KACzE,CACF,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,kBAAkB,CAC/B,OAAmC,EACnC,OAAuB,EACvB,KAAqD;IAErD,KAAK,MAAM,SAAS,IAAI,KAAK,CAAC,UAAU,EAAE,CAAC;QACzC,IAAI,CAAC;YACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACxD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;YACxD,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;QAC7D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,sCAAsC,CAAC,KAAK,CAAC;gBAAE,OAAO;YAC1D,0EAA0E;YAC1E,8BAA8B,CAAC,KAAK,CAAC,CAAC;YACtC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAChB,8BAA8B,SAAS,CAAC,WAAW,KAAK,YAAY,CAAC,KAAK,CAAC,EAAE,CAC9E,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { errorMessage } from \"../../data/errorMessage\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n isProjectionVerificationCancelledError,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport {\n createRuntimePrincipalPolicyResolver,\n type PrincipalPolicyRecoveryRuntime,\n} from \"./runtimePolicyRecovery\";\nimport { createRuntimeProjectionPolicyResolver } from \"./runtimeProjectionPolicyRecovery\";\n\ntype PolicyResolver = NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveReference\"]\n>;\ninterface PrincipalPolicyWarmRuntime extends PrincipalPolicyRecoveryRuntime {\n readonly util: PrincipalPolicyRecoveryRuntime[\"util\"] & {\n readonly log?: ((message: string) => void) | undefined;\n };\n}\n\n/**\n * One warmer serves one workflow operation; create it per operation. Its\n * projection collections share one authenticated directory view, discovered\n * once per operation and discarded with the warmer. Prefetch is best-effort;\n * exact resolution still rejects unavailable evidence.\n */\nexport function createRuntimePrincipalPolicyWarmer(\n runtime: PrincipalPolicyWarmRuntime,\n options: { readonly preferLocalCurrent?: boolean } = {},\n): ReferencedPrincipalPolicyWarmer {\n const resolve = createRuntimePrincipalPolicyResolver(runtime, options);\n const operation = {};\n const resolveReference: PolicyResolver = async (input) => {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Principal policies require private paged recovery\",\n );\n return resolve({\n ...input,\n recoveryBatch: input.recoveryBatch ?? operation,\n });\n };\n return Object.assign(\n (input: Parameters<ReferencedPrincipalPolicyWarmer>[0]) =>\n prefetchReferences(runtime, resolveReference, input),\n {\n resolveReference,\n resolveProjectionHistory: createRuntimeProjectionPolicyResolver(runtime),\n },\n );\n}\n\nasync function prefetchReferences(\n runtime: PrincipalPolicyWarmRuntime,\n resolve: PolicyResolver,\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n): Promise<void> {\n for (const reference of input.references) {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await resolve({ ...input, reference });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return;\n // Recovery already reports signature/authority failures. Keep them fatal.\n rethrowKeyingVerificationError(error);\n runtime.util.log?.(\n `Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`,\n );\n }\n }\n}\n"]}
1
+ {"version":3,"file":"runtimePolicyWarm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ACxD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC;YACxD,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;QAC7D,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,sCAAsC,CAAC,KAAK,CAAC;gBAAE,OAAO;YAC1D,0EAA0E;YAC1E,8BAA8B,CAAC,KAAK,CAAC,CAAC;YACtC,OAAO,CAAC,IAAI,CAAC,GAAG,EAAE,CAChB,8BAA8B,SAAS,CAAC,WAAW,KAAK,YAAY,CAAC,KAAK,CAAC,EAAE,CAC9E,CAAC;QACJ,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n isProjectionVerificationCancelledError,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport {\n createRuntimePrincipalPolicyResolver,\n type PrincipalPolicyRecoveryRuntime,\n} from \"./runtimePolicyRecovery\";\nimport { createRuntimeProjectionPolicyResolver } from \"./runtimeProjectionPolicyRecovery\";\n\ntype PolicyResolver = NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveReference\"]\n>;\ninterface PrincipalPolicyWarmRuntime extends PrincipalPolicyRecoveryRuntime {\n readonly util: PrincipalPolicyRecoveryRuntime[\"util\"] & {\n readonly log?: ((message: string) => void) | undefined;\n };\n}\n\n/**\n * One warmer serves one workflow operation; create it per operation. Its\n * projection collections share one authenticated directory view, discovered\n * once per operation and discarded with the warmer. Prefetch is best-effort;\n * exact resolution still rejects unavailable evidence.\n */\nexport function createRuntimePrincipalPolicyWarmer(\n runtime: PrincipalPolicyWarmRuntime,\n options: { readonly preferLocalCurrent?: boolean } = {},\n): ReferencedPrincipalPolicyWarmer {\n const resolve = createRuntimePrincipalPolicyResolver(runtime, options);\n const operation = {};\n const resolveReference: PolicyResolver = async (input) => {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Principal policies require private paged recovery\",\n );\n return resolve({\n ...input,\n recoveryBatch: input.recoveryBatch ?? operation,\n });\n };\n return Object.assign(\n (input: Parameters<ReferencedPrincipalPolicyWarmer>[0]) =>\n prefetchReferences(runtime, resolveReference, input),\n {\n resolveReference,\n resolveProjectionHistory: createRuntimeProjectionPolicyResolver(runtime),\n },\n );\n}\n\nasync function prefetchReferences(\n runtime: PrincipalPolicyWarmRuntime,\n resolve: PolicyResolver,\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n): Promise<void> {\n for (const reference of input.references) {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await resolve({ ...input, reference });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return;\n // Recovery already reports signature/authority failures. Keep them fatal.\n rethrowKeyingVerificationError(error);\n runtime.util.log?.(\n `Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`,\n );\n }\n }\n}\n"]}
@@ -1,5 +1,4 @@
1
1
  import { createDocument, encodeVersionVector, importUpdates, } from "../../internal/loro/index.js";
2
- import { getScopedPeerSeed } from "../../data/crdtPeerSeed.js";
3
2
  import { createPendingUpdateFields } from "../../data/documents/documentSync.js";
4
3
  import { sqlContainerContentsPersistence, } from "../../data/persistence/container-contents/containerContentsPersistence.js";
5
4
  import { primeAuthoredDocumentDiscoveryHeads, } from "../../data/persistence/documents/documentDiscoveryEvidencePersistence.js";
@@ -8,6 +7,7 @@ import { advanceLocallyAcknowledgedAccessManifestHeadsAtomically, } from "../../
8
7
  import { documentContainerProjectionTables } from "../../data/sqlite/schema.js";
9
8
  import { getClientSQLitePersistenceRuntime } from "../../data/sqlite/sqlitePersistenceRuntime.js";
10
9
  import { createExecSql, ensureSqlTables, runSerializedSqlMutation, } from "../../data/sqlite/sqlSchema.js";
10
+ import { getScopedPeerSeed } from "../../data/sync/crdtPeerSeed.js";
11
11
  import { persistDocumentState } from "../documents/persistence.js";
12
12
  import { ORGANIZATION_PROFILE_DOCUMENT_KIND } from "../organizations/organizationProfile.js";
13
13
  import { ORGANIZATION_METADATA_CONTAINER_NAME, ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME, ROSTER_PROFILE_DOCUMENT_KIND, } from "../organizations/rosterProfileContainer.js";
@@ -1 +1 @@
1
- {"version":3,"file":"persistRegistrationBootstrap.js","sourceRoot":"","sources":["persistRegistrationBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAE5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAEL,+BAA+B,GAChC,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAEL,mCAAmC,GACpC,MAAM,uEAAuE,CAAC;AAC/E,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EACL,uDAAuD,GAExD,MAAM,iEAAiE,CAAC;AAEzE,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAC7E,OAAO,EAAE,iCAAiC,EAAE,MAAM,4CAA4C,CAAC;AAC/F,OAAO,EACL,aAAa,EAGb,eAAe,EACf,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EACL,oCAAoC,EACpC,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,qCAAqC,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b,KAAK,EACL,KAAK,CAAC,6BAA6B,EACnC,oCAAoC,CACrC,CAAC;YACF,MAAM,+BAA+B,CACnC,aAAa,EACb,KAAK,EACL,KAAK,CAAC,2BAA2B,EACjC,kCAAkC,CACnC,CAAC;YACF,MAAM,gCAAgC,CAAC,aAAa,EAAE,KAAK,CAAC,CAAC;YAC7D,mEAAmE;YACnE,sDAAsD;YACtD,MAAM,mCAAmC,CACvC,aAAa,EACb,KAAK,CAAC,sBAAsB,CAC7B,CAAC;QACJ,CAAC,EACD,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,uBAAuB,IAAI,KAAK,CAAC,uBAAuB,EAAE,CACxE,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,MAAyB,EACzB,KAAiC;IAEjC,MAAM,uCAAuC,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import {\n createDocument,\n encodeVersionVector,\n importUpdates,\n} from \"@tearleads/loro\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { getScopedPeerSeed } from \"../../data/crdtPeerSeed\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport {\n type ContainerMetadataRecord,\n sqlContainerContentsPersistence,\n} from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport {\n type AuthoredDiscoveryHead,\n primeAuthoredDocumentDiscoveryHeads,\n} from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport {\n DOCUMENTS_APP_KIND,\n sqlDocumentsPersistence,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport {\n advanceLocallyAcknowledgedAccessManifestHeadsAtomically,\n type LocallyAcknowledgedAccessManifestHead,\n} from \"../../data/persistence/locallyAcknowledgedCheckpointPersistence\";\nimport type { DocumentRecord } from \"../../data/sqlite/documentPersistence\";\nimport { documentContainerProjectionTables } from \"../../data/sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { persistDocumentState } from \"../documents/persistence\";\nimport { ORGANIZATION_PROFILE_DOCUMENT_KIND } from \"../organizations/organizationProfile\";\nimport {\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"../organizations/rosterProfileContainer\";\nimport { enqueueInitialContainerMetadataUpdate } from \"./registrationBootstrapPendingUpdates\";\nimport { persistRegistrationPrincipalPolicies } from \"./registrationPrincipalPolicyPersistence\";\n\ninterface ProvisionedContainerBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n metadataSnapshot: string;\n metadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n systemSlot: ContainerSystemSlot;\n updatedAt: string;\n}\n\ninterface ProvisionedProfileDocumentBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n}\n\nexport interface RegistrationBootstrapInput {\n acknowledgedAccessHeads: readonly LocallyAcknowledgedAccessManifestHead[];\n /** Seeded documents' acknowledged signed heads; see the discovery cache. */\n authoredDiscoveryHeads: readonly AuthoredDiscoveryHead[];\n /** Checked inside the mutation queue claim; false skips every write. */\n canStartDurableMutation?: (() => boolean) | undefined;\n /**\n * @internal Test-only synchronization seam. Invoked synchronously,\n * immediately before this persist joins the serialized mutation queue —\n * no interleaving can separate the two. Lets identity-race tests\n * deterministically place an identity replacement inside the queue-wait\n * window instead of sleeping.\n */\n onPersistQueued?: (() => void) | undefined;\n containerId: string;\n initialAdminGroupPolicy: PrincipalPolicyBundleResponse;\n initialMemberGroupPolicy: PrincipalPolicyBundleResponse;\n initialOrganizationPolicy: PrincipalPolicyBundleResponse;\n rootMetadataAccessEpoch: number;\n rootMetadataAccessStateHash: string;\n rootContainerServerTimestamp: string;\n rootMetadataDocumentId: string;\n rootMetadataInitialUpdate: Uint8Array;\n rootMetadataInitialUpdateCommitted?: boolean | undefined;\n rootMetadataSnapshot: string;\n rootMetadataState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n rosterProfileContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationMetadataContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n rosterProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n // Additional app-owned system containers provisioned with the organization\n // (e.g. a trash bin). Each carries its own display name and icon (unlike the\n // roster/organization-metadata containers, whose names are fixed), since the\n // caller declares them.\n systemContainers?: Array<\n ProvisionedContainerBootstrapInput & {\n icon: string | null;\n name: string;\n }\n >;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n organizationId: string;\n userId: string;\n}\nasync function persistProvisionedContainerBootstrap(\n execSql: ExecSql,\n input: {\n container: ProvisionedContainerBootstrapInput;\n icon: string | null;\n name: string;\n organizationId: string;\n parentId: string | null;\n },\n): Promise<void> {\n const { container } = input;\n const metadataState = container.metadataState;\n const record: ContainerMetadataRecord = {\n accessEpoch: container.accessEpoch,\n accessStateHash: container.accessStateHash,\n documentId: container.metadataDocumentId,\n id: container.containerId,\n lastCommitLsn: null,\n metadataUpdates: container.metadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: metadataState.contentKeyBundle ?? null,\n documentKekTargets: metadataState.documentKekTargets ?? null,\n documentManifestBundle: metadataState.documentManifestBundle ?? null,\n };\n await sqlContainerContentsPersistence.saveContainer(\n execSql,\n {\n id: container.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: input.parentId,\n metadataDocumentId: container.metadataDocumentId,\n systemSlot: container.systemSlot,\n name: input.name,\n icon: input.icon,\n },\n record,\n {\n localUpdatedAt: container.updatedAt,\n serverTimestamps: {\n createdAt: container.createdAt,\n updatedAt: container.updatedAt,\n },\n },\n );\n}\n\nasync function persistRootContainerBootstrap(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n const rootRecord: ContainerMetadataRecord = {\n accessEpoch: input.rootMetadataAccessEpoch,\n accessStateHash: input.rootMetadataAccessStateHash,\n documentId: input.rootMetadataDocumentId,\n id: input.containerId,\n lastCommitLsn: null,\n metadataUpdates: input.rootMetadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: input.rootMetadataState.contentKeyBundle ?? null,\n documentKekTargets: input.rootMetadataState.documentKekTargets ?? null,\n documentManifestBundle:\n input.rootMetadataState.documentManifestBundle ?? null,\n };\n await sqlContainerContentsPersistence.saveContainer(\n execSql,\n {\n id: input.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: null,\n metadataDocumentId: input.rootMetadataDocumentId,\n name: \"/\",\n icon: null,\n },\n rootRecord,\n {\n localUpdatedAt: input.rootContainerServerTimestamp,\n serverTimestamps: {\n createdAt: input.rootContainerServerTimestamp,\n updatedAt: input.rootContainerServerTimestamp,\n },\n },\n );\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n input.containerId,\n input.rootMetadataInitialUpdate,\n input.rootMetadataInitialUpdateCommitted,\n );\n}\n\n// Persist reserved profile containers using their fixed topology: roster profiles\n// inherit the personal root; shared organization metadata has an independent root.\nasync function persistNamedChildContainerBootstrap(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n container: RegistrationBootstrapInput[\"rosterProfileContainer\"],\n name: string,\n): Promise<void> {\n if (!container) {\n return;\n }\n\n await persistProvisionedContainerBootstrap(execSql, {\n container,\n icon: null,\n name,\n organizationId: input.organizationId,\n parentId:\n container === input.organizationMetadataContainer\n ? null\n : input.containerId,\n });\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n container.containerId,\n container.metadataInitialUpdate,\n container.metadataInitialUpdateCommitted,\n );\n}\n\nasync function persistSystemContainersBootstrap(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n const systemContainers = input.systemContainers;\n if (!systemContainers) {\n return;\n }\n\n for (const systemContainer of systemContainers) {\n await persistProvisionedContainerBootstrap(execSql, {\n container: systemContainer,\n icon: systemContainer.icon,\n name: systemContainer.name,\n organizationId: input.organizationId,\n parentId: input.containerId,\n });\n // Provisioned system-container metadata is already committed remotely in\n // the organization transaction. Persist the initialized snapshot locally,\n // but do not queue a duplicate write with a second update id.\n }\n}\n\n// The ONE persist shape for the provisioned profile documents (organization\n// profile and roster profile): the input carries exactly the bootstrap\n// fields, so only the document kind and the host's projectors join it.\nasync function persistProfileDocumentBootstrap(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n profileDocument: ProvisionedProfileDocumentBootstrapInput | undefined,\n documentKind: string,\n): Promise<void> {\n if (!profileDocument) {\n return;\n }\n\n await persistInitialDocumentBootstrap(execSql, {\n ...profileDocument,\n documentKind,\n documentProjectors: input.documentProjectors,\n });\n}\n\nexport async function persistInitialDocumentBootstrap(\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentKind: string;\n documentProjectors: DocumentProjectorRegistryInput | undefined;\n documentState: Pick<\n DocumentRecord,\n \"contentKeyBundle\" | \"documentKekTargets\" | \"documentManifestBundle\"\n >;\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n },\n): Promise<void> {\n const doc = await createDocument(await getScopedPeerSeed(DOCUMENTS_APP_KIND));\n importUpdates(doc, [input.initialUpdate]);\n const pendingUpdate = input.initialUpdateCommitted\n ? undefined\n : (createPendingUpdateFields(input.initialUpdate) ?? undefined);\n\n await persistDocumentState({\n currentDoc: doc,\n currentRecord: null,\n documentProjectors: input.documentProjectors ?? [],\n execSql,\n localId: input.localId,\n patch: {\n accessEpoch: input.accessEpoch,\n accessStateHash: input.accessStateHash,\n containerId: input.containerId,\n contentKeyBundle: input.documentState.contentKeyBundle ?? null,\n documentId: input.documentId,\n // Successful provisioning makes this device's user the founding admin.\n // Stores can open before discovery returns the same access level.\n effectiveAccessLevel: \"admin\",\n documentKekTargets: input.documentState.documentKekTargets ?? null,\n documentKind: input.documentKind,\n documentManifestBundle:\n input.documentState.documentManifestBundle ?? null,\n // The create-only persistence primitive stores this frontier and the\n // full-history checkpoint in one transaction.\n snapshotEndVersion: encodeVersionVector(doc),\n },\n pendingUpdate,\n persistence: sqlDocumentsPersistence,\n });\n}\n\n/**\n * Persists the local root-container bootstrap created during successful\n * registration so container contents can initialize from SQLite on first\n * login — atomically: every write lands inside ONE transaction whose last\n * act re-checks identity currency, so an identity replaced anywhere between\n * the queue claim and the commit rolls the entire bootstrap back instead of\n * leaving a partial one. Resolves false when either currency check rejected\n * the write, so callers do not report a bootstrap that was never persisted.\n */\nexport async function persistRegistrationBootstrapFromExecSql(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<boolean> {\n input.onPersistQueued?.();\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n // In-mutex currency check, adjacent to the serialized-mutation claim\n // (see persistDocumentState): the identity can be replaced while this\n // persist waits for the queue, and its bootstrap must not be written\n // through a client the replacement closed or renewed.\n if (input.canStartDurableMutation && !input.canStartDurableMutation()) {\n return false;\n }\n // Idempotent DDL stays outside the atomic boundary.\n await sqlContainerContentsPersistence.ensureSchema(lockedExecSql);\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n await ensureSqlTables(lockedExecSql, documentContainerProjectionTables);\n // Pre-commit currency guard: the write sequence awaits real work, so\n // the identity can be replaced mid-sequence. The guard runs\n // synchronously with the COMMIT dispatch, so a refusal rolls the whole\n // write set back and a pass cannot go stale before the commit is sent —\n // the partial-persist window a single entry check leaves open.\n const { committed } = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async () => {\n await advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n execSql: lockedExecSql,\n heads: input.acknowledgedAccessHeads,\n });\n await persistRegistrationPrincipalPolicies({\n adminGroup: input.initialAdminGroupPolicy,\n execSql: lockedExecSql,\n memberGroup: input.initialMemberGroupPolicy,\n organization: input.initialOrganizationPolicy,\n });\n await persistRootContainerBootstrap(lockedExecSql, input);\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n input,\n input.rosterProfileContainer,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n input,\n input.rosterProfileDocument,\n ROSTER_PROFILE_DOCUMENT_KIND,\n );\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n input,\n input.organizationMetadataContainer,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n input,\n input.organizationProfileDocument,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n );\n await persistSystemContainersBootstrap(lockedExecSql, input);\n // After the checkpoints above: discovery reuses a cached head only\n // while its access-manifest checkpoint still matches.\n await primeAuthoredDocumentDiscoveryHeads(\n lockedExecSql,\n input.authoredDiscoveryHeads,\n );\n },\n () => !input.canStartDurableMutation || input.canStartDurableMutation(),\n );\n return committed;\n });\n}\n\nexport async function persistRegistrationBootstrap(\n client: ExecSqlClientLike,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n await persistRegistrationBootstrapFromExecSql(createExecSql(client), input);\n}\n"]}
1
+ {"version":3,"file":"persistRegistrationBootstrap.js","sourceRoot":"","sources":["persistRegistrationBootstrap.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,MAAM,iBAAiB,CAAC;AAIzB,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAC9E,OAAO,EAEL,+BAA+B,GAChC,MAAM,wEAAwE,CAAC;AAChF,OAAO,EAEL,mCAAmC,GACpC,MAAM,uEAAuE,CAAC;AAC/E,OAAO,EACL,kBAAkB,EAClB,uBAAuB,GACxB,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EACL,uDAAuD,GAExD,MAAM,iEAAiE,CAAC;AAEzE,OAAO,EAAE,iCAAiC,EAAE,MAAM,0BAA0B,CAAC;AAC7E,OAAO,EAAE,iCAAiC,EAAE,MAAM,4CAA4C,CAAC;AAC/F,OAAO,EACL,aAAa,EAGb,eAAe,EACf,wBAAwB,GACzB,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,0BAA0B,CAAC;AAChE,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EACL,oCAAoC,EACpC,0CAA0C,EAC1C,4BAA4B,GAC7B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,qCAAqC,EAAE,MAAM,uCAAuC,CAAC;AAC9F,OAAO,EAAE,oCAAoC,EAAE,MAAM,0CAA0C,CAAC;AAiFhG,KAAK,UAAU,oCAAoC,CACjD,OAAgB,EAChB,KAMC;IAED,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC;IAC5B,MAAM,aAAa,GAAG,SAAS,CAAC,aAAa,CAAC;IAC9C,MAAM,MAAM,GAA4B;QACtC,WAAW,EAAE,SAAS,CAAC,WAAW;QAClC,eAAe,EA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C;QACJ,CAAC,EACD,GAAG,EAAE,CAAC,CAAC,KAAK,CAAC,uBAAuB,IAAI,KAAK,CAAC,uBAAuB,EAAE,CACxE,CAAC;QACF,OAAO,SAAS,CAAC;IACnB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,4BAA4B,CAChD,MAAyB,EACzB,KAAiC;IAEjC,MAAM,uCAAuC,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,KAAK,CAAC,CAAC;AAC9E,CAAC","sourcesContent":["import {\n createDocument,\n encodeVersionVector,\n importUpdates,\n} from \"@tearleads/loro\";\nimport type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport type { DocumentProjectorRegistryInput } from \"../../data/documents/documentKinds\";\nimport { createPendingUpdateFields } from \"../../data/documents/documentSync\";\nimport {\n type ContainerMetadataRecord,\n sqlContainerContentsPersistence,\n} from \"../../data/persistence/container-contents/containerContentsPersistence\";\nimport {\n type AuthoredDiscoveryHead,\n primeAuthoredDocumentDiscoveryHeads,\n} from \"../../data/persistence/documents/documentDiscoveryEvidencePersistence\";\nimport {\n DOCUMENTS_APP_KIND,\n sqlDocumentsPersistence,\n} from \"../../data/persistence/documents/documentsPersistence\";\nimport {\n advanceLocallyAcknowledgedAccessManifestHeadsAtomically,\n type LocallyAcknowledgedAccessManifestHead,\n} from \"../../data/persistence/locallyAcknowledgedCheckpointPersistence\";\nimport type { DocumentRecord } from \"../../data/sqlite/documentPersistence\";\nimport { documentContainerProjectionTables } from \"../../data/sqlite/schema\";\nimport { getClientSQLitePersistenceRuntime } from \"../../data/sqlite/sqlitePersistenceRuntime\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n ensureSqlTables,\n runSerializedSqlMutation,\n} from \"../../data/sqlite/sqlSchema\";\nimport { getScopedPeerSeed } from \"../../data/sync/crdtPeerSeed\";\nimport { persistDocumentState } from \"../documents/persistence\";\nimport { ORGANIZATION_PROFILE_DOCUMENT_KIND } from \"../organizations/organizationProfile\";\nimport {\n ORGANIZATION_METADATA_CONTAINER_NAME,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n ROSTER_PROFILE_DOCUMENT_KIND,\n} from \"../organizations/rosterProfileContainer\";\nimport { enqueueInitialContainerMetadataUpdate } from \"./registrationBootstrapPendingUpdates\";\nimport { persistRegistrationPrincipalPolicies } from \"./registrationPrincipalPolicyPersistence\";\n\ninterface ProvisionedContainerBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n metadataSnapshot: string;\n metadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n systemSlot: ContainerSystemSlot;\n updatedAt: string;\n}\n\ninterface ProvisionedProfileDocumentBootstrapInput {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n}\n\nexport interface RegistrationBootstrapInput {\n acknowledgedAccessHeads: readonly LocallyAcknowledgedAccessManifestHead[];\n /** Seeded documents' acknowledged signed heads; see the discovery cache. */\n authoredDiscoveryHeads: readonly AuthoredDiscoveryHead[];\n /** Checked inside the mutation queue claim; false skips every write. */\n canStartDurableMutation?: (() => boolean) | undefined;\n /**\n * @internal Test-only synchronization seam. Invoked synchronously,\n * immediately before this persist joins the serialized mutation queue —\n * no interleaving can separate the two. Lets identity-race tests\n * deterministically place an identity replacement inside the queue-wait\n * window instead of sleeping.\n */\n onPersistQueued?: (() => void) | undefined;\n containerId: string;\n initialAdminGroupPolicy: PrincipalPolicyBundleResponse;\n initialMemberGroupPolicy: PrincipalPolicyBundleResponse;\n initialOrganizationPolicy: PrincipalPolicyBundleResponse;\n rootMetadataAccessEpoch: number;\n rootMetadataAccessStateHash: string;\n rootContainerServerTimestamp: string;\n rootMetadataDocumentId: string;\n rootMetadataInitialUpdate: Uint8Array;\n rootMetadataInitialUpdateCommitted?: boolean | undefined;\n rootMetadataSnapshot: string;\n rootMetadataState: ProvisionedContainerBootstrapInput[\"metadataState\"];\n rosterProfileContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationMetadataContainer?: ProvisionedContainerBootstrapInput & {\n metadataInitialUpdate: Uint8Array;\n metadataInitialUpdateCommitted?: boolean | undefined;\n };\n organizationProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n rosterProfileDocument?: ProvisionedProfileDocumentBootstrapInput;\n // Additional app-owned system containers provisioned with the organization\n // (e.g. a trash bin). Each carries its own display name and icon (unlike the\n // roster/organization-metadata containers, whose names are fixed), since the\n // caller declares them.\n systemContainers?: Array<\n ProvisionedContainerBootstrapInput & {\n icon: string | null;\n name: string;\n }\n >;\n documentProjectors?: DocumentProjectorRegistryInput | undefined;\n organizationId: string;\n userId: string;\n}\nasync function persistProvisionedContainerBootstrap(\n execSql: ExecSql,\n input: {\n container: ProvisionedContainerBootstrapInput;\n icon: string | null;\n name: string;\n organizationId: string;\n parentId: string | null;\n },\n): Promise<void> {\n const { container } = input;\n const metadataState = container.metadataState;\n const record: ContainerMetadataRecord = {\n accessEpoch: container.accessEpoch,\n accessStateHash: container.accessStateHash,\n documentId: container.metadataDocumentId,\n id: container.containerId,\n lastCommitLsn: null,\n metadataUpdates: container.metadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: metadataState.contentKeyBundle ?? null,\n documentKekTargets: metadataState.documentKekTargets ?? null,\n documentManifestBundle: metadataState.documentManifestBundle ?? null,\n };\n await sqlContainerContentsPersistence.saveContainer(\n execSql,\n {\n id: container.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: input.parentId,\n metadataDocumentId: container.metadataDocumentId,\n systemSlot: container.systemSlot,\n name: input.name,\n icon: input.icon,\n },\n record,\n {\n localUpdatedAt: container.updatedAt,\n serverTimestamps: {\n createdAt: container.createdAt,\n updatedAt: container.updatedAt,\n },\n },\n );\n}\n\nasync function persistRootContainerBootstrap(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n const rootRecord: ContainerMetadataRecord = {\n accessEpoch: input.rootMetadataAccessEpoch,\n accessStateHash: input.rootMetadataAccessStateHash,\n documentId: input.rootMetadataDocumentId,\n id: input.containerId,\n lastCommitLsn: null,\n metadataUpdates: input.rootMetadataSnapshot,\n snapshotEndVersion: \"\",\n contentKeyBundle: input.rootMetadataState.contentKeyBundle ?? null,\n documentKekTargets: input.rootMetadataState.documentKekTargets ?? null,\n documentManifestBundle:\n input.rootMetadataState.documentManifestBundle ?? null,\n };\n await sqlContainerContentsPersistence.saveContainer(\n execSql,\n {\n id: input.containerId,\n effectiveAccessLevel: \"admin\",\n organizationId: input.organizationId,\n parentId: null,\n metadataDocumentId: input.rootMetadataDocumentId,\n name: \"/\",\n icon: null,\n },\n rootRecord,\n {\n localUpdatedAt: input.rootContainerServerTimestamp,\n serverTimestamps: {\n createdAt: input.rootContainerServerTimestamp,\n updatedAt: input.rootContainerServerTimestamp,\n },\n },\n );\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n input.containerId,\n input.rootMetadataInitialUpdate,\n input.rootMetadataInitialUpdateCommitted,\n );\n}\n\n// Persist reserved profile containers using their fixed topology: roster profiles\n// inherit the personal root; shared organization metadata has an independent root.\nasync function persistNamedChildContainerBootstrap(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n container: RegistrationBootstrapInput[\"rosterProfileContainer\"],\n name: string,\n): Promise<void> {\n if (!container) {\n return;\n }\n\n await persistProvisionedContainerBootstrap(execSql, {\n container,\n icon: null,\n name,\n organizationId: input.organizationId,\n parentId:\n container === input.organizationMetadataContainer\n ? null\n : input.containerId,\n });\n await enqueueInitialContainerMetadataUpdate(\n execSql,\n container.containerId,\n container.metadataInitialUpdate,\n container.metadataInitialUpdateCommitted,\n );\n}\n\nasync function persistSystemContainersBootstrap(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n const systemContainers = input.systemContainers;\n if (!systemContainers) {\n return;\n }\n\n for (const systemContainer of systemContainers) {\n await persistProvisionedContainerBootstrap(execSql, {\n container: systemContainer,\n icon: systemContainer.icon,\n name: systemContainer.name,\n organizationId: input.organizationId,\n parentId: input.containerId,\n });\n // Provisioned system-container metadata is already committed remotely in\n // the organization transaction. Persist the initialized snapshot locally,\n // but do not queue a duplicate write with a second update id.\n }\n}\n\n// The ONE persist shape for the provisioned profile documents (organization\n// profile and roster profile): the input carries exactly the bootstrap\n// fields, so only the document kind and the host's projectors join it.\nasync function persistProfileDocumentBootstrap(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n profileDocument: ProvisionedProfileDocumentBootstrapInput | undefined,\n documentKind: string,\n): Promise<void> {\n if (!profileDocument) {\n return;\n }\n\n await persistInitialDocumentBootstrap(execSql, {\n ...profileDocument,\n documentKind,\n documentProjectors: input.documentProjectors,\n });\n}\n\nexport async function persistInitialDocumentBootstrap(\n execSql: ExecSql,\n input: {\n accessEpoch: number;\n accessStateHash: string;\n containerId: string;\n documentId: string;\n documentKind: string;\n documentProjectors: DocumentProjectorRegistryInput | undefined;\n documentState: Pick<\n DocumentRecord,\n \"contentKeyBundle\" | \"documentKekTargets\" | \"documentManifestBundle\"\n >;\n initialUpdate: Uint8Array;\n initialUpdateCommitted: boolean;\n localId: string;\n },\n): Promise<void> {\n const doc = await createDocument(await getScopedPeerSeed(DOCUMENTS_APP_KIND));\n importUpdates(doc, [input.initialUpdate]);\n const pendingUpdate = input.initialUpdateCommitted\n ? undefined\n : (createPendingUpdateFields(input.initialUpdate) ?? undefined);\n\n await persistDocumentState({\n currentDoc: doc,\n currentRecord: null,\n documentProjectors: input.documentProjectors ?? [],\n execSql,\n localId: input.localId,\n patch: {\n accessEpoch: input.accessEpoch,\n accessStateHash: input.accessStateHash,\n containerId: input.containerId,\n contentKeyBundle: input.documentState.contentKeyBundle ?? null,\n documentId: input.documentId,\n // Successful provisioning makes this device's user the founding admin.\n // Stores can open before discovery returns the same access level.\n effectiveAccessLevel: \"admin\",\n documentKekTargets: input.documentState.documentKekTargets ?? null,\n documentKind: input.documentKind,\n documentManifestBundle:\n input.documentState.documentManifestBundle ?? null,\n // The create-only persistence primitive stores this frontier and the\n // full-history checkpoint in one transaction.\n snapshotEndVersion: encodeVersionVector(doc),\n },\n pendingUpdate,\n persistence: sqlDocumentsPersistence,\n });\n}\n\n/**\n * Persists the local root-container bootstrap created during successful\n * registration so container contents can initialize from SQLite on first\n * login — atomically: every write lands inside ONE transaction whose last\n * act re-checks identity currency, so an identity replaced anywhere between\n * the queue claim and the commit rolls the entire bootstrap back instead of\n * leaving a partial one. Resolves false when either currency check rejected\n * the write, so callers do not report a bootstrap that was never persisted.\n */\nexport async function persistRegistrationBootstrapFromExecSql(\n execSql: ExecSql,\n input: RegistrationBootstrapInput,\n): Promise<boolean> {\n input.onPersistQueued?.();\n return runSerializedSqlMutation(execSql, async (lockedExecSql) => {\n // In-mutex currency check, adjacent to the serialized-mutation claim\n // (see persistDocumentState): the identity can be replaced while this\n // persist waits for the queue, and its bootstrap must not be written\n // through a client the replacement closed or renewed.\n if (input.canStartDurableMutation && !input.canStartDurableMutation()) {\n return false;\n }\n // Idempotent DDL stays outside the atomic boundary.\n await sqlContainerContentsPersistence.ensureSchema(lockedExecSql);\n await sqlDocumentsPersistence.ensureSchema(lockedExecSql);\n await ensureSqlTables(lockedExecSql, documentContainerProjectionTables);\n // Pre-commit currency guard: the write sequence awaits real work, so\n // the identity can be replaced mid-sequence. The guard runs\n // synchronously with the COMMIT dispatch, so a refusal rolls the whole\n // write set back and a pass cannot go stale before the commit is sent —\n // the partial-persist window a single entry check leaves open.\n const { committed } = await getClientSQLitePersistenceRuntime(\n lockedExecSql,\n ).guardedTransaction(\n async () => {\n await advanceLocallyAcknowledgedAccessManifestHeadsAtomically({\n execSql: lockedExecSql,\n heads: input.acknowledgedAccessHeads,\n });\n await persistRegistrationPrincipalPolicies({\n adminGroup: input.initialAdminGroupPolicy,\n execSql: lockedExecSql,\n memberGroup: input.initialMemberGroupPolicy,\n organization: input.initialOrganizationPolicy,\n });\n await persistRootContainerBootstrap(lockedExecSql, input);\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n input,\n input.rosterProfileContainer,\n ORGANIZATION_ROSTER_PROFILE_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n input,\n input.rosterProfileDocument,\n ROSTER_PROFILE_DOCUMENT_KIND,\n );\n await persistNamedChildContainerBootstrap(\n lockedExecSql,\n input,\n input.organizationMetadataContainer,\n ORGANIZATION_METADATA_CONTAINER_NAME,\n );\n await persistProfileDocumentBootstrap(\n lockedExecSql,\n input,\n input.organizationProfileDocument,\n ORGANIZATION_PROFILE_DOCUMENT_KIND,\n );\n await persistSystemContainersBootstrap(lockedExecSql, input);\n // After the checkpoints above: discovery reuses a cached head only\n // while its access-manifest checkpoint still matches.\n await primeAuthoredDocumentDiscoveryHeads(\n lockedExecSql,\n input.authoredDiscoveryHeads,\n );\n },\n () => !input.canStartDurableMutation || input.canStartDurableMutation(),\n );\n return committed;\n });\n}\n\nexport async function persistRegistrationBootstrap(\n client: ExecSqlClientLike,\n input: RegistrationBootstrapInput,\n): Promise<void> {\n await persistRegistrationBootstrapFromExecSql(createExecSql(client), input);\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import type { EncapsulationKeyPair, SigningKeyPair } from "../internal/crypto/index.js";
2
- import type { BlobStore } from "../data/blobContracts.js";
2
+ import type { BlobStore } from "../data/blobs/blobContracts.js";
3
3
  import type { DocumentProjectorRegistry } from "../data/documents/documentKinds.js";
4
- import type { DomainScope } from "../data/domainScope.js";
5
- import type { SecurityIncidentReporter } from "../data/securityIncidents.js";
4
+ import type { DomainScope } from "../data/shared/domainScope.js";
5
+ import type { SecurityIncidentReporter } from "../data/shared/securityIncidents.js";
6
6
  import type { ExecSql } from "../data/sqlite/sqlSchema.js";
7
7
  export type WorkflowRuntimeDatabaseStatus = "idle" | "ready" | "error" | "terminated";
8
8
  export interface WorkflowRuntimeAuthInput {