@tearleads/client-sdk 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (354) hide show
  1. package/client/Tearleads.d.ts +2 -0
  2. package/client/Tearleads.js +1 -0
  3. package/client/Tearleads.js.map +1 -1
  4. package/client/containerContents.js +2 -1
  5. package/client/containerContents.js.map +1 -1
  6. package/client/index.d.ts +1 -1
  7. package/client/index.js.map +1 -1
  8. package/client/organizations/index.d.ts +4 -42
  9. package/client/organizations/index.js +13 -0
  10. package/client/organizations/index.js.map +1 -1
  11. package/client/organizations/organizationGroupNameHydration.js +8 -1
  12. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  13. package/client/organizations/organizationsTypes.d.ts +47 -0
  14. package/client/organizations/organizationsTypes.js +2 -0
  15. package/client/organizations/organizationsTypes.js.map +1 -0
  16. package/client/organizations/principalMutationRecovery.d.ts +16 -0
  17. package/client/organizations/principalMutationRecovery.js +23 -0
  18. package/client/organizations/principalMutationRecovery.js.map +1 -0
  19. package/client/organizations/principalMutationScope.js +7 -2
  20. package/client/organizations/principalMutationScope.js.map +1 -1
  21. package/client/principalMutationApi.d.ts +24 -0
  22. package/client/principalMutationApi.js +108 -0
  23. package/client/principalMutationApi.js.map +1 -0
  24. package/client/principalMutationDeadline.js +23 -0
  25. package/client/principalMutationDeadline.js.map +1 -0
  26. package/client/workflowRuntime.d.ts +3 -1
  27. package/client/workflowRuntime.js +44 -5
  28. package/client/workflowRuntime.js.map +1 -1
  29. package/data/documents/blob/shared/types.d.ts +4 -0
  30. package/data/documents/blob/shared/types.js.map +1 -1
  31. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js +2 -0
  32. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
  33. package/data/keyingProjectionVerification/checkpointContext.d.ts +2 -1
  34. package/data/keyingProjectionVerification/checkpointContext.js +22 -0
  35. package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
  36. package/data/keyingProjectionVerification/containerDestinationVerification.js +11 -1
  37. package/data/keyingProjectionVerification/containerDestinationVerification.js.map +1 -1
  38. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  39. package/data/keyingProjectionVerification/containerPathVerification.js.map +1 -1
  40. package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +3 -2
  41. package/data/keyingProjectionVerification/containerProjectionVerification.js +10 -11
  42. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
  43. package/data/keyingProjectionVerification/documentManifestPolicies.js.map +1 -1
  44. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  45. package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +2 -3
  46. package/data/keyingProjectionVerification/documentProjectionVerification.js +4 -0
  47. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
  48. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js +14 -12
  49. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js.map +1 -1
  50. package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
  51. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js +33 -6
  52. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
  53. package/data/keyingProjectionVerification/projectionLifetimes.js +13 -0
  54. package/data/keyingProjectionVerification/projectionLifetimes.js.map +1 -0
  55. package/data/keyingProjectionVerification/projectionPolicyEvidence.js +19 -66
  56. package/data/keyingProjectionVerification/projectionPolicyEvidence.js.map +1 -1
  57. package/data/keyingProjectionVerification/types.d.ts +13 -2
  58. package/data/keyingProjectionVerification/types.js +15 -0
  59. package/data/keyingProjectionVerification/types.js.map +1 -1
  60. package/data/persistence/keyingCheckpointAdvancePersistence.js +4 -1
  61. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +1 -1
  62. package/data/persistence/organizationFounderPersistence.js +2 -2
  63. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  64. package/data/persistence/principalAuthorizationCheckpoints.js +29 -0
  65. package/data/persistence/principalAuthorizationCheckpoints.js.map +1 -0
  66. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +27 -0
  67. package/data/persistence/principalCurrentAcknowledgementPersistence.js +109 -0
  68. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -0
  69. package/data/persistence/principalGrantRetirementPersistence.d.ts +3 -3
  70. package/data/persistence/principalGrantRetirementPersistence.js +4 -1
  71. package/data/persistence/principalGrantRetirementPersistence.js.map +1 -1
  72. package/data/persistence/principalHistoryEvidencePersistence.d.ts +30 -0
  73. package/data/persistence/principalHistoryPrefixPersistence.d.ts +24 -0
  74. package/data/persistence/principalHistoryPrefixPersistence.js +6 -2
  75. package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -1
  76. package/data/persistence/principalHistoryStagePersistence.d.ts +21 -0
  77. package/data/persistence/principalKeyEnvelopeCandidates.js +12 -1
  78. package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -1
  79. package/data/persistence/principalMutationJournalPersistence.d.ts +19 -0
  80. package/data/persistence/principalMutationJournalPersistence.js +53 -0
  81. package/data/persistence/principalMutationJournalPersistence.js.map +1 -0
  82. package/data/persistence/verifiedPrincipalPolicyBundle.js +7 -51
  83. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
  84. package/data/persistence/verifiedPrincipalPolicyCurrent.js +56 -0
  85. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -0
  86. package/data/principals/principalHistoryRuntime.js +12 -0
  87. package/data/principals/principalHistoryRuntime.js.map +1 -0
  88. package/data/principals/principalHistoryStageProtection.js +2 -12
  89. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  90. package/data/principals/principalMutationJournal.d.ts +26 -0
  91. package/data/principals/principalMutationJournal.js +90 -0
  92. package/data/principals/principalMutationJournal.js.map +1 -0
  93. package/data/principals/principalMutationJournalRecord.d.ts +8 -0
  94. package/data/principals/principalMutationJournalRecord.js +25 -0
  95. package/data/principals/principalMutationJournalRecord.js.map +1 -0
  96. package/data/principals/principalPolicyEvidence.d.ts +2 -2
  97. package/data/principals/principalPolicyEvidence.js.map +1 -1
  98. package/data/sqlite/principalHistoryEvidenceSchema.d.ts +308 -0
  99. package/data/sqlite/principalHistoryStageSchema.d.ts +119 -0
  100. package/data/sqlite/principalHistoryStageSchema.js +3 -0
  101. package/data/sqlite/principalHistoryStageSchema.js.map +1 -1
  102. package/data/sqlite/principalMutationJournalSchema.d.ts +85 -0
  103. package/data/sqlite/principalMutationJournalSchema.js +13 -0
  104. package/data/sqlite/principalMutationJournalSchema.js.map +1 -0
  105. package/data/sqlite/schema.d.ts +83 -0
  106. package/data/sqlite/schema.js +3 -0
  107. package/data/sqlite/schema.js.map +1 -1
  108. package/index.d.ts +5 -5
  109. package/index.js +2 -2
  110. package/index.js.map +1 -1
  111. package/internal/api-client/ApiCache.d.ts +54 -0
  112. package/internal/api-client/ApiClient.d.ts +255 -309
  113. package/internal/api-client/ApiClient.js +15 -6
  114. package/internal/api-client/ApiClient.js.map +1 -1
  115. package/internal/api-client/index.d.ts +1 -0
  116. package/internal/api-client/index.js.map +1 -1
  117. package/internal/api-client/principalHistoryDeadline.js +20 -0
  118. package/internal/api-client/principalHistoryDeadline.js.map +1 -0
  119. package/internal/api-client/principalHistoryRequest.js +59 -22
  120. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  121. package/internal/api-client/principalHistoryRequestContext.js +18 -5
  122. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  123. package/internal/api-client/principalPolicyRequests.d.ts +799 -0
  124. package/internal/api-client/principalPolicyRequests.js +9 -4
  125. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  126. package/internal/api-client/projectionPolicyHistoryPages.d.ts +9 -0
  127. package/internal/api-client/projectionPolicyHistoryPages.js +88 -0
  128. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -0
  129. package/internal/api-client/writerProjectionRequests.js +26 -0
  130. package/internal/api-client/writerProjectionRequests.js.map +1 -0
  131. package/internal/crypto/index.d.ts +1 -1
  132. package/internal/crypto/index.js +1 -1
  133. package/internal/crypto/index.js.map +1 -1
  134. package/internal/crypto/keying/index.d.ts +2 -0
  135. package/internal/crypto/keying/index.js +2 -0
  136. package/internal/crypto/keying/index.js.map +1 -1
  137. package/internal/crypto/keying/principalPolicyCurrent.d.ts +1 -1
  138. package/internal/crypto/keying/principalPolicyCurrent.js +3 -3
  139. package/internal/crypto/keying/principalPolicyCurrent.js.map +1 -1
  140. package/internal/crypto/keying/principalPolicyCurrentEvidence.js +16 -0
  141. package/internal/crypto/keying/principalPolicyCurrentEvidence.js.map +1 -0
  142. package/internal/crypto/keying/principalPolicyCurrentMutation.d.ts +10 -0
  143. package/internal/crypto/keying/principalPolicyCurrentMutation.js +51 -0
  144. package/internal/crypto/keying/principalPolicyCurrentMutation.js.map +1 -0
  145. package/internal/crypto/keying/principalPolicyCurrentSuccessor.d.ts +10 -0
  146. package/internal/crypto/keying/principalPolicyCurrentSuccessor.js +60 -0
  147. package/internal/crypto/keying/principalPolicyCurrentSuccessor.js.map +1 -0
  148. package/internal/crypto/keying/principalPolicyHistory.js +8 -1
  149. package/internal/crypto/keying/principalPolicyHistory.js.map +1 -1
  150. package/internal/crypto/keying/principalPolicyHistoryReferences.js +1 -1
  151. package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
  152. package/internal/crypto/keying/principalPolicyHistoryTypes.d.ts +7 -2
  153. package/internal/crypto/keying/principalPolicyHistoryTypes.js +6 -3
  154. package/internal/crypto/keying/principalPolicyHistoryTypes.js.map +1 -1
  155. package/internal/crypto/projectionHistorySlots.js +0 -4
  156. package/internal/crypto/projectionHistorySlots.js.map +1 -1
  157. package/internal/validators/operation/index.d.ts +1 -0
  158. package/internal/validators/operation/index.js +1 -0
  159. package/internal/validators/operation/index.js.map +1 -1
  160. package/internal/validators/operation/principals.d.ts +38 -16
  161. package/internal/validators/operation/principals.js +11 -5
  162. package/internal/validators/operation/principals.js.map +1 -1
  163. package/internal/validators/operation/projectionPolicyHistory.d.ts +512 -0
  164. package/internal/validators/operation/projectionPolicyHistory.js +37 -0
  165. package/internal/validators/operation/projectionPolicyHistory.js.map +1 -0
  166. package/internal/validators/operation/registry.d.ts +2 -0
  167. package/internal/validators/operation/registry.js +2 -0
  168. package/internal/validators/operation/registry.js.map +1 -1
  169. package/internal/validators/operation/writerProjections.d.ts +178 -1224
  170. package/internal/validators/operation/writerProjections.js +9 -2
  171. package/internal/validators/operation/writerProjections.js.map +1 -1
  172. package/internal/validators/response/container.d.ts +84 -612
  173. package/internal/validators/response/documentMutation.d.ts +84 -612
  174. package/internal/validators/response/index.d.ts +1 -0
  175. package/internal/validators/response/index.js +1 -0
  176. package/internal/validators/response/index.js.map +1 -1
  177. package/internal/validators/response/organizationBilling.d.ts +1 -0
  178. package/internal/validators/response/organizationBilling.js +1 -1
  179. package/internal/validators/response/organizationBilling.js.map +1 -1
  180. package/internal/validators/response/principalHistoryPreparation.js +28 -1
  181. package/internal/validators/response/principalHistoryPreparation.js.map +1 -1
  182. package/internal/validators/response/principalPolicySnapshotPage.d.ts +388 -0
  183. package/internal/validators/response/principalPolicySnapshotPage.js +24 -0
  184. package/internal/validators/response/principalPolicySnapshotPage.js.map +1 -0
  185. package/internal/validators/response/projectionPolicyEvidence.d.ts +85 -613
  186. package/internal/validators/response/projectionPolicyEvidence.js +10 -5
  187. package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
  188. package/package.json +1 -1
  189. package/stores/documents/documentStore/attachmentHydration.js +3 -0
  190. package/stores/documents/documentStore/attachmentHydration.js.map +1 -1
  191. package/stores/documents/documentStore/syncDetachedAttachments.js +3 -0
  192. package/stores/documents/documentStore/syncDetachedAttachments.js.map +1 -1
  193. package/workflows/blobs/decrypt.d.ts +1 -1
  194. package/workflows/blobs/decrypt.js +3 -1
  195. package/workflows/blobs/decrypt.js.map +1 -1
  196. package/workflows/blobs/detach.js +6 -1
  197. package/workflows/blobs/detach.js.map +1 -1
  198. package/workflows/blobs/hydrate.d.ts +3 -1
  199. package/workflows/blobs/hydrate.js +2 -0
  200. package/workflows/blobs/hydrate.js.map +1 -1
  201. package/workflows/blobs/retainedAttachmentVerification.js +2 -0
  202. package/workflows/blobs/retainedAttachmentVerification.js.map +1 -1
  203. package/workflows/container-contents/container-state/createAdoption.js +2 -0
  204. package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
  205. package/workflows/container-contents/container-state/createWithMetadata.js +7 -39
  206. package/workflows/container-contents/container-state/createWithMetadata.js.map +1 -1
  207. package/workflows/container-contents/container-state/createWithMetadataPlan.js +68 -0
  208. package/workflows/container-contents/container-state/createWithMetadataPlan.js.map +1 -0
  209. package/workflows/container-contents/remoteContainerState.js +3 -1
  210. package/workflows/container-contents/remoteContainerState.js.map +1 -1
  211. package/workflows/container-contents/remoteHydration/verifiedDestination.js +3 -0
  212. package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +1 -1
  213. package/workflows/container-contents/runtime.d.ts +3 -0
  214. package/workflows/container-contents/runtime.js +7 -6
  215. package/workflows/container-contents/runtime.js.map +1 -1
  216. package/workflows/containers/child/share.js +4 -0
  217. package/workflows/containers/child/share.js.map +1 -1
  218. package/workflows/containers/child/sharePrincipalPolicy.d.ts +1 -0
  219. package/workflows/containers/child/sharePrincipalPolicy.js.map +1 -1
  220. package/workflows/documents/create.d.ts +2 -15
  221. package/workflows/documents/create.js +9 -64
  222. package/workflows/documents/create.js.map +1 -1
  223. package/workflows/documents/createProjection.d.ts +14 -0
  224. package/workflows/documents/createProjection.js +26 -0
  225. package/workflows/documents/createProjection.js.map +1 -0
  226. package/workflows/documents/createResponse.js +49 -0
  227. package/workflows/documents/createResponse.js.map +1 -0
  228. package/workflows/documents/linkSetBlobRewraps.js +2 -0
  229. package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
  230. package/workflows/documents/runtime.d.ts +3 -0
  231. package/workflows/documents/runtime.js +3 -2
  232. package/workflows/documents/runtime.js.map +1 -1
  233. package/workflows/documents/syncFailureClassification.js +3 -1
  234. package/workflows/documents/syncFailureClassification.js.map +1 -1
  235. package/workflows/organizations/acknowledgedDirectoryBindings.js +18 -0
  236. package/workflows/organizations/acknowledgedDirectoryBindings.js.map +1 -0
  237. package/workflows/organizations/currentGroupMetadataAuthority.js +32 -0
  238. package/workflows/organizations/currentGroupMetadataAuthority.js.map +1 -0
  239. package/workflows/organizations/currentOrganizationAuthority.js +88 -0
  240. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -0
  241. package/workflows/organizations/currentOrganizationGroupNames.js +68 -0
  242. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -0
  243. package/workflows/organizations/currentPolicyMutationAcknowledgement.js +65 -0
  244. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -0
  245. package/workflows/organizations/deleteOrganizationGroup.js +1 -0
  246. package/workflows/organizations/deleteOrganizationGroup.js.map +1 -1
  247. package/workflows/organizations/groupCreation.js +1 -0
  248. package/workflows/organizations/groupCreation.js.map +1 -1
  249. package/workflows/organizations/groupMetadataAccess.d.ts +2 -2
  250. package/workflows/organizations/groupMetadataAccess.js +1 -1
  251. package/workflows/organizations/groupMetadataAccess.js.map +1 -1
  252. package/workflows/organizations/groupMetadataBinding.js.map +1 -1
  253. package/workflows/organizations/groupMetadataContainerAuthority.js +2 -47
  254. package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
  255. package/workflows/organizations/groupMetadataRootBinding.js +51 -0
  256. package/workflows/organizations/groupMetadataRootBinding.js.map +1 -0
  257. package/workflows/organizations/groupMetadataRuntime.js +20 -9
  258. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  259. package/workflows/organizations/groupMutationAuthorization.js.map +1 -1
  260. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +9 -75
  261. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  262. package/workflows/organizations/groupPolicyMutationContext.d.ts +5 -13
  263. package/workflows/organizations/groupPolicyMutationContext.js +1 -0
  264. package/workflows/organizations/groupPolicyMutationContext.js.map +1 -1
  265. package/workflows/organizations/groupPolicyMutationEvidence.d.ts +26 -0
  266. package/workflows/organizations/groupPolicyMutationEvidence.js +64 -0
  267. package/workflows/organizations/groupPolicyMutationEvidence.js.map +1 -0
  268. package/workflows/organizations/groupPolicyMutationHead.js.map +1 -1
  269. package/workflows/organizations/groupPolicyRequests.js +69 -63
  270. package/workflows/organizations/groupPolicyRequests.js.map +1 -1
  271. package/workflows/organizations/index.d.ts +6 -0
  272. package/workflows/organizations/index.js +5 -0
  273. package/workflows/organizations/index.js.map +1 -1
  274. package/workflows/organizations/organizationGroupNames.js +7 -0
  275. package/workflows/organizations/organizationGroupNames.js.map +1 -1
  276. package/workflows/organizations/principalCurrentPublicationSeal.js +51 -0
  277. package/workflows/organizations/principalCurrentPublicationSeal.js.map +1 -0
  278. package/workflows/organizations/principalMutationJournalLane.js +26 -0
  279. package/workflows/organizations/principalMutationJournalLane.js.map +1 -0
  280. package/workflows/organizations/principalMutationJournalManagement.d.ts +26 -0
  281. package/workflows/organizations/principalMutationJournalManagement.js +104 -0
  282. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -0
  283. package/workflows/organizations/principalMutationJournalSession.d.ts +26 -0
  284. package/workflows/organizations/principalMutationJournalSession.js +85 -0
  285. package/workflows/organizations/principalMutationJournalSession.js.map +1 -0
  286. package/workflows/organizations/principalMutationReceipt.js +21 -0
  287. package/workflows/organizations/principalMutationReceipt.js.map +1 -0
  288. package/workflows/organizations/principalPolicyReceiptArtifacts.js +74 -0
  289. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -0
  290. package/workflows/organizations/principalPolicyRequest.d.ts +5 -4
  291. package/workflows/organizations/principalPolicyRequest.js.map +1 -1
  292. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +21 -0
  293. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +155 -0
  294. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -0
  295. package/workflows/principals/index.d.ts +2 -0
  296. package/workflows/principals/index.js +1 -0
  297. package/workflows/principals/index.js.map +1 -1
  298. package/workflows/principals/policyVerification.js.map +1 -1
  299. package/workflows/principals/principalCurrentRecoveryBatch.js +14 -0
  300. package/workflows/principals/principalCurrentRecoveryBatch.js.map +1 -0
  301. package/workflows/principals/principalHistoryRecoveryAuthority.js +20 -0
  302. package/workflows/principals/principalHistoryRecoveryAuthority.js.map +1 -0
  303. package/workflows/principals/principalHistoryRecoveryStage.js +1 -1
  304. package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
  305. package/workflows/principals/principalHistoryRecoveryTypes.d.ts +3 -3
  306. package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
  307. package/workflows/principals/principalHistoryRecoveryVerification.js +6 -1
  308. package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -1
  309. package/workflows/principals/principalRecoveryDirectory.d.ts +1 -1
  310. package/workflows/principals/principalRecoveryDirectory.js +29 -4
  311. package/workflows/principals/principalRecoveryDirectory.js.map +1 -1
  312. package/workflows/principals/principalRecoveryDiscoveryPage.js +36 -0
  313. package/workflows/principals/principalRecoveryDiscoveryPage.js.map +1 -0
  314. package/workflows/principals/principalRecoveryLocalPreference.js +28 -0
  315. package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -0
  316. package/workflows/principals/principalRecoveryMemo.d.ts +16 -0
  317. package/workflows/principals/principalRecoveryMemo.js +88 -16
  318. package/workflows/principals/principalRecoveryMemo.js.map +1 -1
  319. package/workflows/principals/principalRecoveryOutage.js +1 -1
  320. package/workflows/principals/principalRecoveryOutage.js.map +1 -1
  321. package/workflows/principals/publicPrincipalHistoryAuthority.js +60 -0
  322. package/workflows/principals/publicPrincipalHistoryAuthority.js.map +1 -0
  323. package/workflows/principals/publicPrincipalHistoryPage.js +87 -0
  324. package/workflows/principals/publicPrincipalHistoryPage.js.map +1 -0
  325. package/workflows/principals/publicPrincipalHistoryProgress.js +178 -0
  326. package/workflows/principals/publicPrincipalHistoryProgress.js.map +1 -0
  327. package/workflows/principals/publicPrincipalHistoryTypes.d.ts +39 -0
  328. package/workflows/principals/publicPrincipalHistoryTypes.js +2 -0
  329. package/workflows/principals/publicPrincipalHistoryTypes.js.map +1 -0
  330. package/workflows/principals/publicProjectionDirectory.js +40 -0
  331. package/workflows/principals/publicProjectionDirectory.js.map +1 -0
  332. package/workflows/principals/publicProjectionPrincipal.js +53 -0
  333. package/workflows/principals/publicProjectionPrincipal.js.map +1 -0
  334. package/workflows/principals/recoverCurrentOrganizationPolicy.js +33 -0
  335. package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +1 -0
  336. package/workflows/principals/recoverPrincipalPolicyHistory.js +4 -1
  337. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
  338. package/workflows/principals/recoverProjectionPolicyHistory.d.ts +9 -0
  339. package/workflows/principals/recoverProjectionPolicyHistory.js +98 -0
  340. package/workflows/principals/recoverProjectionPolicyHistory.js.map +1 -0
  341. package/workflows/principals/recoverPublicPrincipalHistory.js +176 -0
  342. package/workflows/principals/recoverPublicPrincipalHistory.js.map +1 -0
  343. package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +2 -1
  344. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +15 -20
  345. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  346. package/workflows/principals/runtimePolicyRecovery.js +16 -9
  347. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  348. package/workflows/principals/runtimePolicyWarmer.js +2 -0
  349. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  350. package/workflows/principals/runtimeProjectionPolicyRecovery.js +56 -0
  351. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -0
  352. package/workflows/principals/selectPublicPrincipalHistory.js +90 -0
  353. package/workflows/principals/selectPublicPrincipalHistory.js.map +1 -0
  354. package/workflows/registration/provisioningBootstrapBuilders.d.ts +21 -153
@@ -0,0 +1,47 @@
1
+ import type { NativeSubscriptionStore } from "../../internal/validators/billing.js";
2
+ import type { addOrganizationGroupUser, cancelStripeSubscription, checkNativePurchaseEligibility, claimNativeOrganizationSubscription, createOrganizationGroup, createStripeCheckout, createStripeCheckoutSession, importOrganizationUser, LocalOrganizationSummary, loadOrganizationBilling, loadOrganizationBillingHistory, loadOrganizationBillingManagementUrl, loadStripeCheckoutOptions, removeOrganizationGroupUser, revokeOrganizationContainerGrant, rotateOrganizationGroupForAccessSetShrink, startOrganizationTrial, updateOrganizationProfile, updateOrganizationRosterEntry } from "../../workflows/organizations/index.js";
3
+ import type { InternalWorkflowRuntimeInput } from "../workflowRuntime.js";
4
+ import type { OrganizationDataUsageCoordinator } from "./organizationDataUsage.js";
5
+ import type { loadOrganizationGroupPresentationDetails } from "./organizationGroupPresentation.js";
6
+ import type { OrganizationReadModelCoordinator } from "./organizationReadModels.js";
7
+ import type { AbandonOrganizationPolicyMutationInput, DiscardUnreadableOrganizationPolicyMutationInput, readPendingOrganizationPolicyMutation } from "./principalMutationRecovery.js";
8
+ import type { AddOrganizationGroupUserInput, deleteGroupForOrganization, OrganizationGrantRef, RemoveOrganizationGroupUserInput } from "./principalMutations.js";
9
+ export interface Organizations {
10
+ discardUnreadablePolicyMutation: (input: DiscardUnreadableOrganizationPolicyMutationInput) => Promise<boolean>;
11
+ readPendingPolicyMutation: (organizationId: string) => ReturnType<typeof readPendingOrganizationPolicyMutation>;
12
+ retryPendingPolicyMutation: (organizationId: string) => Promise<void>;
13
+ abandonPendingPolicyMutation: (input: AbandonOrganizationPolicyMutationInput) => Promise<boolean>;
14
+ addUserToGroup: (input: AddOrganizationGroupUserInput) => ReturnType<typeof addOrganizationGroupUser>;
15
+ createGroup: (name: string) => ReturnType<typeof createOrganizationGroup>;
16
+ deleteGroup: (groupId: string) => ReturnType<typeof deleteGroupForOrganization>;
17
+ importUserById: (userId: string) => ReturnType<typeof importOrganizationUser>;
18
+ loadBilling: () => ReturnType<typeof loadOrganizationBilling>;
19
+ /** Billing for an organization the session is not currently switched to. */
20
+ loadBillingForOrganization: (organizationId: string) => ReturnType<typeof loadOrganizationBilling>;
21
+ loadBillingHistory: () => ReturnType<typeof loadOrganizationBillingHistory>;
22
+ loadBillingManagementUrl: () => ReturnType<typeof loadOrganizationBillingManagementUrl>;
23
+ /** Direct Stripe checkout (issue #1654): options, start, and cancel. */
24
+ loadStripeCheckoutOptions: (organizationId?: string) => ReturnType<typeof loadStripeCheckoutOptions>;
25
+ createStripeCheckout: (organizationId?: string) => ReturnType<typeof createStripeCheckout>;
26
+ createStripeCheckoutSession: (returnUrl: string, organizationId?: string) => ReturnType<typeof createStripeCheckoutSession>;
27
+ cancelStripeSubscription: () => ReturnType<typeof cancelStripeSubscription>;
28
+ claimNativeSubscription: (organizationId: string, store: NativeSubscriptionStore) => ReturnType<typeof claimNativeOrganizationSubscription>;
29
+ checkNativePurchaseEligibility: (organizationId: string, store: NativeSubscriptionStore) => ReturnType<typeof checkNativePurchaseEligibility>;
30
+ loadDataUsage: () => ReturnType<OrganizationDataUsageCoordinator["reconcile"]>;
31
+ loadLocalDataUsage: () => ReturnType<OrganizationDataUsageCoordinator["loadLocal"]>;
32
+ loadDirectoryAndGroups: () => ReturnType<OrganizationReadModelCoordinator["reconcile"]>;
33
+ loadDirectoryAndGroupsAfterMutation: () => ReturnType<OrganizationReadModelCoordinator["reconcileAfterMutation"]>;
34
+ loadLocalDirectoryAndGroups: () => ReturnType<OrganizationReadModelCoordinator["loadLocal"]>;
35
+ loadGroupMembers: (groupId: string) => ReturnType<InternalWorkflowRuntimeInput["apiClient"]["listOrganizationGroupMembers"]>;
36
+ loadGroupPresentationDetails(groupId: string): ReturnType<typeof loadOrganizationGroupPresentationDetails>;
37
+ loadGroupContainers: (groupId: string) => ReturnType<OrganizationReadModelCoordinator["loadLocalGroupContainers"]>;
38
+ loadGrants: () => ReturnType<OrganizationReadModelCoordinator["loadLocalGrants"]>;
39
+ listLocalOrganizations: () => Promise<LocalOrganizationSummary[]>;
40
+ loadPolicyHistory: () => ReturnType<OrganizationReadModelCoordinator["loadOrganizationPolicyHistory"]>;
41
+ loadUserDetail: (userId: string) => ReturnType<OrganizationReadModelCoordinator["loadLocalUserDetail"]>;
42
+ updateRosterEntry: (userId: string, profileDocumentId: string | null) => ReturnType<typeof updateOrganizationRosterEntry>;
43
+ updateProfile: (profileDocumentId: string | null) => ReturnType<typeof updateOrganizationProfile>;
44
+ removeUserFromGroup: (input: RemoveOrganizationGroupUserInput) => ReturnType<typeof removeOrganizationGroupUser>;
45
+ revokeGrant: (grant: OrganizationGrantRef) => Promise<Awaited<ReturnType<typeof revokeOrganizationContainerGrant>> | Awaited<ReturnType<typeof rotateOrganizationGroupForAccessSetShrink>>>;
46
+ startTrial: (organizationId?: string) => ReturnType<typeof startOrganizationTrial>;
47
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=organizationsTypes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"organizationsTypes.js","sourceRoot":"","sources":["organizationsTypes.ts"],"names":[],"mappings":"","sourcesContent":["import type { NativeSubscriptionStore } from \"@tearleads/validators/billing\";\nimport type {\n addOrganizationGroupUser,\n cancelStripeSubscription,\n checkNativePurchaseEligibility,\n claimNativeOrganizationSubscription,\n createOrganizationGroup,\n createStripeCheckout,\n createStripeCheckoutSession,\n importOrganizationUser,\n LocalOrganizationSummary,\n loadOrganizationBilling,\n loadOrganizationBillingHistory,\n loadOrganizationBillingManagementUrl,\n loadStripeCheckoutOptions,\n removeOrganizationGroupUser,\n revokeOrganizationContainerGrant,\n rotateOrganizationGroupForAccessSetShrink,\n startOrganizationTrial,\n updateOrganizationProfile,\n updateOrganizationRosterEntry,\n} from \"../../workflows/organizations\";\nimport type { InternalWorkflowRuntimeInput } from \"../workflowRuntime\";\nimport type { OrganizationDataUsageCoordinator } from \"./organizationDataUsage\";\nimport type { loadOrganizationGroupPresentationDetails } from \"./organizationGroupPresentation\";\nimport type { OrganizationReadModelCoordinator } from \"./organizationReadModels\";\nimport type {\n AbandonOrganizationPolicyMutationInput,\n DiscardUnreadableOrganizationPolicyMutationInput,\n readPendingOrganizationPolicyMutation,\n} from \"./principalMutationRecovery\";\nimport type {\n AddOrganizationGroupUserInput,\n deleteGroupForOrganization,\n OrganizationGrantRef,\n RemoveOrganizationGroupUserInput,\n} from \"./principalMutations\";\n\nexport interface Organizations {\n discardUnreadablePolicyMutation: (\n input: DiscardUnreadableOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n readPendingPolicyMutation: (\n organizationId: string,\n ) => ReturnType<typeof readPendingOrganizationPolicyMutation>;\n retryPendingPolicyMutation: (organizationId: string) => Promise<void>;\n abandonPendingPolicyMutation: (\n input: AbandonOrganizationPolicyMutationInput,\n ) => Promise<boolean>;\n addUserToGroup: (\n input: AddOrganizationGroupUserInput,\n ) => ReturnType<typeof addOrganizationGroupUser>;\n createGroup: (name: string) => ReturnType<typeof createOrganizationGroup>;\n deleteGroup: (\n groupId: string,\n ) => ReturnType<typeof deleteGroupForOrganization>;\n importUserById: (userId: string) => ReturnType<typeof importOrganizationUser>;\n loadBilling: () => ReturnType<typeof loadOrganizationBilling>;\n /** Billing for an organization the session is not currently switched to. */\n loadBillingForOrganization: (\n organizationId: string,\n ) => ReturnType<typeof loadOrganizationBilling>;\n loadBillingHistory: () => ReturnType<typeof loadOrganizationBillingHistory>;\n loadBillingManagementUrl: () => ReturnType<\n typeof loadOrganizationBillingManagementUrl\n >;\n /** Direct Stripe checkout (issue #1654): options, start, and cancel. */\n loadStripeCheckoutOptions: (\n organizationId?: string,\n ) => ReturnType<typeof loadStripeCheckoutOptions>;\n createStripeCheckout: (\n organizationId?: string,\n ) => ReturnType<typeof createStripeCheckout>;\n createStripeCheckoutSession: (\n returnUrl: string,\n organizationId?: string,\n ) => ReturnType<typeof createStripeCheckoutSession>;\n cancelStripeSubscription: () => ReturnType<typeof cancelStripeSubscription>;\n claimNativeSubscription: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof claimNativeOrganizationSubscription>;\n checkNativePurchaseEligibility: (\n organizationId: string,\n store: NativeSubscriptionStore,\n ) => ReturnType<typeof checkNativePurchaseEligibility>;\n loadDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"reconcile\"]\n >;\n loadLocalDataUsage: () => ReturnType<\n OrganizationDataUsageCoordinator[\"loadLocal\"]\n >;\n loadDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcile\"]\n >;\n loadDirectoryAndGroupsAfterMutation: () => ReturnType<\n OrganizationReadModelCoordinator[\"reconcileAfterMutation\"]\n >;\n loadLocalDirectoryAndGroups: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocal\"]\n >;\n loadGroupMembers: (\n groupId: string,\n ) => ReturnType<\n InternalWorkflowRuntimeInput[\"apiClient\"][\"listOrganizationGroupMembers\"]\n >;\n loadGroupPresentationDetails(\n groupId: string,\n ): ReturnType<typeof loadOrganizationGroupPresentationDetails>;\n loadGroupContainers: (\n groupId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalGroupContainers\"]>;\n loadGrants: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadLocalGrants\"]\n >;\n listLocalOrganizations: () => Promise<LocalOrganizationSummary[]>;\n loadPolicyHistory: () => ReturnType<\n OrganizationReadModelCoordinator[\"loadOrganizationPolicyHistory\"]\n >;\n loadUserDetail: (\n userId: string,\n ) => ReturnType<OrganizationReadModelCoordinator[\"loadLocalUserDetail\"]>;\n updateRosterEntry: (\n userId: string,\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationRosterEntry>;\n updateProfile: (\n profileDocumentId: string | null,\n ) => ReturnType<typeof updateOrganizationProfile>;\n removeUserFromGroup: (\n input: RemoveOrganizationGroupUserInput,\n ) => ReturnType<typeof removeOrganizationGroupUser>;\n revokeGrant: (\n grant: OrganizationGrantRef,\n ) => Promise<\n | Awaited<ReturnType<typeof revokeOrganizationContainerGrant>>\n | Awaited<ReturnType<typeof rotateOrganizationGroupForAccessSetShrink>>\n >;\n startTrial: (\n organizationId?: string,\n ) => ReturnType<typeof startOrganizationTrial>;\n}\n"]}
@@ -0,0 +1,16 @@
1
+ import type { AuthoredPrincipalMutation } from "../../data/principals/principalMutationJournal.js";
2
+ import type { InternalRuntime } from "../workflowRuntime.js";
3
+ export interface AbandonOrganizationPolicyMutationInput {
4
+ readonly organizationId: string;
5
+ readonly mutation: AuthoredPrincipalMutation;
6
+ readonly acknowledgeUnknownOutcome: true;
7
+ }
8
+ export interface DiscardUnreadableOrganizationPolicyMutationInput {
9
+ readonly organizationId: string;
10
+ readonly recordId: string;
11
+ readonly acknowledgeUnknownOutcome: true;
12
+ }
13
+ export declare function discardUnreadableOrganizationPolicyMutation(service: InternalRuntime, input: DiscardUnreadableOrganizationPolicyMutationInput): Promise<boolean>;
14
+ export declare function readPendingOrganizationPolicyMutation(service: InternalRuntime, organizationId: string): Promise<AuthoredPrincipalMutation | null>;
15
+ export declare function retryPendingOrganizationPolicyMutation(service: InternalRuntime, organizationId: string): Promise<void>;
16
+ export declare function abandonPendingOrganizationPolicyMutation(service: InternalRuntime, input: AbandonOrganizationPolicyMutationInput): Promise<boolean>;
@@ -0,0 +1,23 @@
1
+ import { assertProjectionVerificationCurrent } from "../../data/keyingProjectionVerification/types.js";
2
+ import { currentOrganizationMutation } from "./principalMutationScope.js";
3
+ async function runRecovery(service, organizationId, run) {
4
+ const active = currentOrganizationMutation(service, true);
5
+ const { runtime, stillCurrent } = active;
6
+ assertProjectionVerificationCurrent(() => stillCurrent() && runtime.auth.organizationId === organizationId);
7
+ const result = await run(runtime.apiClient);
8
+ assertProjectionVerificationCurrent(stillCurrent);
9
+ return result;
10
+ }
11
+ export function discardUnreadableOrganizationPolicyMutation(service, input) {
12
+ return runRecovery(service, input.organizationId, (api) => api.discardUnreadablePrincipalMutation(input.organizationId, input.recordId, input.acknowledgeUnknownOutcome));
13
+ }
14
+ export function readPendingOrganizationPolicyMutation(service, organizationId) {
15
+ return runRecovery(service, organizationId, (api) => api.readPendingPrincipalMutation(organizationId));
16
+ }
17
+ export function retryPendingOrganizationPolicyMutation(service, organizationId) {
18
+ return runRecovery(service, organizationId, (api) => api.recoverPendingPrincipalMutation(organizationId));
19
+ }
20
+ export function abandonPendingOrganizationPolicyMutation(service, input) {
21
+ return runRecovery(service, input.organizationId, (api) => api.abandonPendingPrincipalMutation(input.organizationId, input.mutation, input.acknowledgeUnknownOutcome));
22
+ }
23
+ //# sourceMappingURL=principalMutationRecovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalMutationRecovery.js","sourceRoot":"","sources":["principalMutationRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AAIpG,OAAO,EAAE,2BAA2B,EAAE,MAAM,0BAA0B,CAAC;AAcvE,KAAK,UAAU,WAAW,CACxB,OAAwB,EACxB,cAAsB,EACtB,GAAsD;IAEtD,MAAM,MAAM,GAAG,2BAA2B,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAC1D,MAAM,EAAE,OAAO,EAAE,YAAY,EAAE,GAAG,MAAM,CAAC;IACzC,mCAAmC,CACjC,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,OAAO,CAAC,IAAI,CAAC,cAAc,KAAK,cAAc,CACvE,CAAC;IACF,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC;IAC5C,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,MAAM,UAAU,2CAA2C,CACzD,OAAwB,EACxB,KAAuD;IAEvD,OAAO,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,cAAc,EAAE,CAAC,GAAG,EAAE,EAAE,CACxD,GAAG,CAAC,kCAAkC,CACpC,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,QAAQ,EACd,KAAK,CAAC,yBAAyB,CAChC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,qCAAqC,CACnD,OAAwB,EACxB,cAAsB;IAEtB,OAAO,WAAW,CAAC,OAAO,EAAE,cAAc,EAAE,CAAC,GAAG,EAAE,EAAE,CAClD,GAAG,CAAC,4BAA4B,CAAC,cAAc,CAAC,CACjD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,OAAwB,EACxB,cAAsB;IAEtB,OAAO,WAAW,CAAC,OAAO,EAAE,cAAc,EAAE,CAAC,GAAG,EAAE,EAAE,CAClD,GAAG,CAAC,+BAA+B,CAAC,cAAc,CAAC,CACpD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,wCAAwC,CACtD,OAAwB,EACxB,KAA6C;IAE7C,OAAO,WAAW,CAAC,OAAO,EAAE,KAAK,CAAC,cAAc,EAAE,CAAC,GAAG,EAAE,EAAE,CACxD,GAAG,CAAC,+BAA+B,CACjC,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,QAAQ,EACd,KAAK,CAAC,yBAAyB,CAChC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport type { AuthoredPrincipalMutation } from \"../../data/principals/principalMutationJournal\";\nimport type { PrincipalMutationRecoveryApi } from \"../../workflows/organizations/principalMutationJournalManagement\";\nimport type { InternalRuntime } from \"../workflowRuntime\";\nimport { currentOrganizationMutation } from \"./principalMutationScope\";\n\nexport interface AbandonOrganizationPolicyMutationInput {\n readonly organizationId: string;\n readonly mutation: AuthoredPrincipalMutation;\n readonly acknowledgeUnknownOutcome: true;\n}\n\nexport interface DiscardUnreadableOrganizationPolicyMutationInput {\n readonly organizationId: string;\n readonly recordId: string;\n readonly acknowledgeUnknownOutcome: true;\n}\n\nasync function runRecovery<T>(\n service: InternalRuntime,\n organizationId: string,\n run: (api: PrincipalMutationRecoveryApi) => Promise<T>,\n): Promise<T> {\n const active = currentOrganizationMutation(service, true);\n const { runtime, stillCurrent } = active;\n assertProjectionVerificationCurrent(\n () => stillCurrent() && runtime.auth.organizationId === organizationId,\n );\n const result = await run(runtime.apiClient);\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n}\n\nexport function discardUnreadableOrganizationPolicyMutation(\n service: InternalRuntime,\n input: DiscardUnreadableOrganizationPolicyMutationInput,\n) {\n return runRecovery(service, input.organizationId, (api) =>\n api.discardUnreadablePrincipalMutation(\n input.organizationId,\n input.recordId,\n input.acknowledgeUnknownOutcome,\n ),\n );\n}\n\nexport function readPendingOrganizationPolicyMutation(\n service: InternalRuntime,\n organizationId: string,\n) {\n return runRecovery(service, organizationId, (api) =>\n api.readPendingPrincipalMutation(organizationId),\n );\n}\n\nexport function retryPendingOrganizationPolicyMutation(\n service: InternalRuntime,\n organizationId: string,\n) {\n return runRecovery(service, organizationId, (api) =>\n api.recoverPendingPrincipalMutation(organizationId),\n );\n}\n\nexport function abandonPendingOrganizationPolicyMutation(\n service: InternalRuntime,\n input: AbandonOrganizationPolicyMutationInput,\n) {\n return runRecovery(service, input.organizationId, (api) =>\n api.abandonPendingPrincipalMutation(\n input.organizationId,\n input.mutation,\n input.acknowledgeUnknownOutcome,\n ),\n );\n}\n"]}
@@ -1,12 +1,17 @@
1
1
  /** Capture a mutation's identity/database lifetime without freezing live status. */
2
- export function currentOrganizationMutation(service) {
2
+ export function currentOrganizationMutation(service, allowTokenRenewal = false) {
3
3
  const runtime = service.workflowInput();
4
4
  const sessionGeneration = service.sessionGeneration;
5
5
  return {
6
6
  runtime,
7
7
  stillCurrent: () => {
8
8
  const current = service.workflowInput();
9
- return (service.sessionGeneration === sessionGeneration &&
9
+ return (
10
+ // Journal API custody survives token renewal, but its identity,
11
+ // organization and storage generation are still bound immutably.
12
+ (allowTokenRenewal
13
+ ? current.apiClient === runtime.apiClient
14
+ : service.sessionGeneration === sessionGeneration) &&
10
15
  current.infra.dbStatus === "ready" &&
11
16
  current.infra.execSql === runtime.infra.execSql &&
12
17
  current.state.domainScope === runtime.state.domainScope &&
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationScope.js","sourceRoot":"","sources":["principalMutationScope.ts"],"names":[],"mappings":"AAEA,oFAAoF;AACpF,MAAM,UAAU,2BAA2B,CACzC,OAAqE;IAErE,MAAM,OAAO,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;IACxC,MAAM,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IACpD,OAAO;QACL,OAAO;QACP,YAAY,EAAE,GAAG,EAAE;YACjB,MAAM,OAAO,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;YACxC,OAAO,CACL,OAAO,CAAC,iBAAiB,KAAK,iBAAiB;gBAC/C,OAAO,CAAC,KAAK,CAAC,QAAQ,KAAK,OAAO;gBAClC,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,OAAO,CAAC,KAAK,CAAC,OAAO;gBAC/C,OAAO,CAAC,KAAK,CAAC,WAAW,KAAK,OAAO,CAAC,KAAK,CAAC,WAAW;gBACvD,OAAO,CAAC,IAAI,CAAC,eAAe;gBAC5B,OAAO,CAAC,IAAI,CAAC,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,cAAc;gBAC3D,OAAO,CAAC,IAAI,CAAC,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,MAAM;gBAC3C,OAAO,CAAC,MAAM,CAAC,kBAAkB,KAAK,OAAO,CAAC,MAAM,CAAC,kBAAkB,CACxE,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { InternalRuntime } from \"../workflowRuntime\";\n\n/** Capture a mutation's identity/database lifetime without freezing live status. */\nexport function currentOrganizationMutation(\n service: Pick<InternalRuntime, \"workflowInput\" | \"sessionGeneration\">,\n) {\n const runtime = service.workflowInput();\n const sessionGeneration = service.sessionGeneration;\n return {\n runtime,\n stillCurrent: () => {\n const current = service.workflowInput();\n return (\n service.sessionGeneration === sessionGeneration &&\n current.infra.dbStatus === \"ready\" &&\n current.infra.execSql === runtime.infra.execSql &&\n current.state.domainScope === runtime.state.domainScope &&\n current.auth.isAuthenticated &&\n current.auth.organizationId === runtime.auth.organizationId &&\n current.auth.userId === runtime.auth.userId &&\n current.crypto.signingFingerprint === runtime.crypto.signingFingerprint\n );\n },\n };\n}\n"]}
1
+ {"version":3,"file":"principalMutationScope.js","sourceRoot":"","sources":["principalMutationScope.ts"],"names":[],"mappings":"AAEA,oFAAoF;AACpF,MAAM,UAAU,2BAA2B,CACzC,OAAqE,EACrE,iBAAiB,GAAG,KAAK;IAEzB,MAAM,OAAO,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;IACxC,MAAM,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC;IACpD,OAAO;QACL,OAAO;QACP,YAAY,EAAE,GAAG,EAAE;YACjB,MAAM,OAAO,GAAG,OAAO,CAAC,aAAa,EAAE,CAAC;YACxC,OAAO;YACL,gEAAgE;YAChE,iEAAiE;YACjE,CAAC,iBAAiB;gBAChB,CAAC,CAAC,OAAO,CAAC,SAAS,KAAK,OAAO,CAAC,SAAS;gBACzC,CAAC,CAAC,OAAO,CAAC,iBAAiB,KAAK,iBAAiB,CAAC;gBACpD,OAAO,CAAC,KAAK,CAAC,QAAQ,KAAK,OAAO;gBAClC,OAAO,CAAC,KAAK,CAAC,OAAO,KAAK,OAAO,CAAC,KAAK,CAAC,OAAO;gBAC/C,OAAO,CAAC,KAAK,CAAC,WAAW,KAAK,OAAO,CAAC,KAAK,CAAC,WAAW;gBACvD,OAAO,CAAC,IAAI,CAAC,eAAe;gBAC5B,OAAO,CAAC,IAAI,CAAC,cAAc,KAAK,OAAO,CAAC,IAAI,CAAC,cAAc;gBAC3D,OAAO,CAAC,IAAI,CAAC,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,MAAM;gBAC3C,OAAO,CAAC,MAAM,CAAC,kBAAkB,KAAK,OAAO,CAAC,MAAM,CAAC,kBAAkB,CACxE,CAAC;QACJ,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { InternalRuntime } from \"../workflowRuntime\";\n\n/** Capture a mutation's identity/database lifetime without freezing live status. */\nexport function currentOrganizationMutation(\n service: Pick<InternalRuntime, \"workflowInput\" | \"sessionGeneration\">,\n allowTokenRenewal = false,\n) {\n const runtime = service.workflowInput();\n const sessionGeneration = service.sessionGeneration;\n return {\n runtime,\n stillCurrent: () => {\n const current = service.workflowInput();\n return (\n // Journal API custody survives token renewal, but its identity,\n // organization and storage generation are still bound immutably.\n (allowTokenRenewal\n ? current.apiClient === runtime.apiClient\n : service.sessionGeneration === sessionGeneration) &&\n current.infra.dbStatus === \"ready\" &&\n current.infra.execSql === runtime.infra.execSql &&\n current.state.domainScope === runtime.state.domainScope &&\n current.auth.isAuthenticated &&\n current.auth.organizationId === runtime.auth.organizationId &&\n current.auth.userId === runtime.auth.userId &&\n current.crypto.signingFingerprint === runtime.crypto.signingFingerprint\n );\n },\n };\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import type { ApiClient } from "../internal/api-client/index.js";
2
+ import type { SigningKeyPair } from "../internal/crypto/index.js";
3
+ import type { ExecSql } from "../data/sqlite/sqlSchema.js";
4
+ import { type PrincipalMutationRecoveryApi } from "../workflows/organizations/principalMutationJournalManagement.js";
5
+ export interface PrincipalMutationRuntimeScope {
6
+ readonly database: object;
7
+ readonly execSql: ExecSql;
8
+ readonly generation: number;
9
+ readonly identityTrustDomain: string;
10
+ readonly signingFingerprint: string;
11
+ readonly signingKeyPair: SigningKeyPair;
12
+ readonly userId: string;
13
+ }
14
+ export type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;
15
+ interface PrincipalMutationApiCustodyInput {
16
+ readonly api: ApiClient;
17
+ readonly readScope: () => PrincipalMutationRuntimeScope | null;
18
+ readonly principalMutationTimeoutMs?: number | undefined;
19
+ }
20
+ /** Keep API methods bound to their real receiver and journal only policy writes. */
21
+ export declare function createPrincipalMutationApiCustody(input: PrincipalMutationApiCustodyInput): {
22
+ bind(): PrincipalMutationApi;
23
+ };
24
+ export {};
@@ -0,0 +1,108 @@
1
+ import { abandonJournaledPrincipalMutation, discardUnreadableJournaledPrincipalMutation, readJournaledPrincipalMutation, } from "../workflows/organizations/principalMutationJournalManagement.js";
2
+ import { recoverJournaledPrincipalMutation, submitJournaledPrincipalMutation, } from "../workflows/organizations/principalMutationJournalSession.js";
3
+ import { createPrincipalMutationDispatcher } from "./principalMutationDeadline.js";
4
+ function sameScope(current, bound) {
5
+ if (!current || !bound)
6
+ return current === bound;
7
+ return (current.database === bound.database &&
8
+ current.execSql === bound.execSql &&
9
+ current.generation === bound.generation &&
10
+ current.identityTrustDomain === bound.identityTrustDomain &&
11
+ current.signingFingerprint === bound.signingFingerprint &&
12
+ current.signingKeyPair === bound.signingKeyPair &&
13
+ current.userId === bound.userId);
14
+ }
15
+ function mutationContext(input, scope, organizationId) {
16
+ if (!scope)
17
+ throw new Error("Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage");
18
+ return {
19
+ execSql: scope.execSql,
20
+ signingKeyPair: scope.signingKeyPair,
21
+ scope: {
22
+ identityTrustDomain: scope.identityTrustDomain,
23
+ organizationId,
24
+ signingFingerprint: scope.signingFingerprint,
25
+ userId: scope.userId,
26
+ },
27
+ stillCurrent: () => sameScope(input.readScope(), scope),
28
+ };
29
+ }
30
+ /** Keep API methods bound to their real receiver and journal only policy writes. */
31
+ export function createPrincipalMutationApiCustody(input) {
32
+ const dispatch = createPrincipalMutationDispatcher(input.principalMutationTimeoutMs);
33
+ let cached = null;
34
+ return {
35
+ bind() {
36
+ const scope = input.readScope();
37
+ if (cached && sameScope(scope, cached.scope))
38
+ return cached.api;
39
+ const context = (organizationId) => mutationContext(input, scope, organizationId);
40
+ const commit = async (organizationId, groupId, request, options) => submitJournaledPrincipalMutation({
41
+ ...context(organizationId),
42
+ mutation: { groupId, request },
43
+ submit: (mutation) => dispatch(options, (dispatchOptions) => input.api.commitOrganizationGroupPolicyResult(organizationId, mutation.groupId, mutation.request, dispatchOptions)),
44
+ });
45
+ const read = async (organizationId) => scope
46
+ ? readJournaledPrincipalMutation(context(organizationId))
47
+ : null;
48
+ const abandon = async (organizationId, mutation, acknowledgeUnknownOutcome) => abandonJournaledPrincipalMutation({
49
+ ...context(organizationId),
50
+ mutation,
51
+ acknowledgeUnknownOutcome,
52
+ });
53
+ const methods = {
54
+ discardUnreadablePrincipalMutation: async (organizationId, recordId, acknowledgeUnknownOutcome) => discardUnreadableJournaledPrincipalMutation({
55
+ ...context(organizationId),
56
+ recordId,
57
+ acknowledgeUnknownOutcome,
58
+ }),
59
+ readPendingPrincipalMutation: read,
60
+ abandonPendingPrincipalMutation: abandon,
61
+ commitOrganizationGroupPolicyResult: commit,
62
+ commitOrganizationGroupPolicy: async (...args) => {
63
+ const result = await commit(...args);
64
+ return result.ok ? result.data : null;
65
+ },
66
+ recoverPendingPrincipalMutation: async (organizationId) => {
67
+ await recoverJournaledPrincipalMutation({
68
+ ...context(organizationId),
69
+ submit: (mutation) => dispatch({ reportErrors: false }, (dispatchOptions) => input.api.commitOrganizationGroupPolicyResult(organizationId, mutation.groupId, mutation.request, dispatchOptions)),
70
+ });
71
+ },
72
+ };
73
+ const api = bindMutationMethods(input.api, methods);
74
+ cached = { scope, api };
75
+ return api;
76
+ },
77
+ };
78
+ }
79
+ function bindMutationMethods(api, methods) {
80
+ const boundMethods = new Map();
81
+ const bound = new Proxy(api, {
82
+ get(target, property) {
83
+ if (Object.hasOwn(methods, property))
84
+ return Reflect.get(methods, property);
85
+ const value = Reflect.get(target, property, target);
86
+ if (typeof value !== "function")
87
+ return value;
88
+ const previous = boundMethods.get(property);
89
+ if (previous?.source === value)
90
+ return previous.bound;
91
+ const bound = value.bind(target);
92
+ boundMethods.set(property, { source: value, bound });
93
+ return bound;
94
+ },
95
+ });
96
+ // The checked overrides supply the signatures; verify their presence through
97
+ // the reflective boundary before exposing the extended API to callers.
98
+ if (!hasRecoveryMethods(bound))
99
+ throw new Error("Principal mutation recovery methods are unavailable");
100
+ return bound;
101
+ }
102
+ function hasRecoveryMethods(api) {
103
+ return (typeof Reflect.get(api, "readPendingPrincipalMutation") === "function" &&
104
+ typeof Reflect.get(api, "recoverPendingPrincipalMutation") === "function" &&
105
+ typeof Reflect.get(api, "abandonPendingPrincipalMutation") === "function" &&
106
+ typeof Reflect.get(api, "discardUnreadablePrincipalMutation") === "function");
107
+ }
108
+ //# sourceMappingURL=principalMutationApi.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalMutationApi.js","sourceRoot":"","sources":["principalMutationApi.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iCAAiC,EACjC,2CAA2C,EAE3C,8BAA8B,GAC/B,MAAM,+DAA+D,CAAC;AACvE,OAAO,EACL,iCAAiC,EACjC,gCAAgC,GACjC,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAAE,iCAAiC,EAAE,MAAM,6BAA6B,CAAC;AAYhF,SAAS,SAAS,CAChB,OAA6C,EAC7C,KAA2C;IAE3C,IAAI,CAAC,OAAO,IAAI,CAAC,KAAK;QAAE,OAAO,OAAO,KAAK,KAAK,CAAC;IACjD,OAAO,CACL,OAAO,CAAC,QAAQ,KAAK,KAAK,CAAC,QAAQ;QACnC,OAAO,CAAC,OAAO,KAAK,KAAK,CAAC,OAAO;QACjC,OAAO,CAAC,UAAU,KAAK,KAAK,CAAC,UAAU;QACvC,OAAO,CAAC,mBAAmB,KAAK,KAAK,CAAC,mBAAmB;QACzD,OAAO,CAAC,kBAAkB,KAAK,KAAK,CAAC,kBAAkB;QACvD,OAAO,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAC/C,OAAO,CAAC,MAAM,KAAK,KAAK,CAAC,MAAM,CAChC,CAAC;AACJ,CAAC;AAeD,SAAS,eAAe,CACtB,KAAuC,EACvC,KAA2C,EAC3C,cAAsB;IAEtB,IAAI,CAAC,KAAK;QACR,MAAM,IAAI,KAAK,CACb,+GAA+G,CAChH,CAAC;IACJ,OAAO;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f,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO,CACL,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,8BAA8B,CAAC,KAAK,UAAU;QACtE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,iCAAiC,CAAC,KAAK,UAAU;QACzE,OAAO,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,oCAAoC,CAAC,KAAK,UAAU,CAC7E,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { ExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n abandonJournaledPrincipalMutation,\n discardUnreadableJournaledPrincipalMutation,\n type PrincipalMutationRecoveryApi,\n readJournaledPrincipalMutation,\n} from \"../workflows/organizations/principalMutationJournalManagement\";\nimport {\n recoverJournaledPrincipalMutation,\n submitJournaledPrincipalMutation,\n} from \"../workflows/organizations/principalMutationJournalSession\";\nimport { createPrincipalMutationDispatcher } from \"./principalMutationDeadline\";\n\nexport interface PrincipalMutationRuntimeScope {\n readonly database: object;\n readonly execSql: ExecSql;\n readonly generation: number;\n readonly identityTrustDomain: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}\n\nfunction sameScope(\n current: PrincipalMutationRuntimeScope | null,\n bound: PrincipalMutationRuntimeScope | null,\n): boolean {\n if (!current || !bound) return current === bound;\n return (\n current.database === bound.database &&\n current.execSql === bound.execSql &&\n current.generation === bound.generation &&\n current.identityTrustDomain === bound.identityTrustDomain &&\n current.signingFingerprint === bound.signingFingerprint &&\n current.signingKeyPair === bound.signingKeyPair &&\n current.userId === bound.userId\n );\n}\n\nexport type PrincipalMutationApi = ApiClient & PrincipalMutationRecoveryApi;\ntype MutationOverrides = Pick<\n ApiClient,\n \"commitOrganizationGroupPolicy\" | \"commitOrganizationGroupPolicyResult\"\n> &\n PrincipalMutationRecoveryApi;\n\ninterface PrincipalMutationApiCustodyInput {\n readonly api: ApiClient;\n readonly readScope: () => PrincipalMutationRuntimeScope | null;\n readonly principalMutationTimeoutMs?: number | undefined;\n}\n\nfunction mutationContext(\n input: PrincipalMutationApiCustodyInput,\n scope: PrincipalMutationRuntimeScope | null,\n organizationId: string,\n) {\n if (!scope)\n throw new Error(\n \"Principal mutations require an authenticated signing identity, a trusted API origin and durable local storage\",\n );\n return {\n execSql: scope.execSql,\n signingKeyPair: scope.signingKeyPair,\n scope: {\n identityTrustDomain: scope.identityTrustDomain,\n organizationId,\n signingFingerprint: scope.signingFingerprint,\n userId: scope.userId,\n },\n stillCurrent: () => sameScope(input.readScope(), scope),\n };\n}\n\n/** Keep API methods bound to their real receiver and journal only policy writes. */\nexport function createPrincipalMutationApiCustody(\n input: PrincipalMutationApiCustodyInput,\n) {\n const dispatch = createPrincipalMutationDispatcher(\n input.principalMutationTimeoutMs,\n );\n let cached: {\n scope: PrincipalMutationRuntimeScope | null;\n api: PrincipalMutationApi;\n } | null = null;\n return {\n bind(): PrincipalMutationApi {\n const scope = input.readScope();\n if (cached && sameScope(scope, cached.scope)) return cached.api;\n const context = (organizationId: string) =>\n mutationContext(input, scope, organizationId);\n const commit: ApiClient[\"commitOrganizationGroupPolicyResult\"] = async (\n organizationId,\n groupId,\n request,\n options,\n ) =>\n submitJournaledPrincipalMutation({\n ...context(organizationId),\n mutation: { groupId, request },\n submit: (mutation) =>\n dispatch(options, (dispatchOptions) =>\n input.api.commitOrganizationGroupPolicyResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n dispatchOptions,\n ),\n ),\n });\n const read: PrincipalMutationRecoveryApi[\"readPendingPrincipalMutation\"] =\n async (organizationId) =>\n scope\n ? readJournaledPrincipalMutation(context(organizationId))\n : null;\n const abandon: PrincipalMutationRecoveryApi[\"abandonPendingPrincipalMutation\"] =\n async (organizationId, mutation, acknowledgeUnknownOutcome) =>\n abandonJournaledPrincipalMutation({\n ...context(organizationId),\n mutation,\n acknowledgeUnknownOutcome,\n });\n const methods = {\n discardUnreadablePrincipalMutation: async (\n organizationId,\n recordId,\n acknowledgeUnknownOutcome,\n ) =>\n discardUnreadableJournaledPrincipalMutation({\n ...context(organizationId),\n recordId,\n acknowledgeUnknownOutcome,\n }),\n readPendingPrincipalMutation: read,\n abandonPendingPrincipalMutation: abandon,\n commitOrganizationGroupPolicyResult: commit,\n commitOrganizationGroupPolicy: async (...args) => {\n const result = await commit(...args);\n return result.ok ? result.data : null;\n },\n recoverPendingPrincipalMutation: async (organizationId) => {\n await recoverJournaledPrincipalMutation({\n ...context(organizationId),\n submit: (mutation) =>\n dispatch({ reportErrors: false }, (dispatchOptions) =>\n input.api.commitOrganizationGroupPolicyResult(\n organizationId,\n mutation.groupId,\n mutation.request,\n dispatchOptions,\n ),\n ),\n });\n },\n } satisfies MutationOverrides;\n const api = bindMutationMethods(input.api, methods);\n cached = { scope, api };\n return api;\n },\n };\n}\n\nfunction bindMutationMethods(\n api: ApiClient,\n methods: MutationOverrides,\n): PrincipalMutationApi {\n const boundMethods = new Map<\n PropertyKey,\n { source: unknown; bound: unknown }\n >();\n const bound = new Proxy(api, {\n get(target, property) {\n if (Object.hasOwn(methods, property))\n return Reflect.get(methods, property);\n const value: unknown = Reflect.get(target, property, target);\n if (typeof value !== \"function\") return value;\n const previous = boundMethods.get(property);\n if (previous?.source === value) return previous.bound;\n const bound = value.bind(target);\n boundMethods.set(property, { source: value, bound });\n return bound;\n },\n });\n // The checked overrides supply the signatures; verify their presence through\n // the reflective boundary before exposing the extended API to callers.\n if (!hasRecoveryMethods(bound))\n throw new Error(\"Principal mutation recovery methods are unavailable\");\n return bound;\n}\n\nfunction hasRecoveryMethods(api: ApiClient): api is PrincipalMutationApi {\n return (\n typeof Reflect.get(api, \"readPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"recoverPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"abandonPendingPrincipalMutation\") === \"function\" &&\n typeof Reflect.get(api, \"discardUnreadablePrincipalMutation\") === \"function\"\n );\n}\n"]}
@@ -0,0 +1,23 @@
1
+ /** One host-configurable deadline covers dispatch and all preparation exchanges. */
2
+ export function createPrincipalMutationDispatcher(timeoutMs = 60_000) {
3
+ if (!Number.isSafeInteger(timeoutMs) ||
4
+ timeoutMs <= 0 ||
5
+ timeoutMs > 2_147_483_647)
6
+ throw new RangeError("Principal mutation timeout must be a positive integer no greater than 2147483647 milliseconds");
7
+ return async (options, submit) => {
8
+ const controller = new AbortController();
9
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
10
+ try {
11
+ return await submit({
12
+ ...options,
13
+ signal: options?.signal
14
+ ? AbortSignal.any([options.signal, controller.signal])
15
+ : controller.signal,
16
+ });
17
+ }
18
+ finally {
19
+ clearTimeout(timer);
20
+ }
21
+ };
22
+ }
23
+ //# sourceMappingURL=principalMutationDeadline.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalMutationDeadline.js","sourceRoot":"","sources":["principalMutationDeadline.ts"],"names":[],"mappings":"AAEA,oFAAoF;AACpF,MAAM,UAAU,iCAAiC,CAAC,SAAS,GAAG,MAAM;IAClE,IACE,CAAC,MAAM,CAAC,aAAa,CAAC,SAAS,CAAC;QAChC,SAAS,IAAI,CAAC;QACd,SAAS,GAAG,aAAa;QAEzB,MAAM,IAAI,UAAU,CAClB,+FAA+F,CAChG,CAAC;IACJ,OAAO,KAAK,EACV,OAAyC,EACzC,MAAqD,EACzC,EAAE;QACd,MAAM,UAAU,GAAG,IAAI,eAAe,EAAE,CAAC;QACzC,MAAM,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,UAAU,CAAC,KAAK,EAAE,EAAE,SAAS,CAAC,CAAC;QAC9D,IAAI,CAAC;YACH,OAAO,MAAM,MAAM,CAAC;gBAClB,GAAG,OAAO;gBACV,MAAM,EAAE,OAAO,EAAE,MAAM;oBACrB,CAAC,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC,OAAO,CAAC,MAAM,EAAE,UAAU,CAAC,MAAM,CAAC,CAAC;oBACtD,CAAC,CAAC,UAAU,CAAC,MAAM;aACtB,CAAC,CAAC;QACL,CAAC;gBAAS,CAAC;YACT,YAAY,CAAC,KAAK,CAAC,CAAC;QACtB,CAAC;IACH,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import type { RequestResultOptions } from \"@tearleads/api-client\";\n\n/** One host-configurable deadline covers dispatch and all preparation exchanges. */\nexport function createPrincipalMutationDispatcher(timeoutMs = 60_000) {\n if (\n !Number.isSafeInteger(timeoutMs) ||\n timeoutMs <= 0 ||\n timeoutMs > 2_147_483_647\n )\n throw new RangeError(\n \"Principal mutation timeout must be a positive integer no greater than 2147483647 milliseconds\",\n );\n return async <T>(\n options: RequestResultOptions | undefined,\n submit: (options: RequestResultOptions) => Promise<T>,\n ): Promise<T> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n return await submit({\n ...options,\n signal: options?.signal\n ? AbortSignal.any([options.signal, controller.signal])\n : controller.signal,\n });\n } finally {\n clearTimeout(timer);\n }\n };\n}\n"]}
@@ -12,6 +12,7 @@ import type { Events } from "./events.js";
12
12
  import type { Identity } from "./identity.js";
13
13
  import type { Network } from "./network.js";
14
14
  import { type PrincipalHistoryKeyProvider } from "./principalHistoryProtection.js";
15
+ import { type PrincipalMutationApi } from "./principalMutationApi.js";
15
16
  import type { Session } from "./session/sessionTypes.js";
16
17
  import type { SyncBillingGate } from "./syncBillingGate.js";
17
18
  type HostWorkflowRuntimeUtilInput = Omit<WorkflowRuntimeUtilInput, "reportSecurityIncident">;
@@ -25,7 +26,7 @@ export interface Runtime {
25
26
  subscribe(listener: RuntimeListener): () => void;
26
27
  }
27
28
  export interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {
28
- readonly apiClient: ApiClient;
29
+ readonly apiClient: PrincipalMutationApi;
29
30
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
30
31
  readonly withPrincipalHistoryProtection?: PrincipalHistoryProtectionLease | undefined;
31
32
  }
@@ -52,6 +53,7 @@ interface WorkflowRuntimeDependencies {
52
53
  network: Network;
53
54
  peerScope?: string | null;
54
55
  principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;
56
+ principalMutationTimeoutMs?: number | undefined;
55
57
  reportSecurityIncident: SecurityIncidentReporter;
56
58
  session: Session;
57
59
  syncBillingGate?: SyncBillingGate | undefined;
@@ -3,8 +3,36 @@ import { unavailableExecSql } from "../data/sqlite/sqlSchema.js";
3
3
  import { createApiUserIdentitySource, createTrustedUserIdentityService, } from "../data/trustedUserIdentity/index.js";
4
4
  import { createListenerSet } from "./listenerSet.js";
5
5
  import { createPrincipalHistoryProtectionCustody, } from "./principalHistoryProtection.js";
6
+ import { createPrincipalMutationApiCustody, } from "./principalMutationApi.js";
6
7
  import { adoptSessionRootContainer } from "./rootContainerAdoption.js";
7
8
  import { acknowledgedSessionRoot } from "./session/sessionRootAuthority.js";
9
+ function createRuntimeMutationApi(dependencies, readGeneration) {
10
+ return createPrincipalMutationApiCustody({
11
+ api: dependencies.api,
12
+ principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,
13
+ readScope: () => {
14
+ const { signingKeyPair, signingFingerprint } = dependencies.identity;
15
+ const { userId, isAuthenticated } = dependencies.session;
16
+ const identityTrustDomain = dependencies.identityTrustDomain;
17
+ if (!isAuthenticated ||
18
+ !userId ||
19
+ !signingKeyPair ||
20
+ !signingFingerprint ||
21
+ !identityTrustDomain ||
22
+ dependencies.database.status !== "ready")
23
+ return null;
24
+ return {
25
+ database: dependencies.getDomainScope(),
26
+ execSql: dependencies.database.requireExecSql("principal mutation"),
27
+ generation: readGeneration(),
28
+ identityTrustDomain,
29
+ signingFingerprint,
30
+ signingKeyPair,
31
+ userId,
32
+ };
33
+ },
34
+ });
35
+ }
8
36
  export function createRuntime(dependencies) {
9
37
  const trustedUserIdentityService = createTrustedUserIdentityService({
10
38
  getExecSql: () => dependencies.database.status === "ready"
@@ -50,7 +78,7 @@ export function createRuntime(dependencies) {
50
78
  };
51
79
  },
52
80
  });
53
- const runtimeInput = createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, historyProtection.bind);
81
+ const runtimeInput = createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, historyProtection.bind, createRuntimeMutationApi(dependencies, () => runtimeSubscription.mutationGeneration).bind);
54
82
  return {
55
83
  retirePrincipalHistoryProtection: historyProtection.retire,
56
84
  get sessionGeneration() {
@@ -81,6 +109,7 @@ function createRuntimeSubscription(dependencies) {
81
109
  let version = 0;
82
110
  let sessionGeneration = 0;
83
111
  let recoveryGeneration = 0;
112
+ let mutationGeneration = 0;
84
113
  let sessionSnapshot = dependencies.session.snapshot;
85
114
  const notifyListeners = () => {
86
115
  version += 1;
@@ -88,6 +117,7 @@ function createRuntimeSubscription(dependencies) {
88
117
  };
89
118
  const notifyAuthority = () => {
90
119
  recoveryGeneration += 1;
120
+ mutationGeneration += 1;
91
121
  notifyListeners();
92
122
  };
93
123
  dependencies.database.subscribe(notifyAuthority);
@@ -100,11 +130,16 @@ function createRuntimeSubscription(dependencies) {
100
130
  sessionGeneration += 1;
101
131
  recoveryGeneration += 1;
102
132
  }
133
+ if (sessionScopeChanged(sessionSnapshot, next))
134
+ mutationGeneration += 1;
103
135
  sessionSnapshot = next;
104
136
  notifyListeners();
105
137
  });
106
138
  dependencies.syncBillingGate?.subscribe(notifyListeners);
107
139
  return {
140
+ get mutationGeneration() {
141
+ return mutationGeneration;
142
+ },
108
143
  get recoveryGeneration() {
109
144
  return recoveryGeneration;
110
145
  },
@@ -132,13 +167,17 @@ function sessionAuthInput({ session, identity, }) {
132
167
  }
133
168
  /** Fields whose change invalidates work keyed on the session's authority. */
134
169
  function sessionAuthorityChanged(previous, next) {
135
- return (next.authToken !== previous.authToken ||
136
- next.isAuthenticated !== previous.isAuthenticated ||
170
+ return (next.authToken !== previous.authToken || sessionScopeChanged(previous, next));
171
+ }
172
+ // A transport token renewal cannot turn a definite write refusal into saved work.
173
+ // Journal custody still expires on every change to its identity or storage scope.
174
+ function sessionScopeChanged(previous, next) {
175
+ return (next.isAuthenticated !== previous.isAuthenticated ||
137
176
  next.isRoot !== previous.isRoot ||
138
177
  next.organizationId !== previous.organizationId ||
139
178
  next.userId !== previous.userId);
140
179
  }
141
- function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, bindHistoryProtection) {
180
+ function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, bindHistoryProtection, bindMutationApi) {
142
181
  let auth;
143
182
  let crypto;
144
183
  let infra;
@@ -190,7 +229,7 @@ function createRuntimeInputFactory(dependencies, resolveTrustedUserIdentity, bin
190
229
  };
191
230
  }
192
231
  return {
193
- apiClient: dependencies.api,
232
+ apiClient: bindMutationApi(),
194
233
  auth,
195
234
  crypto,
196
235
  infra,
@@ -1 +1 @@
1
- {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["workflowRuntime.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAG9F,OAAO,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AAC9D,OAAO,EACL,2BAA2B,EAC3B,gCAAgC,GAGjC,MAAM,6BAA6B,CAAC;AAcrC,OAAO,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AAElD,OAAO,EACL,uCAAuC,GAExC,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AAgEzE,MAAM,UAAU,aAAa,CAC3B,YAAyC;IAEzC,MAAM,0BAA0B,GAAG,gCAAgC,CAAC;QAClE,UAAU,EAAE,GAAG,EAAE,CACf,YAAY,CAAC,QAAQ,CAAC,MAAM,KAAK,OAAO;YACt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ACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAC1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { unavailableExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n type TrustedUserIdentityResolver,\n} from \"../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../workflows/container-contents/runtime\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../workflows/runtimeInput\";\nimport type { Blobs } from \"./blobs\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Identity } from \"./identity\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { acknowledgedSessionRoot } from \"./session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"./session/sessionTypes\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: ApiClient;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null,\n getLocalIdentity: () => {\n const encapsulationKeyPair = dependencies.identity.encapsulationKeyPair;\n const signingKeyPair = dependencies.identity.signingKeyPair;\n if (!encapsulationKeyPair || !signingKeyPair) {\n return null;\n }\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: dependencies.identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n },\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n );\n\n return {\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken ||\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: dependencies.api,\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
1
+ {"version":3,"file":"workflowRuntime.js","sourceRoot":"","sources":["work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AAE,YAAY,CAAC,sBAAsB;aAC5D,CAAC;QACJ,CAAC;QAED,OAAO;YACL,SAAS,EAAE,eAAe,EAAE;YAC5B,IAAI;YACJ,MAAM;YACN,KAAK;YACL,KAAK;YACL,IAAI;YACJ,0BAA0B;YAC1B,8BAA8B,EAAE,qBAAqB,EAAE;SACxD,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO;QACL,SAAS,CAAC,WAAW;YACnB,MAAM,EACJ,SAAS,EAAE,UAAU,EACrB,0BAA0B,EAAE,2BAA2B,EACvD,8BAA8B,EAAE,+BAA+B,EAC/D,IAAI,EAAE,YAAY,EAClB,GAAG,KAAK,EACT,GAAG,aAAa,CAAC,WAAW,CAAC,CAAC;YAC/B,QAAQ,GAAG,mBAAmB,CAAC,QAAQ,EAAE;gBACvC,mBAAmB,EAAE,YAAY,CAAC,mBAAmB;gBACrD,GAAG,EAAE,YAAY,CAAC,GAAG;gBACrB,QAAQ,EAAE,YAAY,CAAC,QAAQ;aAChC,CAAC,CAAC;YACH,OAAO,EAAE,GAAG,KAAK,EAAE,IAAI,EAAE,QAAQ,EAAE,CAAC;QACtC,CAAC;QACD,aAAa;KACd,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,mBAAmB,CAC1B,OAAsB,EACtB,IAAO;IAEP,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,IAAI,CAAC;IACd,CAAC;IACD,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QACpC,IAAI,OAAO,CAAC,GAAG,CAAC,OAAO,EAAE,GAAG,CAAC,KAAK,OAAO,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,EAAE,CAAC;YACzD,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { DocumentProjectorRegistry } from \"../data/documents/documentKinds\";\nimport type { DomainScope } from \"../data/domainScope\";\nimport { runWithSecurityIncidentReporting } from \"../data/keyingProjectionVerification/error\";\nimport type { PrincipalHistoryProtectionLease } from \"../data/principals/principalHistoryProtection\";\nimport type { SecurityIncidentReporter } from \"../data/securityIncidents\";\nimport { unavailableExecSql } from \"../data/sqlite/sqlSchema\";\nimport {\n createApiUserIdentitySource,\n createTrustedUserIdentityService,\n type LocalUserIdentityCandidate,\n type TrustedUserIdentityResolver,\n} from \"../data/trustedUserIdentity\";\nimport type { ContainerContentsRootAdopter } from \"../workflows/container-contents/runtime\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeGroups,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../workflows/runtimeInput\";\nimport type { Blobs } from \"./blobs\";\nimport type { Database } from \"./database\";\nimport type { Events } from \"./events\";\nimport type { Identity } from \"./identity\";\nimport { createListenerSet } from \"./listenerSet\";\nimport type { Network } from \"./network\";\nimport {\n createPrincipalHistoryProtectionCustody,\n type PrincipalHistoryKeyProvider,\n} from \"./principalHistoryProtection\";\nimport {\n createPrincipalMutationApiCustody,\n type PrincipalMutationApi,\n} from \"./principalMutationApi\";\nimport { adoptSessionRootContainer } from \"./rootContainerAdoption\";\nimport { acknowledgedSessionRoot } from \"./session/sessionRootAuthority\";\nimport type { Session, SessionSnapshot } from \"./session/sessionTypes\";\nimport type { SyncBillingGate } from \"./syncBillingGate\";\n\ntype HostWorkflowRuntimeUtilInput = Omit<\n WorkflowRuntimeUtilInput,\n \"reportSecurityIncident\"\n>;\n\nexport interface WorkflowRuntimeInput\n extends Omit<WorkflowRuntimeGroups, \"util\"> {\n readonly util: HostWorkflowRuntimeUtilInput;\n}\n\nexport type RuntimeListener = () => void;\n\nexport interface Runtime {\n readonly version: number;\n input(containerId?: string | null | undefined): WorkflowRuntimeInput;\n subscribe(listener: RuntimeListener): () => void;\n}\n\nexport interface InternalWorkflowRuntimeInput extends WorkflowRuntimeGroups {\n readonly apiClient: PrincipalMutationApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface InternalRuntime {\n retirePrincipalHistoryProtection(): void;\n readonly sessionGeneration: number;\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n readonly publicRuntime: Runtime;\n boundUserId(signingKeyFingerprint: string): Promise<string | null>;\n pinLocalUserIdentity(\n userId: string,\n candidate: LocalUserIdentityCandidate,\n ): Promise<void>;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\ninterface WorkflowRuntimeDependencies {\n api: ApiClient;\n blobs: Blobs;\n database: Database;\n documentProjectors: DocumentProjectorRegistry;\n events: Events;\n getDomainScope: () => DomainScope;\n identity: Identity;\n identityTrustDomain: string | null;\n log: (message: string) => void;\n logError: (message: string | Error, cause?: unknown) => void;\n network: Network;\n peerScope?: string | null;\n principalHistoryKeyProvider?: PrincipalHistoryKeyProvider | undefined;\n principalMutationTimeoutMs?: number | undefined;\n reportSecurityIncident: SecurityIncidentReporter;\n session: Session;\n syncBillingGate?: SyncBillingGate | undefined;\n}\n\nfunction createRuntimeMutationApi(\n dependencies: WorkflowRuntimeDependencies,\n readGeneration: () => number,\n) {\n return createPrincipalMutationApiCustody({\n api: dependencies.api,\n principalMutationTimeoutMs: dependencies.principalMutationTimeoutMs,\n readScope: () => {\n const { signingKeyPair, signingFingerprint } = dependencies.identity;\n const { userId, isAuthenticated } = dependencies.session;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !isAuthenticated ||\n !userId ||\n !signingKeyPair ||\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n database: dependencies.getDomainScope(),\n execSql: dependencies.database.requireExecSql(\"principal mutation\"),\n generation: readGeneration(),\n identityTrustDomain,\n signingFingerprint,\n signingKeyPair,\n userId,\n };\n },\n });\n}\n\nexport function createRuntime(\n dependencies: WorkflowRuntimeDependencies,\n): InternalRuntime {\n const trustedUserIdentityService = createTrustedUserIdentityService({\n getExecSql: () =>\n dependencies.database.status === \"ready\"\n ? dependencies.database.requireExecSql(\"trusted user identity\")\n : null,\n getLocalIdentity: () => {\n const encapsulationKeyPair = dependencies.identity.encapsulationKeyPair;\n const signingKeyPair = dependencies.identity.signingKeyPair;\n if (!encapsulationKeyPair || !signingKeyPair) {\n return null;\n }\n return {\n encapsulationPublicKey: encapsulationKeyPair.publicKey,\n signingKeyFingerprint: dependencies.identity.signingFingerprint,\n signingPublicKey: signingKeyPair.signingPublicKey,\n };\n },\n getLocalUserId: () => dependencies.session.userId,\n identityTrustDomain: dependencies.identityTrustDomain,\n remoteSource: createApiUserIdentitySource(dependencies.api),\n });\n const resolveTrustedUserIdentity: TrustedUserIdentityResolver = (userId) =>\n runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.resolve\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.resolve(userId),\n );\n const runtimeSubscription = createRuntimeSubscription(dependencies);\n const historyProtection = createPrincipalHistoryProtectionCustody({\n keyProvider: dependencies.principalHistoryKeyProvider,\n readScope: () => {\n const signingFingerprint = dependencies.identity.signingFingerprint;\n const identityTrustDomain = dependencies.identityTrustDomain;\n if (\n !signingFingerprint ||\n !identityTrustDomain ||\n dependencies.database.status !== \"ready\"\n )\n return null;\n return {\n signingFingerprint,\n identityTrustDomain,\n database: dependencies.getDomainScope(),\n generation: runtimeSubscription.recoveryGeneration,\n };\n },\n });\n const runtimeInput = createRuntimeInputFactory(\n dependencies,\n resolveTrustedUserIdentity,\n historyProtection.bind,\n createRuntimeMutationApi(\n dependencies,\n () => runtimeSubscription.mutationGeneration,\n ).bind,\n );\n\n return {\n retirePrincipalHistoryProtection: historyProtection.retire,\n get sessionGeneration() {\n return runtimeSubscription.sessionGeneration;\n },\n adoptRootContainer: (input) =>\n adoptSessionRootContainer(dependencies, input),\n boundUserId: (signingKeyFingerprint) =>\n trustedUserIdentityService.boundUserId(signingKeyFingerprint),\n async pinLocalUserIdentity(userId, candidate) {\n await runWithSecurityIncidentReporting(\n dependencies.reportSecurityIncident,\n {\n objectId: userId,\n objectKind: \"user\",\n operation: \"user.identity.pin_local\",\n organizationId: dependencies.session.organizationId,\n },\n () => trustedUserIdentityService.pinLocal(userId, candidate),\n );\n },\n publicRuntime: {\n get version() {\n return runtimeSubscription.version;\n },\n input: runtimeInput.hostInput,\n subscribe: runtimeSubscription.subscribe,\n },\n workflowInput: runtimeInput.workflowInput,\n };\n}\n\nfunction createRuntimeSubscription(dependencies: WorkflowRuntimeDependencies) {\n const listeners = createListenerSet();\n let version = 0;\n let sessionGeneration = 0;\n let recoveryGeneration = 0;\n let mutationGeneration = 0;\n let sessionSnapshot = dependencies.session.snapshot;\n const notifyListeners = () => {\n version += 1;\n listeners.notify();\n };\n\n const notifyAuthority = () => {\n recoveryGeneration += 1;\n mutationGeneration += 1;\n notifyListeners();\n };\n dependencies.database.subscribe(notifyAuthority);\n dependencies.events.subscribe(notifyListeners);\n dependencies.identity.subscribe(notifyAuthority);\n dependencies.network.subscribe(() => notifyListeners());\n dependencies.session.subscribe(() => {\n const next = dependencies.session.snapshot;\n if (sessionAuthorityChanged(sessionSnapshot, next)) {\n sessionGeneration += 1;\n recoveryGeneration += 1;\n }\n if (sessionScopeChanged(sessionSnapshot, next)) mutationGeneration += 1;\n sessionSnapshot = next;\n notifyListeners();\n });\n dependencies.syncBillingGate?.subscribe(notifyListeners);\n\n return {\n get mutationGeneration() {\n return mutationGeneration;\n },\n get recoveryGeneration() {\n return recoveryGeneration;\n },\n get sessionGeneration() {\n return sessionGeneration;\n },\n get version() {\n return version;\n },\n subscribe(listener: RuntimeListener): () => void {\n return listeners.subscribe(listener);\n },\n };\n}\n\ninterface RuntimeInputFactory {\n hostInput(containerId?: string | null | undefined): WorkflowRuntimeInput;\n workflowInput(\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput;\n}\n\nfunction sessionAuthInput({\n session,\n identity,\n}: WorkflowRuntimeDependencies): WorkflowRuntimeAuthInput {\n const signingFingerprint = identity.snapshot.signingFingerprint;\n return {\n defaultOrganizationId: session.defaultOrganizationId,\n rootContainerId: acknowledgedSessionRoot(session, signingFingerprint),\n isAuthenticated: session.isAuthenticated,\n isRoot: session.isRoot,\n organizationId: session.organizationId,\n userId: session.userId,\n };\n}\n\n/** Fields whose change invalidates work keyed on the session's authority. */\nfunction sessionAuthorityChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.authToken !== previous.authToken || sessionScopeChanged(previous, next)\n );\n}\n\n// A transport token renewal cannot turn a definite write refusal into saved work.\n// Journal custody still expires on every change to its identity or storage scope.\nfunction sessionScopeChanged(\n previous: SessionSnapshot,\n next: SessionSnapshot,\n): boolean {\n return (\n next.isAuthenticated !== previous.isAuthenticated ||\n next.isRoot !== previous.isRoot ||\n next.organizationId !== previous.organizationId ||\n next.userId !== previous.userId\n );\n}\n\nfunction createRuntimeInputFactory(\n dependencies: WorkflowRuntimeDependencies,\n resolveTrustedUserIdentity: TrustedUserIdentityResolver,\n bindHistoryProtection: () => PrincipalHistoryProtectionLease | undefined,\n bindMutationApi: () => PrincipalMutationApi,\n): RuntimeInputFactory {\n let auth: WorkflowRuntimeAuthInput | undefined;\n let crypto: WorkflowRuntimeCryptoInput | undefined;\n let infra: WorkflowRuntimeInfraInput | undefined;\n let state: WorkflowRuntimeStateInput | undefined;\n let util: WorkflowRuntimeUtilInput | undefined;\n let hostUtil: HostWorkflowRuntimeUtilInput | undefined;\n\n const workflowInput = (\n containerId?: string | null | undefined,\n ): InternalWorkflowRuntimeInput => {\n const dbStatus = dependencies.database.status;\n const execSql =\n dbStatus === \"ready\"\n ? dependencies.database.requireExecSql(\"tearleads.runtime.input\")\n : unavailableExecSql;\n const nextContainerId =\n (containerId === undefined\n ? dependencies.session.containerId\n : containerId) ?? null;\n\n auth = reuseIfShallowEqual(auth, sessionAuthInput(dependencies));\n crypto = reuseIfShallowEqual(crypto, {\n encapsulationKeyPair: dependencies.identity.encapsulationKeyPair,\n signingFingerprint: dependencies.identity.signingFingerprint,\n signingKeyPair: dependencies.identity.signingKeyPair,\n });\n infra = reuseIfShallowEqual(infra, {\n blobStore: dependencies.blobs.store,\n dbStatus,\n documentProjectors: dependencies.documentProjectors,\n // Runtime consumers branch on dbStatus before touching SQLite. The\n // fallback preserves the runtime shape and catches lifecycle bugs.\n execSql,\n });\n state = reuseIfShallowEqual(state, {\n containerId: nextContainerId,\n domainScope: dependencies.getDomainScope(),\n events: dependencies.events.events,\n // Resolved sync-online: workflows treat local-only mode exactly like being\n // offline (no server I/O), while `tearleads.network` stays the truthful\n // connectivity signal for host/UI. See Session.syncEnabled.\n online: dependencies.network.online && dependencies.session.syncEnabled,\n peerScope: dependencies.peerScope ?? null,\n serverEventsConnectionGeneration:\n dependencies.events.connectionGeneration,\n });\n if (\n !util ||\n util.log !== dependencies.log ||\n util.logError !== dependencies.logError ||\n util.reportSecurityIncident !== dependencies.reportSecurityIncident\n ) {\n util = {\n isRemoteSyncBlocked: (organizationId) =>\n dependencies.syncBillingGate?.isBlockedForOrganization(\n organizationId,\n ) ?? false,\n log: dependencies.log,\n logError: dependencies.logError,\n reportSecurityIncident: dependencies.reportSecurityIncident,\n };\n }\n\n return {\n apiClient: bindMutationApi(),\n auth,\n crypto,\n infra,\n state,\n util,\n resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: bindHistoryProtection(),\n };\n };\n\n return {\n hostInput(containerId) {\n const {\n apiClient: _apiClient,\n resolveTrustedUserIdentity: _resolveTrustedUserIdentity,\n withPrincipalHistoryProtection: _withPrincipalHistoryProtection,\n util: workflowUtil,\n ...input\n } = workflowInput(containerId);\n hostUtil = reuseIfShallowEqual(hostUtil, {\n isRemoteSyncBlocked: workflowUtil.isRemoteSyncBlocked,\n log: workflowUtil.log,\n logError: workflowUtil.logError,\n });\n return { ...input, util: hostUtil };\n },\n workflowInput,\n };\n}\n\n/**\n * Reuses the current runtime-input group when every field of the freshly\n * constructed `next` literal is reference-equal, so unchanged groups keep a\n * stable identity across runtime reads.\n */\nfunction reuseIfShallowEqual<T extends object>(\n current: T | undefined,\n next: T,\n): T {\n if (!current) {\n return next;\n }\n for (const key of Object.keys(next)) {\n if (Reflect.get(current, key) !== Reflect.get(next, key)) {\n return next;\n }\n }\n return current;\n}\n"]}
@@ -154,6 +154,8 @@ export interface DetachDocumentAttachmentInput {
154
154
  resolveProjectionUserKey: ProjectionUserKeyResolver;
155
155
  signedAt?: string | undefined;
156
156
  slotId: string;
157
+ stillCurrent?: (() => boolean) | undefined;
158
+ warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
157
159
  writerProjection?: DocumentWriterProjectionResponse | undefined;
158
160
  }
159
161
  export interface DetachDocumentAttachmentResult {
@@ -169,5 +171,7 @@ export interface DecryptDocumentAttachmentBlobInput {
169
171
  execSql: ExecSql;
170
172
  resolveProjectionUserKey: ProjectionUserKeyResolver;
171
173
  targetSecretKey: Uint8Array;
174
+ stillCurrent?: (() => boolean) | undefined;
175
+ warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
172
176
  writerProjection: DocumentWriterProjectionResponse;
173
177
  }