@tearleads/client-sdk 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (354) hide show
  1. package/client/Tearleads.d.ts +2 -0
  2. package/client/Tearleads.js +1 -0
  3. package/client/Tearleads.js.map +1 -1
  4. package/client/containerContents.js +2 -1
  5. package/client/containerContents.js.map +1 -1
  6. package/client/index.d.ts +1 -1
  7. package/client/index.js.map +1 -1
  8. package/client/organizations/index.d.ts +4 -42
  9. package/client/organizations/index.js +13 -0
  10. package/client/organizations/index.js.map +1 -1
  11. package/client/organizations/organizationGroupNameHydration.js +8 -1
  12. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  13. package/client/organizations/organizationsTypes.d.ts +47 -0
  14. package/client/organizations/organizationsTypes.js +2 -0
  15. package/client/organizations/organizationsTypes.js.map +1 -0
  16. package/client/organizations/principalMutationRecovery.d.ts +16 -0
  17. package/client/organizations/principalMutationRecovery.js +23 -0
  18. package/client/organizations/principalMutationRecovery.js.map +1 -0
  19. package/client/organizations/principalMutationScope.js +7 -2
  20. package/client/organizations/principalMutationScope.js.map +1 -1
  21. package/client/principalMutationApi.d.ts +24 -0
  22. package/client/principalMutationApi.js +108 -0
  23. package/client/principalMutationApi.js.map +1 -0
  24. package/client/principalMutationDeadline.js +23 -0
  25. package/client/principalMutationDeadline.js.map +1 -0
  26. package/client/workflowRuntime.d.ts +3 -1
  27. package/client/workflowRuntime.js +44 -5
  28. package/client/workflowRuntime.js.map +1 -1
  29. package/data/documents/blob/shared/types.d.ts +4 -0
  30. package/data/documents/blob/shared/types.js.map +1 -1
  31. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js +2 -0
  32. package/data/keyingProjectionVerification/accessManifestCheckpointEnforcement.js.map +1 -1
  33. package/data/keyingProjectionVerification/checkpointContext.d.ts +2 -1
  34. package/data/keyingProjectionVerification/checkpointContext.js +22 -0
  35. package/data/keyingProjectionVerification/checkpointContext.js.map +1 -1
  36. package/data/keyingProjectionVerification/containerDestinationVerification.js +11 -1
  37. package/data/keyingProjectionVerification/containerDestinationVerification.js.map +1 -1
  38. package/data/keyingProjectionVerification/containerManifestVerification.js.map +1 -1
  39. package/data/keyingProjectionVerification/containerPathVerification.js.map +1 -1
  40. package/data/keyingProjectionVerification/containerProjectionVerification.d.ts +3 -2
  41. package/data/keyingProjectionVerification/containerProjectionVerification.js +10 -11
  42. package/data/keyingProjectionVerification/containerProjectionVerification.js.map +1 -1
  43. package/data/keyingProjectionVerification/documentManifestPolicies.js.map +1 -1
  44. package/data/keyingProjectionVerification/documentManifestVerification.js.map +1 -1
  45. package/data/keyingProjectionVerification/documentProjectionVerification.d.ts +2 -3
  46. package/data/keyingProjectionVerification/documentProjectionVerification.js +4 -0
  47. package/data/keyingProjectionVerification/documentProjectionVerification.js.map +1 -1
  48. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js +14 -12
  49. package/data/keyingProjectionVerification/mergeProjectionPolicyEvidence.js.map +1 -1
  50. package/data/keyingProjectionVerification/organizationFounderBinding.js.map +1 -1
  51. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js +33 -6
  52. package/data/keyingProjectionVerification/projectionAuthorizationEvidence.js.map +1 -1
  53. package/data/keyingProjectionVerification/projectionLifetimes.js +13 -0
  54. package/data/keyingProjectionVerification/projectionLifetimes.js.map +1 -0
  55. package/data/keyingProjectionVerification/projectionPolicyEvidence.js +19 -66
  56. package/data/keyingProjectionVerification/projectionPolicyEvidence.js.map +1 -1
  57. package/data/keyingProjectionVerification/types.d.ts +13 -2
  58. package/data/keyingProjectionVerification/types.js +15 -0
  59. package/data/keyingProjectionVerification/types.js.map +1 -1
  60. package/data/persistence/keyingCheckpointAdvancePersistence.js +4 -1
  61. package/data/persistence/keyingCheckpointAdvancePersistence.js.map +1 -1
  62. package/data/persistence/organizationFounderPersistence.js +2 -2
  63. package/data/persistence/organizationFounderPersistence.js.map +1 -1
  64. package/data/persistence/principalAuthorizationCheckpoints.js +29 -0
  65. package/data/persistence/principalAuthorizationCheckpoints.js.map +1 -0
  66. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +27 -0
  67. package/data/persistence/principalCurrentAcknowledgementPersistence.js +109 -0
  68. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -0
  69. package/data/persistence/principalGrantRetirementPersistence.d.ts +3 -3
  70. package/data/persistence/principalGrantRetirementPersistence.js +4 -1
  71. package/data/persistence/principalGrantRetirementPersistence.js.map +1 -1
  72. package/data/persistence/principalHistoryEvidencePersistence.d.ts +30 -0
  73. package/data/persistence/principalHistoryPrefixPersistence.d.ts +24 -0
  74. package/data/persistence/principalHistoryPrefixPersistence.js +6 -2
  75. package/data/persistence/principalHistoryPrefixPersistence.js.map +1 -1
  76. package/data/persistence/principalHistoryStagePersistence.d.ts +21 -0
  77. package/data/persistence/principalKeyEnvelopeCandidates.js +12 -1
  78. package/data/persistence/principalKeyEnvelopeCandidates.js.map +1 -1
  79. package/data/persistence/principalMutationJournalPersistence.d.ts +19 -0
  80. package/data/persistence/principalMutationJournalPersistence.js +53 -0
  81. package/data/persistence/principalMutationJournalPersistence.js.map +1 -0
  82. package/data/persistence/verifiedPrincipalPolicyBundle.js +7 -51
  83. package/data/persistence/verifiedPrincipalPolicyBundle.js.map +1 -1
  84. package/data/persistence/verifiedPrincipalPolicyCurrent.js +56 -0
  85. package/data/persistence/verifiedPrincipalPolicyCurrent.js.map +1 -0
  86. package/data/principals/principalHistoryRuntime.js +12 -0
  87. package/data/principals/principalHistoryRuntime.js.map +1 -0
  88. package/data/principals/principalHistoryStageProtection.js +2 -12
  89. package/data/principals/principalHistoryStageProtection.js.map +1 -1
  90. package/data/principals/principalMutationJournal.d.ts +26 -0
  91. package/data/principals/principalMutationJournal.js +90 -0
  92. package/data/principals/principalMutationJournal.js.map +1 -0
  93. package/data/principals/principalMutationJournalRecord.d.ts +8 -0
  94. package/data/principals/principalMutationJournalRecord.js +25 -0
  95. package/data/principals/principalMutationJournalRecord.js.map +1 -0
  96. package/data/principals/principalPolicyEvidence.d.ts +2 -2
  97. package/data/principals/principalPolicyEvidence.js.map +1 -1
  98. package/data/sqlite/principalHistoryEvidenceSchema.d.ts +308 -0
  99. package/data/sqlite/principalHistoryStageSchema.d.ts +119 -0
  100. package/data/sqlite/principalHistoryStageSchema.js +3 -0
  101. package/data/sqlite/principalHistoryStageSchema.js.map +1 -1
  102. package/data/sqlite/principalMutationJournalSchema.d.ts +85 -0
  103. package/data/sqlite/principalMutationJournalSchema.js +13 -0
  104. package/data/sqlite/principalMutationJournalSchema.js.map +1 -0
  105. package/data/sqlite/schema.d.ts +83 -0
  106. package/data/sqlite/schema.js +3 -0
  107. package/data/sqlite/schema.js.map +1 -1
  108. package/index.d.ts +5 -5
  109. package/index.js +2 -2
  110. package/index.js.map +1 -1
  111. package/internal/api-client/ApiCache.d.ts +54 -0
  112. package/internal/api-client/ApiClient.d.ts +255 -309
  113. package/internal/api-client/ApiClient.js +15 -6
  114. package/internal/api-client/ApiClient.js.map +1 -1
  115. package/internal/api-client/index.d.ts +1 -0
  116. package/internal/api-client/index.js.map +1 -1
  117. package/internal/api-client/principalHistoryDeadline.js +20 -0
  118. package/internal/api-client/principalHistoryDeadline.js.map +1 -0
  119. package/internal/api-client/principalHistoryRequest.js +59 -22
  120. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  121. package/internal/api-client/principalHistoryRequestContext.js +18 -5
  122. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  123. package/internal/api-client/principalPolicyRequests.d.ts +799 -0
  124. package/internal/api-client/principalPolicyRequests.js +9 -4
  125. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  126. package/internal/api-client/projectionPolicyHistoryPages.d.ts +9 -0
  127. package/internal/api-client/projectionPolicyHistoryPages.js +88 -0
  128. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -0
  129. package/internal/api-client/writerProjectionRequests.js +26 -0
  130. package/internal/api-client/writerProjectionRequests.js.map +1 -0
  131. package/internal/crypto/index.d.ts +1 -1
  132. package/internal/crypto/index.js +1 -1
  133. package/internal/crypto/index.js.map +1 -1
  134. package/internal/crypto/keying/index.d.ts +2 -0
  135. package/internal/crypto/keying/index.js +2 -0
  136. package/internal/crypto/keying/index.js.map +1 -1
  137. package/internal/crypto/keying/principalPolicyCurrent.d.ts +1 -1
  138. package/internal/crypto/keying/principalPolicyCurrent.js +3 -3
  139. package/internal/crypto/keying/principalPolicyCurrent.js.map +1 -1
  140. package/internal/crypto/keying/principalPolicyCurrentEvidence.js +16 -0
  141. package/internal/crypto/keying/principalPolicyCurrentEvidence.js.map +1 -0
  142. package/internal/crypto/keying/principalPolicyCurrentMutation.d.ts +10 -0
  143. package/internal/crypto/keying/principalPolicyCurrentMutation.js +51 -0
  144. package/internal/crypto/keying/principalPolicyCurrentMutation.js.map +1 -0
  145. package/internal/crypto/keying/principalPolicyCurrentSuccessor.d.ts +10 -0
  146. package/internal/crypto/keying/principalPolicyCurrentSuccessor.js +60 -0
  147. package/internal/crypto/keying/principalPolicyCurrentSuccessor.js.map +1 -0
  148. package/internal/crypto/keying/principalPolicyHistory.js +8 -1
  149. package/internal/crypto/keying/principalPolicyHistory.js.map +1 -1
  150. package/internal/crypto/keying/principalPolicyHistoryReferences.js +1 -1
  151. package/internal/crypto/keying/principalPolicyHistoryReferences.js.map +1 -1
  152. package/internal/crypto/keying/principalPolicyHistoryTypes.d.ts +7 -2
  153. package/internal/crypto/keying/principalPolicyHistoryTypes.js +6 -3
  154. package/internal/crypto/keying/principalPolicyHistoryTypes.js.map +1 -1
  155. package/internal/crypto/projectionHistorySlots.js +0 -4
  156. package/internal/crypto/projectionHistorySlots.js.map +1 -1
  157. package/internal/validators/operation/index.d.ts +1 -0
  158. package/internal/validators/operation/index.js +1 -0
  159. package/internal/validators/operation/index.js.map +1 -1
  160. package/internal/validators/operation/principals.d.ts +38 -16
  161. package/internal/validators/operation/principals.js +11 -5
  162. package/internal/validators/operation/principals.js.map +1 -1
  163. package/internal/validators/operation/projectionPolicyHistory.d.ts +512 -0
  164. package/internal/validators/operation/projectionPolicyHistory.js +37 -0
  165. package/internal/validators/operation/projectionPolicyHistory.js.map +1 -0
  166. package/internal/validators/operation/registry.d.ts +2 -0
  167. package/internal/validators/operation/registry.js +2 -0
  168. package/internal/validators/operation/registry.js.map +1 -1
  169. package/internal/validators/operation/writerProjections.d.ts +178 -1224
  170. package/internal/validators/operation/writerProjections.js +9 -2
  171. package/internal/validators/operation/writerProjections.js.map +1 -1
  172. package/internal/validators/response/container.d.ts +84 -612
  173. package/internal/validators/response/documentMutation.d.ts +84 -612
  174. package/internal/validators/response/index.d.ts +1 -0
  175. package/internal/validators/response/index.js +1 -0
  176. package/internal/validators/response/index.js.map +1 -1
  177. package/internal/validators/response/organizationBilling.d.ts +1 -0
  178. package/internal/validators/response/organizationBilling.js +1 -1
  179. package/internal/validators/response/organizationBilling.js.map +1 -1
  180. package/internal/validators/response/principalHistoryPreparation.js +28 -1
  181. package/internal/validators/response/principalHistoryPreparation.js.map +1 -1
  182. package/internal/validators/response/principalPolicySnapshotPage.d.ts +388 -0
  183. package/internal/validators/response/principalPolicySnapshotPage.js +24 -0
  184. package/internal/validators/response/principalPolicySnapshotPage.js.map +1 -0
  185. package/internal/validators/response/projectionPolicyEvidence.d.ts +85 -613
  186. package/internal/validators/response/projectionPolicyEvidence.js +10 -5
  187. package/internal/validators/response/projectionPolicyEvidence.js.map +1 -1
  188. package/package.json +1 -1
  189. package/stores/documents/documentStore/attachmentHydration.js +3 -0
  190. package/stores/documents/documentStore/attachmentHydration.js.map +1 -1
  191. package/stores/documents/documentStore/syncDetachedAttachments.js +3 -0
  192. package/stores/documents/documentStore/syncDetachedAttachments.js.map +1 -1
  193. package/workflows/blobs/decrypt.d.ts +1 -1
  194. package/workflows/blobs/decrypt.js +3 -1
  195. package/workflows/blobs/decrypt.js.map +1 -1
  196. package/workflows/blobs/detach.js +6 -1
  197. package/workflows/blobs/detach.js.map +1 -1
  198. package/workflows/blobs/hydrate.d.ts +3 -1
  199. package/workflows/blobs/hydrate.js +2 -0
  200. package/workflows/blobs/hydrate.js.map +1 -1
  201. package/workflows/blobs/retainedAttachmentVerification.js +2 -0
  202. package/workflows/blobs/retainedAttachmentVerification.js.map +1 -1
  203. package/workflows/container-contents/container-state/createAdoption.js +2 -0
  204. package/workflows/container-contents/container-state/createAdoption.js.map +1 -1
  205. package/workflows/container-contents/container-state/createWithMetadata.js +7 -39
  206. package/workflows/container-contents/container-state/createWithMetadata.js.map +1 -1
  207. package/workflows/container-contents/container-state/createWithMetadataPlan.js +68 -0
  208. package/workflows/container-contents/container-state/createWithMetadataPlan.js.map +1 -0
  209. package/workflows/container-contents/remoteContainerState.js +3 -1
  210. package/workflows/container-contents/remoteContainerState.js.map +1 -1
  211. package/workflows/container-contents/remoteHydration/verifiedDestination.js +3 -0
  212. package/workflows/container-contents/remoteHydration/verifiedDestination.js.map +1 -1
  213. package/workflows/container-contents/runtime.d.ts +3 -0
  214. package/workflows/container-contents/runtime.js +7 -6
  215. package/workflows/container-contents/runtime.js.map +1 -1
  216. package/workflows/containers/child/share.js +4 -0
  217. package/workflows/containers/child/share.js.map +1 -1
  218. package/workflows/containers/child/sharePrincipalPolicy.d.ts +1 -0
  219. package/workflows/containers/child/sharePrincipalPolicy.js.map +1 -1
  220. package/workflows/documents/create.d.ts +2 -15
  221. package/workflows/documents/create.js +9 -64
  222. package/workflows/documents/create.js.map +1 -1
  223. package/workflows/documents/createProjection.d.ts +14 -0
  224. package/workflows/documents/createProjection.js +26 -0
  225. package/workflows/documents/createProjection.js.map +1 -0
  226. package/workflows/documents/createResponse.js +49 -0
  227. package/workflows/documents/createResponse.js.map +1 -0
  228. package/workflows/documents/linkSetBlobRewraps.js +2 -0
  229. package/workflows/documents/linkSetBlobRewraps.js.map +1 -1
  230. package/workflows/documents/runtime.d.ts +3 -0
  231. package/workflows/documents/runtime.js +3 -2
  232. package/workflows/documents/runtime.js.map +1 -1
  233. package/workflows/documents/syncFailureClassification.js +3 -1
  234. package/workflows/documents/syncFailureClassification.js.map +1 -1
  235. package/workflows/organizations/acknowledgedDirectoryBindings.js +18 -0
  236. package/workflows/organizations/acknowledgedDirectoryBindings.js.map +1 -0
  237. package/workflows/organizations/currentGroupMetadataAuthority.js +32 -0
  238. package/workflows/organizations/currentGroupMetadataAuthority.js.map +1 -0
  239. package/workflows/organizations/currentOrganizationAuthority.js +88 -0
  240. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -0
  241. package/workflows/organizations/currentOrganizationGroupNames.js +68 -0
  242. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -0
  243. package/workflows/organizations/currentPolicyMutationAcknowledgement.js +65 -0
  244. package/workflows/organizations/currentPolicyMutationAcknowledgement.js.map +1 -0
  245. package/workflows/organizations/deleteOrganizationGroup.js +1 -0
  246. package/workflows/organizations/deleteOrganizationGroup.js.map +1 -1
  247. package/workflows/organizations/groupCreation.js +1 -0
  248. package/workflows/organizations/groupCreation.js.map +1 -1
  249. package/workflows/organizations/groupMetadataAccess.d.ts +2 -2
  250. package/workflows/organizations/groupMetadataAccess.js +1 -1
  251. package/workflows/organizations/groupMetadataAccess.js.map +1 -1
  252. package/workflows/organizations/groupMetadataBinding.js.map +1 -1
  253. package/workflows/organizations/groupMetadataContainerAuthority.js +2 -47
  254. package/workflows/organizations/groupMetadataContainerAuthority.js.map +1 -1
  255. package/workflows/organizations/groupMetadataRootBinding.js +51 -0
  256. package/workflows/organizations/groupMetadataRootBinding.js.map +1 -0
  257. package/workflows/organizations/groupMetadataRuntime.js +20 -9
  258. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  259. package/workflows/organizations/groupMutationAuthorization.js.map +1 -1
  260. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +9 -75
  261. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  262. package/workflows/organizations/groupPolicyMutationContext.d.ts +5 -13
  263. package/workflows/organizations/groupPolicyMutationContext.js +1 -0
  264. package/workflows/organizations/groupPolicyMutationContext.js.map +1 -1
  265. package/workflows/organizations/groupPolicyMutationEvidence.d.ts +26 -0
  266. package/workflows/organizations/groupPolicyMutationEvidence.js +64 -0
  267. package/workflows/organizations/groupPolicyMutationEvidence.js.map +1 -0
  268. package/workflows/organizations/groupPolicyMutationHead.js.map +1 -1
  269. package/workflows/organizations/groupPolicyRequests.js +69 -63
  270. package/workflows/organizations/groupPolicyRequests.js.map +1 -1
  271. package/workflows/organizations/index.d.ts +6 -0
  272. package/workflows/organizations/index.js +5 -0
  273. package/workflows/organizations/index.js.map +1 -1
  274. package/workflows/organizations/organizationGroupNames.js +7 -0
  275. package/workflows/organizations/organizationGroupNames.js.map +1 -1
  276. package/workflows/organizations/principalCurrentPublicationSeal.js +51 -0
  277. package/workflows/organizations/principalCurrentPublicationSeal.js.map +1 -0
  278. package/workflows/organizations/principalMutationJournalLane.js +26 -0
  279. package/workflows/organizations/principalMutationJournalLane.js.map +1 -0
  280. package/workflows/organizations/principalMutationJournalManagement.d.ts +26 -0
  281. package/workflows/organizations/principalMutationJournalManagement.js +104 -0
  282. package/workflows/organizations/principalMutationJournalManagement.js.map +1 -0
  283. package/workflows/organizations/principalMutationJournalSession.d.ts +26 -0
  284. package/workflows/organizations/principalMutationJournalSession.js +85 -0
  285. package/workflows/organizations/principalMutationJournalSession.js.map +1 -0
  286. package/workflows/organizations/principalMutationReceipt.js +21 -0
  287. package/workflows/organizations/principalMutationReceipt.js.map +1 -0
  288. package/workflows/organizations/principalPolicyReceiptArtifacts.js +74 -0
  289. package/workflows/organizations/principalPolicyReceiptArtifacts.js.map +1 -0
  290. package/workflows/organizations/principalPolicyRequest.d.ts +5 -4
  291. package/workflows/organizations/principalPolicyRequest.js.map +1 -1
  292. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +21 -0
  293. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +155 -0
  294. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -0
  295. package/workflows/principals/index.d.ts +2 -0
  296. package/workflows/principals/index.js +1 -0
  297. package/workflows/principals/index.js.map +1 -1
  298. package/workflows/principals/policyVerification.js.map +1 -1
  299. package/workflows/principals/principalCurrentRecoveryBatch.js +14 -0
  300. package/workflows/principals/principalCurrentRecoveryBatch.js.map +1 -0
  301. package/workflows/principals/principalHistoryRecoveryAuthority.js +20 -0
  302. package/workflows/principals/principalHistoryRecoveryAuthority.js.map +1 -0
  303. package/workflows/principals/principalHistoryRecoveryStage.js +1 -1
  304. package/workflows/principals/principalHistoryRecoveryStage.js.map +1 -1
  305. package/workflows/principals/principalHistoryRecoveryTypes.d.ts +3 -3
  306. package/workflows/principals/principalHistoryRecoveryTypes.js.map +1 -1
  307. package/workflows/principals/principalHistoryRecoveryVerification.js +6 -1
  308. package/workflows/principals/principalHistoryRecoveryVerification.js.map +1 -1
  309. package/workflows/principals/principalRecoveryDirectory.d.ts +1 -1
  310. package/workflows/principals/principalRecoveryDirectory.js +29 -4
  311. package/workflows/principals/principalRecoveryDirectory.js.map +1 -1
  312. package/workflows/principals/principalRecoveryDiscoveryPage.js +36 -0
  313. package/workflows/principals/principalRecoveryDiscoveryPage.js.map +1 -0
  314. package/workflows/principals/principalRecoveryLocalPreference.js +28 -0
  315. package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -0
  316. package/workflows/principals/principalRecoveryMemo.d.ts +16 -0
  317. package/workflows/principals/principalRecoveryMemo.js +88 -16
  318. package/workflows/principals/principalRecoveryMemo.js.map +1 -1
  319. package/workflows/principals/principalRecoveryOutage.js +1 -1
  320. package/workflows/principals/principalRecoveryOutage.js.map +1 -1
  321. package/workflows/principals/publicPrincipalHistoryAuthority.js +60 -0
  322. package/workflows/principals/publicPrincipalHistoryAuthority.js.map +1 -0
  323. package/workflows/principals/publicPrincipalHistoryPage.js +87 -0
  324. package/workflows/principals/publicPrincipalHistoryPage.js.map +1 -0
  325. package/workflows/principals/publicPrincipalHistoryProgress.js +178 -0
  326. package/workflows/principals/publicPrincipalHistoryProgress.js.map +1 -0
  327. package/workflows/principals/publicPrincipalHistoryTypes.d.ts +39 -0
  328. package/workflows/principals/publicPrincipalHistoryTypes.js +2 -0
  329. package/workflows/principals/publicPrincipalHistoryTypes.js.map +1 -0
  330. package/workflows/principals/publicProjectionDirectory.js +40 -0
  331. package/workflows/principals/publicProjectionDirectory.js.map +1 -0
  332. package/workflows/principals/publicProjectionPrincipal.js +53 -0
  333. package/workflows/principals/publicProjectionPrincipal.js.map +1 -0
  334. package/workflows/principals/recoverCurrentOrganizationPolicy.js +33 -0
  335. package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +1 -0
  336. package/workflows/principals/recoverPrincipalPolicyHistory.js +4 -1
  337. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
  338. package/workflows/principals/recoverProjectionPolicyHistory.d.ts +9 -0
  339. package/workflows/principals/recoverProjectionPolicyHistory.js +98 -0
  340. package/workflows/principals/recoverProjectionPolicyHistory.js.map +1 -0
  341. package/workflows/principals/recoverPublicPrincipalHistory.js +176 -0
  342. package/workflows/principals/recoverPublicPrincipalHistory.js.map +1 -0
  343. package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +2 -1
  344. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +15 -20
  345. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  346. package/workflows/principals/runtimePolicyRecovery.js +16 -9
  347. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  348. package/workflows/principals/runtimePolicyWarmer.js +2 -0
  349. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
  350. package/workflows/principals/runtimeProjectionPolicyRecovery.js +56 -0
  351. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -0
  352. package/workflows/principals/selectPublicPrincipalHistory.js +90 -0
  353. package/workflows/principals/selectPublicPrincipalHistory.js.map +1 -0
  354. package/workflows/registration/provisioningBootstrapBuilders.d.ts +21 -153
@@ -1 +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AE,SAAS,CAAC,CAAC;IACrE,IAAI,CAAC,IAAI;QAAE,OAAO,KAAK,CAAC;IACxB,IAAI,CAAC;QACH,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;YAC3B,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,2DAA2D,CAC5D,CAAC;QACJ,CAAC;QACD,8BAA8B,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;QAC9C,OAAO,IAAI,CAAC;IACd,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,QAAQ,GAAG,MAAM,yCAAyC,CAC9D,KAAK,EACL,OAAO,CAAC,IAAI,CAAC,sBAAsB,EACnC;YACE,QAAQ,EAAE,SAAS,CAAC,EAAE;YACtB,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,0BAA0B;YACrC,cAAc,EAAE,SAAS,CAAC,cAAc;SACzC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ;YAAE,MAAM,KAAK,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport {\n type HeldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../data/containers/containerBinding\";\nimport { verifiedContainerCreateManifest } from \"../../../data/keyingProjectionVerification/containerCreateManifest\";\nimport { verifyContainerDestinationProjection } from \"../../../data/keyingProjectionVerification/containerDestinationVerification\";\nimport { verifyContainerWriterProjection } from \"../../../data/keyingProjectionVerification/containerProjectionVerification\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n runWithSecurityIncidentReporting,\n} from \"../../../data/keyingProjectionVerification/error\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport type { PrefetchedDestinationProjection } from \"./destinationPrefetch\";\nimport {\n cachedDestinationRole,\n type DestinationRole,\n rememberDestinationRole,\n} from \"./destinationRoleCache\";\nimport { resolveWithMetadataRootReload } from \"./destinationRootReload\";\nimport { assertPermittedDestinationBinding } from \"./replacementBinding\";\nimport type {\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationState,\n} from \"./types\";\n\n/** The identity a role is verified and cached under. */\ntype DestinationIdentity = Pick<RemoteContainer, \"id\" | \"organizationId\">;\n\nasync function destinationRoleFromPath(input: {\n listed: DestinationIdentity;\n path: readonly VerifiedContainerAccessManifest[];\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): Promise<{ role: DestinationRole; parentId: string | null }> {\n const { listed, path } = input;\n const head = path.at(-1);\n if (\n !head ||\n head.state.containerId !== listed.id ||\n head.state.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination manifest has the wrong identity\",\n );\n }\n const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: listed.organizationId,\n });\n if (\n head.state.systemSlot !== null &&\n path.length !== (head.state.systemSlot === metadataSlot ? 1 : 2)\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"system destination has the wrong signed topology\",\n );\n }\n // The head may be a later grant signed by any admin; only the epoch-1\n // create names the creator, and roots are always created by the org owner.\n const created = verifiedContainerCreateManifest({\n head,\n label: \"Container destination\",\n verifiedByHash: input.verifiedByHash,\n });\n const root = path[0];\n if (!root) throw new Error(\"Destination root is unavailable\");\n const rootCreated = verifiedContainerCreateManifest({\n head: root,\n label: \"Destination root\",\n verifiedByHash: input.verifiedByHash,\n });\n return {\n parentId: head.state.parentContainerId,\n role: {\n createSignerUserId: created.event.event.signerUserId,\n rootContainerId: rootCreated.state.containerId,\n rootCreateManifestHash: rootCreated.manifestHash,\n rootMetadataDocumentId: rootCreated.state.metadataDocumentId,\n metadataDocumentId: head.state.metadataDocumentId,\n ...(head.state.parentContainerId === null ||\n head.state.systemSlot !== null\n ? { parentId: head.state.parentContainerId }\n : {}),\n systemSlot: head.state.systemSlot,\n },\n };\n}\n\n/**\n * The session's root id arrives in an unsigned login response, so the root it\n * names must prove it belongs to this user: every acknowledged organization was\n * created by the session user, whose device signed the root's `container.create`.\n * A verified root created by anyone else is a substitution, never the merge\n * target for pre-login local content, whatever grants it carries. The check\n * runs on cache reuse too, since the cache is not scoped to the session user.\n */\nfunction assertRootCreatedBySessionUser(\n role: DestinationRole,\n runtime: RemoteContainerHydrationState[\"runtime\"],\n): void {\n if (role.systemSlot !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"acknowledged session root cannot be a system container\",\n );\n }\n if (role.createSignerUserId !== runtime.auth.userId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"acknowledged session root was not created by the session user\",\n );\n }\n}\n\nfunction assertAcknowledgedRootSigner(input: {\n listed: DestinationIdentity;\n role: DestinationRole;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): void {\n const { listed, role, runtime } = input;\n if (role.parentId !== null || listed.id !== runtime.auth.rootContainerId) {\n return;\n }\n assertRootCreatedBySessionUser(role, runtime);\n}\n\n/**\n * Authenticate destination roles before admitting a binding or advancing any\n * placement pin. Shared rehomes additionally require signed replacement evidence.\n */\nasync function verifyDestinationRole(input: {\n heldBinding: HeldContainerBinding | null;\n prefetched: PrefetchedDestinationProjection | undefined;\n verifyCurrentPlacement: boolean;\n onVerifiedCheckpoint:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n isCurrent?: (() => boolean) | undefined;\n listed: DestinationIdentity;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): Promise<{ role: DestinationRole; parentId: string | null } | null> {\n const { isCurrent, listed, runtime } = input;\n const projection = input.prefetched\n ? input.prefetched.projection\n : await runtime.apiClient.getContainerWriterProjection(listed.id);\n if (!projection || isCurrent?.() === false) return null;\n if (\n projection.containerId !== listed.id ||\n projection.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination projection has the wrong identity\",\n );\n }\n const verificationInput = {\n execSql: runtime.infra.execSql,\n projection,\n resolveUserKey: runtime.resolveTrustedUserIdentity,\n };\n const { path, verifiedByHash } =\n await verifyContainerDestinationProjection(verificationInput);\n if (isCurrent?.() === false) return null;\n const destination = await destinationRoleFromPath({\n listed,\n path,\n verifiedByHash,\n });\n const { role } = destination;\n // Refuse a rebinding before group checks or placement pins run for it.\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (role.parentId === null && role.systemSlot !== null) {\n const head = path.at(-1);\n if (!head) throw new Error(\"Metadata root manifest is unavailable\");\n await createGroupMetadataContainerVerifier({\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId: listed.organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent ?? (() => true),\n })(head.state);\n }\n if (isCurrent?.() === false) return null;\n if (input.verifyCurrentPlacement) {\n // Check the immutable role before allowing current placement to advance pins.\n assertAcknowledgedRootSigner({ listed, role, runtime });\n const currentPath = await verifyContainerWriterProjection({\n ...verificationInput,\n stillCurrent: isCurrent,\n });\n const currentHead = currentPath.at(-1);\n if (!currentHead)\n throw new Error(\"Recovery placement manifest is unavailable\");\n input.onVerifiedCheckpoint?.(currentHead.checkpoint);\n }\n if (isCurrent?.() === false) return null;\n return destination;\n}\n\ntype VerifyRemoteContainerDestinationInput = {\n heldBinding: HeldContainerBinding | null;\n /** The held folder was re-homed away from the listed organization. */\n supersededListing?: boolean | undefined;\n /** Fetched ahead by page hydration; ignored when placement is refreshed. */\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n refresh?: boolean;\n onVerifiedCheckpoint?:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n isCurrent?: (() => boolean) | undefined;\n};\n\n/** A cached immutable role, or a freshly verified one with its signed parent. */\nasync function resolveDestinationRole(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<{\n freshlyVerified: boolean;\n parentId: string | null | undefined;\n role: DestinationRole;\n} | null> {\n const { remoteContainer: listed, isCurrent } = input;\n const runtime = input.state.runtime;\n const cached = input.refresh\n ? undefined\n : cachedDestinationRole(runtime.infra.execSql, listed);\n // Ordinary parent edges are not immutable. A refresh authenticates current\n // placement; a forged root hint must also be corrected from a signed path.\n if (cached && !(cached.parentId === undefined && listed.parentId === null)) {\n return { freshlyVerified: false, parentId: cached.parentId, role: cached };\n }\n const verified = await verifyDestinationRole({\n heldBinding: input.heldBinding,\n prefetched: input.refresh ? undefined : input.prefetchedProjection,\n isCurrent,\n listed,\n runtime,\n verifyCurrentPlacement: input.refresh === true,\n onVerifiedCheckpoint: input.onVerifiedCheckpoint,\n });\n if (!verified) return null;\n return {\n freshlyVerified: true,\n parentId:\n input.refresh || listed.parentId === null\n ? verified.parentId\n : verified.role.parentId,\n role: verified.role,\n };\n}\n\n/**\n * Listing hints never establish a metadata target or a system/root role, and a\n * held folder keeps its organization and metadata target unless its own user\n * re-created it or its pinned founder authorized a verified replacement.\n * A conflicting proof is refused before placement pins\n * advance or its role is cached.\n */\nexport async function verifyRemoteContainerDestination(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<RemoteContainer | null> {\n const { remoteContainer: listed, state, isCurrent } = input;\n const runtime = state.runtime;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: listed.id,\n objectKind: \"container\",\n operation: \"container.destination.verify\",\n organizationId: listed.organizationId,\n },\n async () => {\n if (input.supersededListing) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from the listed organization\",\n );\n }\n // A held ordinary binding was verified (or signed by this device) when\n // it was stored; a listing that repeats it needs no second proof.\n if (\n !input.refresh &&\n listingRepeatsHeldOrdinaryBinding(input.heldBinding, listed)\n ) {\n return { ...listed, systemSlot: null };\n }\n if (input.refresh)\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n // A metadata root read before a reserved-group commit is reloaded once.\n const resolved = await resolveWithMetadataRootReload(\n input,\n resolveDestinationRole,\n () => runtime.apiClient.evictContainerWriterProjection(listed.id),\n ).catch((error: unknown) => {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error))\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n throw error;\n });\n if (!resolved || isCurrent?.() === false) return null;\n const { role, parentId } = resolved;\n // Fresh verification checked this binding before any placement pins.\n // A cached role still needs the held binding and replacement proof checked.\n if (!resolved.freshlyVerified)\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (resolved.freshlyVerified)\n rememberDestinationRole(runtime.infra.execSql, listed, role);\n assertAcknowledgedRootSigner({ listed, role, runtime });\n return {\n ...listed,\n metadataDocumentId: role.metadataDocumentId,\n parentId: parentId === undefined ? listed.parentId : parentId,\n systemSlot: role.systemSlot,\n };\n },\n );\n}\n\n/** The root the unsigned login answer named, in the expected organization. */\nexport function isSessionRootState(\n remoteRootState: ContainerState,\n state: RemoteContainerHydrationState,\n): boolean {\n const { container } = remoteRootState;\n const { auth } = state.runtime;\n return (\n container.parentId === null &&\n !container.systemSlot &&\n container.id === auth.rootContainerId &&\n container.organizationId === auth.organizationId\n );\n}\n\n/**\n * Whether the session root may absorb the pre-login local roots. The unsigned\n * login answer only names the root; the merge target must also be the verified\n * root whose epoch-1 `container.create` the session user signed. A row persisted\n * earlier as an ordinary shared container (another user's root this device once\n * hydrated) never passed that check for this session, so the creator is checked\n * here, at the reconciliation boundary itself, before any local content is\n * re-parented. The role comes only from the cache remote hydration fills when\n * it verifies the destination: this gate never fetches, so a local refresh stays\n * independent of the network. Without a cached role the merge is left pending\n * (no incident) until hydration verifies the root and reconciles from the\n * cache. A different creator is a `signer_mismatch` incident and never a merge;\n * the refusal is the \"no merge\" outcome, so the refresh that carried it\n * completes with the local content left in place.\n */\nexport async function isVerifiedLocalRootReconciliationTarget(input: {\n remoteRootState: ContainerState;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const { remoteRootState, state } = input;\n const { container } = remoteRootState;\n const runtime = state.runtime;\n if (!isSessionRootState(remoteRootState, state)) return false;\n const role = cachedDestinationRole(runtime.infra.execSql, container);\n if (!role) return false;\n try {\n if (role.parentId !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"session root reconciliation target is not a verified root\",\n );\n }\n assertRootCreatedBySessionUser(role, runtime);\n return true;\n } catch (error) {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: container.id,\n objectKind: \"container\",\n operation: \"container.root.reconcile\",\n organizationId: container.organizationId,\n },\n );\n if (!reported) throw error;\n return false;\n }\n}\n"]}
1
+ {"version":3,"file":"verifiedDestination.js","sourceRoot":"","sources":["verifiedDestination.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6CAA6C,EAAE,MAAM,2CAA2C,CAAC;AAC1G,OAAO,EAEL,iCAAiC,GAClC,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,+BAA+B,EAAE,MAAM,oEAAoE,CAAC;AACrH,OAAO,EAAE,oCAAoC,EAAE,MAAM,6EAA6E,CAAC;AACnI,OAAO,EAAE,+BAA+B,EAAE,MAAM,4EAA4E,CAAC;AAC7H,OAAO,EACL,yBAAyB,EACzB,yCAAyC,EACzC,gCAAgC,GACjC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,oCAAoC,EAAE,MAAM,qDAAqD,CAAC;AAC3G,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAE1F,OAAO,EAC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B,UAAU,EAAE,WAAW;YACvB,SAAS,EAAE,0BAA0B;YACrC,cAAc,EAAE,SAAS,CAAC,cAAc;SACzC,CACF,CAAC;QACF,IAAI,CAAC,QAAQ;YAAE,MAAM,KAAK,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { deriveOrganizationMetadataContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport {\n type HeldContainerBinding,\n listingRepeatsHeldOrdinaryBinding,\n} from \"../../../data/containers/containerBinding\";\nimport { verifiedContainerCreateManifest } from \"../../../data/keyingProjectionVerification/containerCreateManifest\";\nimport { verifyContainerDestinationProjection } from \"../../../data/keyingProjectionVerification/containerDestinationVerification\";\nimport { verifyContainerWriterProjection } from \"../../../data/keyingProjectionVerification/containerProjectionVerification\";\nimport {\n isKeyingVerificationError,\n reportKeyingVerificationErrorInCauseChain,\n runWithSecurityIncidentReporting,\n} from \"../../../data/keyingProjectionVerification/error\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport type { PrefetchedDestinationProjection } from \"./destinationPrefetch\";\nimport {\n cachedDestinationRole,\n type DestinationRole,\n rememberDestinationRole,\n} from \"./destinationRoleCache\";\nimport { resolveWithMetadataRootReload } from \"./destinationRootReload\";\nimport { assertPermittedDestinationBinding } from \"./replacementBinding\";\nimport type {\n ContainerState,\n RemoteContainer,\n RemoteContainerHydrationState,\n} from \"./types\";\n\n/** The identity a role is verified and cached under. */\ntype DestinationIdentity = Pick<RemoteContainer, \"id\" | \"organizationId\">;\n\nasync function destinationRoleFromPath(input: {\n listed: DestinationIdentity;\n path: readonly VerifiedContainerAccessManifest[];\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): Promise<{ role: DestinationRole; parentId: string | null }> {\n const { listed, path } = input;\n const head = path.at(-1);\n if (\n !head ||\n head.state.containerId !== listed.id ||\n head.state.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination manifest has the wrong identity\",\n );\n }\n const metadataSlot = await deriveOrganizationMetadataContainerSystemSlot({\n organizationId: listed.organizationId,\n });\n if (\n head.state.systemSlot !== null &&\n path.length !== (head.state.systemSlot === metadataSlot ? 1 : 2)\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"system destination has the wrong signed topology\",\n );\n }\n // The head may be a later grant signed by any admin; only the epoch-1\n // create names the creator, and roots are always created by the org owner.\n const created = verifiedContainerCreateManifest({\n head,\n label: \"Container destination\",\n verifiedByHash: input.verifiedByHash,\n });\n const root = path[0];\n if (!root) throw new Error(\"Destination root is unavailable\");\n const rootCreated = verifiedContainerCreateManifest({\n head: root,\n label: \"Destination root\",\n verifiedByHash: input.verifiedByHash,\n });\n return {\n parentId: head.state.parentContainerId,\n role: {\n createSignerUserId: created.event.event.signerUserId,\n rootContainerId: rootCreated.state.containerId,\n rootCreateManifestHash: rootCreated.manifestHash,\n rootMetadataDocumentId: rootCreated.state.metadataDocumentId,\n metadataDocumentId: head.state.metadataDocumentId,\n ...(head.state.parentContainerId === null ||\n head.state.systemSlot !== null\n ? { parentId: head.state.parentContainerId }\n : {}),\n systemSlot: head.state.systemSlot,\n },\n };\n}\n\n/**\n * The session's root id arrives in an unsigned login response, so the root it\n * names must prove it belongs to this user: every acknowledged organization was\n * created by the session user, whose device signed the root's `container.create`.\n * A verified root created by anyone else is a substitution, never the merge\n * target for pre-login local content, whatever grants it carries. The check\n * runs on cache reuse too, since the cache is not scoped to the session user.\n */\nfunction assertRootCreatedBySessionUser(\n role: DestinationRole,\n runtime: RemoteContainerHydrationState[\"runtime\"],\n): void {\n if (role.systemSlot !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"acknowledged session root cannot be a system container\",\n );\n }\n if (role.createSignerUserId !== runtime.auth.userId) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"acknowledged session root was not created by the session user\",\n );\n }\n}\n\nfunction assertAcknowledgedRootSigner(input: {\n listed: DestinationIdentity;\n role: DestinationRole;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): void {\n const { listed, role, runtime } = input;\n if (role.parentId !== null || listed.id !== runtime.auth.rootContainerId) {\n return;\n }\n assertRootCreatedBySessionUser(role, runtime);\n}\n\n/**\n * Authenticate destination roles before admitting a binding or advancing any\n * placement pin. Shared rehomes additionally require signed replacement evidence.\n */\nasync function verifyDestinationRole(input: {\n heldBinding: HeldContainerBinding | null;\n prefetched: PrefetchedDestinationProjection | undefined;\n verifyCurrentPlacement: boolean;\n onVerifiedCheckpoint:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n isCurrent?: (() => boolean) | undefined;\n listed: DestinationIdentity;\n runtime: RemoteContainerHydrationState[\"runtime\"];\n}): Promise<{ role: DestinationRole; parentId: string | null } | null> {\n const { isCurrent, listed, runtime } = input;\n const projection = input.prefetched\n ? input.prefetched.projection\n : await runtime.apiClient.getContainerWriterProjection(listed.id);\n if (!projection || isCurrent?.() === false) return null;\n if (\n projection.containerId !== listed.id ||\n projection.organizationId !== listed.organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container destination projection has the wrong identity\",\n );\n }\n const verificationInput = {\n execSql: runtime.infra.execSql,\n projection,\n resolveUserKey: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent,\n warmReferencedPrincipalPolicies:\n createRuntimePrincipalPolicyWarmer(runtime),\n };\n const { path, verifiedByHash } =\n await verifyContainerDestinationProjection(verificationInput);\n if (isCurrent?.() === false) return null;\n const destination = await destinationRoleFromPath({\n listed,\n path,\n verifiedByHash,\n });\n const { role } = destination;\n // Refuse a rebinding before group checks or placement pins run for it.\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (role.parentId === null && role.systemSlot !== null) {\n const head = path.at(-1);\n if (!head) throw new Error(\"Metadata root manifest is unavailable\");\n await createGroupMetadataContainerVerifier({\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId: listed.organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: isCurrent ?? (() => true),\n })(head.state);\n }\n if (isCurrent?.() === false) return null;\n if (input.verifyCurrentPlacement) {\n // Check the immutable role before allowing current placement to advance pins.\n assertAcknowledgedRootSigner({ listed, role, runtime });\n const currentPath = await verifyContainerWriterProjection({\n ...verificationInput,\n stillCurrent: isCurrent,\n });\n const currentHead = currentPath.at(-1);\n if (!currentHead)\n throw new Error(\"Recovery placement manifest is unavailable\");\n input.onVerifiedCheckpoint?.(currentHead.checkpoint);\n }\n if (isCurrent?.() === false) return null;\n return destination;\n}\n\ntype VerifyRemoteContainerDestinationInput = {\n heldBinding: HeldContainerBinding | null;\n /** The held folder was re-homed away from the listed organization. */\n supersededListing?: boolean | undefined;\n /** Fetched ahead by page hydration; ignored when placement is refreshed. */\n prefetchedProjection?: PrefetchedDestinationProjection | undefined;\n refresh?: boolean;\n onVerifiedCheckpoint?:\n | ((checkpoint: AccessManifestCheckpoint) => void)\n | undefined;\n remoteContainer: RemoteContainer;\n state: RemoteContainerHydrationState;\n isCurrent?: (() => boolean) | undefined;\n};\n\n/** A cached immutable role, or a freshly verified one with its signed parent. */\nasync function resolveDestinationRole(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<{\n freshlyVerified: boolean;\n parentId: string | null | undefined;\n role: DestinationRole;\n} | null> {\n const { remoteContainer: listed, isCurrent } = input;\n const runtime = input.state.runtime;\n const cached = input.refresh\n ? undefined\n : cachedDestinationRole(runtime.infra.execSql, listed);\n // Ordinary parent edges are not immutable. A refresh authenticates current\n // placement; a forged root hint must also be corrected from a signed path.\n if (cached && !(cached.parentId === undefined && listed.parentId === null)) {\n return { freshlyVerified: false, parentId: cached.parentId, role: cached };\n }\n const verified = await verifyDestinationRole({\n heldBinding: input.heldBinding,\n prefetched: input.refresh ? undefined : input.prefetchedProjection,\n isCurrent,\n listed,\n runtime,\n verifyCurrentPlacement: input.refresh === true,\n onVerifiedCheckpoint: input.onVerifiedCheckpoint,\n });\n if (!verified) return null;\n return {\n freshlyVerified: true,\n parentId:\n input.refresh || listed.parentId === null\n ? verified.parentId\n : verified.role.parentId,\n role: verified.role,\n };\n}\n\n/**\n * Listing hints never establish a metadata target or a system/root role, and a\n * held folder keeps its organization and metadata target unless its own user\n * re-created it or its pinned founder authorized a verified replacement.\n * A conflicting proof is refused before placement pins\n * advance or its role is cached.\n */\nexport async function verifyRemoteContainerDestination(\n input: VerifyRemoteContainerDestinationInput,\n): Promise<RemoteContainer | null> {\n const { remoteContainer: listed, state, isCurrent } = input;\n const runtime = state.runtime;\n return runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: listed.id,\n objectKind: \"container\",\n operation: \"container.destination.verify\",\n organizationId: listed.organizationId,\n },\n async () => {\n if (input.supersededListing) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"container was re-homed away from the listed organization\",\n );\n }\n // A held ordinary binding was verified (or signed by this device) when\n // it was stored; a listing that repeats it needs no second proof.\n if (\n !input.refresh &&\n listingRepeatsHeldOrdinaryBinding(input.heldBinding, listed)\n ) {\n return { ...listed, systemSlot: null };\n }\n if (input.refresh)\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n // A metadata root read before a reserved-group commit is reloaded once.\n const resolved = await resolveWithMetadataRootReload(\n input,\n resolveDestinationRole,\n () => runtime.apiClient.evictContainerWriterProjection(listed.id),\n ).catch((error: unknown) => {\n // Never re-serve a cached projection that failed verification.\n if (isKeyingVerificationError(error))\n runtime.apiClient.evictContainerWriterProjection(listed.id);\n throw error;\n });\n if (!resolved || isCurrent?.() === false) return null;\n const { role, parentId } = resolved;\n // Fresh verification checked this binding before any placement pins.\n // A cached role still needs the held binding and replacement proof checked.\n if (!resolved.freshlyVerified)\n await assertPermittedDestinationBinding({\n stillCurrent: isCurrent,\n heldBinding: input.heldBinding,\n listed,\n role,\n runtime,\n });\n if (isCurrent?.() === false) return null;\n if (resolved.freshlyVerified)\n rememberDestinationRole(runtime.infra.execSql, listed, role);\n assertAcknowledgedRootSigner({ listed, role, runtime });\n return {\n ...listed,\n metadataDocumentId: role.metadataDocumentId,\n parentId: parentId === undefined ? listed.parentId : parentId,\n systemSlot: role.systemSlot,\n };\n },\n );\n}\n\n/** The root the unsigned login answer named, in the expected organization. */\nexport function isSessionRootState(\n remoteRootState: ContainerState,\n state: RemoteContainerHydrationState,\n): boolean {\n const { container } = remoteRootState;\n const { auth } = state.runtime;\n return (\n container.parentId === null &&\n !container.systemSlot &&\n container.id === auth.rootContainerId &&\n container.organizationId === auth.organizationId\n );\n}\n\n/**\n * Whether the session root may absorb the pre-login local roots. The unsigned\n * login answer only names the root; the merge target must also be the verified\n * root whose epoch-1 `container.create` the session user signed. A row persisted\n * earlier as an ordinary shared container (another user's root this device once\n * hydrated) never passed that check for this session, so the creator is checked\n * here, at the reconciliation boundary itself, before any local content is\n * re-parented. The role comes only from the cache remote hydration fills when\n * it verifies the destination: this gate never fetches, so a local refresh stays\n * independent of the network. Without a cached role the merge is left pending\n * (no incident) until hydration verifies the root and reconciles from the\n * cache. A different creator is a `signer_mismatch` incident and never a merge;\n * the refusal is the \"no merge\" outcome, so the refresh that carried it\n * completes with the local content left in place.\n */\nexport async function isVerifiedLocalRootReconciliationTarget(input: {\n remoteRootState: ContainerState;\n state: RemoteContainerHydrationState;\n}): Promise<boolean> {\n const { remoteRootState, state } = input;\n const { container } = remoteRootState;\n const runtime = state.runtime;\n if (!isSessionRootState(remoteRootState, state)) return false;\n const role = cachedDestinationRole(runtime.infra.execSql, container);\n if (!role) return false;\n try {\n if (role.parentId !== null) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"session root reconciliation target is not a verified root\",\n );\n }\n assertRootCreatedBySessionUser(role, runtime);\n return true;\n } catch (error) {\n const reported = await reportKeyingVerificationErrorInCauseChain(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: container.id,\n objectKind: \"container\",\n operation: \"container.root.reconcile\",\n organizationId: container.organizationId,\n },\n );\n if (!reported) throw error;\n return false;\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import type { ApiClient } from "../../internal/api-client/index.js";
2
2
  import { type DocumentProjectorRegistryInput } from "../../data/documents/documentKinds.js";
3
+ import type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
3
4
  import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
4
5
  import { type TrustedUserIdentityResolver } from "../../data/trustedUserIdentity/index.js";
5
6
  import { createDocumentsWorkflowRuntime, type DocumentsWorkflowRuntime } from "../documents/index.js";
@@ -44,6 +45,8 @@ export interface ContainerContentsWorkflowRuntimeInputGroups {
44
45
  readonly util: ContainerContentsWorkflowRuntimeUtil;
45
46
  }
46
47
  export interface ContainerContentsWorkflowRuntimeInput extends ContainerContentsWorkflowRuntimeInputGroups {
48
+ /** Private host custody, inherited by container and derived document runtimes. */
49
+ readonly withPrincipalHistoryProtection?: PrincipalHistoryProtectionLease | undefined;
47
50
  readonly apiClient: ContainerContentsWorkflowApi;
48
51
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
49
52
  }
@@ -1,8 +1,9 @@
1
1
  import { resolveDocumentProjectorRegistry, } from "../../data/documents/documentKinds.js";
2
+ import { inheritPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
2
3
  import { requireTrustedUserIdentityResolver, } from "../../data/trustedUserIdentity/index.js";
3
4
  import { createDocumentsWorkflowRuntime, } from "../documents/index.js";
4
5
  function documentsRuntimeInput(runtime, containerId) {
5
- return {
6
+ return inheritPrincipalHistoryProtection(runtime, {
6
7
  apiClient: runtime.apiClient,
7
8
  auth: runtime.auth,
8
9
  crypto: runtime.crypto,
@@ -10,7 +11,7 @@ function documentsRuntimeInput(runtime, containerId) {
10
11
  resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,
11
12
  state: { ...runtime.state, containerId },
12
13
  util: runtime.util,
13
- };
14
+ });
14
15
  }
15
16
  export function createContainerContentsDocumentsRuntime(runtime, containerId) {
16
17
  return createDocumentsWorkflowRuntime(documentsRuntimeInput(runtime, containerId));
@@ -21,7 +22,7 @@ function createContainerContentsWorkflowRuntimeWithRootAdopter(input, adoptRootC
21
22
  ...input.infra,
22
23
  documentProjectors,
23
24
  };
24
- return {
25
+ return inheritPrincipalHistoryProtection(input, {
25
26
  ...(adoptRootContainer ? { adoptRootContainer } : {}),
26
27
  apiClient: input.apiClient,
27
28
  auth: input.auth,
@@ -30,16 +31,16 @@ function createContainerContentsWorkflowRuntimeWithRootAdopter(input, adoptRootC
30
31
  resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(input.resolveTrustedUserIdentity),
31
32
  state: input.state,
32
33
  util: input.util,
33
- };
34
+ });
34
35
  }
35
36
  export function createContainerContentsWorkflowRuntime(input) {
36
37
  return createContainerContentsWorkflowRuntimeWithRootAdopter(input);
37
38
  }
38
39
  /** Internal store runtime with the session-root adoption capability wired. */
39
40
  export function createContainerContentsStoreWorkflowRuntime(input, adoptRootContainer) {
40
- return {
41
+ return inheritPrincipalHistoryProtection(input, {
41
42
  ...createContainerContentsWorkflowRuntimeWithRootAdopter(input, adoptRootContainer),
42
43
  adoptRootContainer,
43
- };
44
+ });
44
45
  }
45
46
  //# sourceMappingURL=runtime.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,gCAAgC,GACjC,MAAM,oCAAoC,CAAC;AAE5C,OAAO,EACL,kCAAkC,GAEnC,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,8BAA8B,G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,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,2CAA2C,CACzD,KAA4C,EAC5C,kBAAgD;IAEhD,OAAO;QACL,GAAG,qDAAqD,CACtD,KAAK,EACL,kBAAkB,CACnB;QACD,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../data/documents/documentKinds\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport {\n createDocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntime,\n} from \"../documents\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../runtimeInput\";\n\ntype DocumentsWorkflowRuntimeInput = Parameters<\n typeof createDocumentsWorkflowRuntime\n>[0];\n\ntype ContainerContentsWorkflowApi = ApiClient &\n DocumentsWorkflowRuntimeInput[\"apiClient\"];\n\nexport interface ContainerContentsWorkflowRuntimeAuth\n extends WorkflowRuntimeAuthInput {}\n\nexport interface ContainerContentsWorkflowRuntimeCrypto\n extends WorkflowRuntimeCryptoInput {}\n\nexport interface ContainerContentsWorkflowRuntimeInfra\n extends Omit<WorkflowRuntimeInfraInput, \"dbStatus\"> {\n readonly dbStatus: string;\n}\n\ninterface ContainerContentsWorkflowRuntimeInputInfra\n extends Omit<ContainerContentsWorkflowRuntimeInfra, \"documentProjectors\"> {\n readonly documentProjectors: DocumentProjectorRegistryInput;\n}\n\nexport interface ContainerContentsWorkflowRuntimeState\n extends WorkflowRuntimeStateInput {}\n\nexport interface ContainerContentsWorkflowRuntimeUtil\n extends Omit<WorkflowRuntimeUtilInput, \"logError\"> {\n // Store recovery is best-effort, so hosts may retain the causal error without\n // making structured error logging mandatory for general workflow runtimes.\n readonly logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n}\n\nexport interface ContainerContentsRootAdoptionInput {\n readonly domainScope: ContainerContentsWorkflowRuntimeState[\"domainScope\"];\n readonly expectedContainerId: string;\n readonly nextContainerId: string;\n readonly organizationId: string;\n readonly userId: string;\n}\n\nexport type ContainerContentsRootAdopter = (\n input: ContainerContentsRootAdoptionInput,\n) => boolean | \"already-adopted\";\n\nexport interface ContainerContentsWorkflowRuntimeGroups {\n readonly auth: ContainerContentsWorkflowRuntimeAuth;\n readonly crypto: ContainerContentsWorkflowRuntimeCrypto;\n readonly infra: ContainerContentsWorkflowRuntimeInfra;\n readonly state: ContainerContentsWorkflowRuntimeState;\n readonly util: ContainerContentsWorkflowRuntimeUtil;\n}\n\nexport interface ContainerContentsWorkflowRuntimeInputGroups {\n readonly auth: ContainerContentsWorkflowRuntimeAuth;\n readonly crypto: ContainerContentsWorkflowRuntimeCrypto;\n readonly infra: ContainerContentsWorkflowRuntimeInputInfra;\n readonly state: ContainerContentsWorkflowRuntimeState;\n readonly util: ContainerContentsWorkflowRuntimeUtil;\n}\n\nexport interface ContainerContentsWorkflowRuntimeInput\n extends ContainerContentsWorkflowRuntimeInputGroups {\n readonly apiClient: ContainerContentsWorkflowApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface ContainerContentsWorkflowRuntime\n extends ContainerContentsWorkflowRuntimeGroups,\n Pick<ContainerContentsWorkflowRuntimeInput, \"apiClient\"> {\n readonly adoptRootContainer?: ContainerContentsRootAdopter | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface ContainerContentsStoreWorkflowRuntime\n extends ContainerContentsWorkflowRuntime {\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n}\n\nexport interface ContainerContentsWorkflowSqlRuntime {\n readonly auth?: {\n readonly organizationId?: string | null | undefined;\n };\n readonly infra: {\n readonly execSql: ExecSql;\n };\n}\n\nfunction documentsRuntimeInput(\n runtime: ContainerContentsWorkflowRuntime,\n containerId: string | null,\n): DocumentsWorkflowRuntimeInput {\n return {\n apiClient: runtime.apiClient,\n auth: runtime.auth,\n crypto: runtime.crypto,\n infra: runtime.infra,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n state: { ...runtime.state, containerId },\n util: runtime.util,\n };\n}\n\nexport function createContainerContentsDocumentsRuntime(\n runtime: ContainerContentsWorkflowRuntime,\n containerId: string | null,\n): DocumentsWorkflowRuntime {\n return createDocumentsWorkflowRuntime(\n documentsRuntimeInput(runtime, containerId),\n );\n}\n\nfunction createContainerContentsWorkflowRuntimeWithRootAdopter(\n input: ContainerContentsWorkflowRuntimeInput,\n adoptRootContainer?: ContainerContentsRootAdopter | undefined,\n): ContainerContentsWorkflowRuntime {\n const documentProjectors = resolveDocumentProjectorRegistry(\n input.infra.documentProjectors,\n );\n const infra = {\n ...input.infra,\n documentProjectors,\n };\n\n return {\n ...(adoptRootContainer ? { adoptRootContainer } : {}),\n apiClient: input.apiClient,\n auth: input.auth,\n crypto: input.crypto,\n infra,\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n state: input.state,\n util: input.util,\n };\n}\n\nexport function createContainerContentsWorkflowRuntime(\n input: ContainerContentsWorkflowRuntimeInput,\n): ContainerContentsWorkflowRuntime {\n return createContainerContentsWorkflowRuntimeWithRootAdopter(input);\n}\n\n/** Internal store runtime with the session-root adoption capability wired. */\nexport function createContainerContentsStoreWorkflowRuntime(\n input: ContainerContentsWorkflowRuntimeInput,\n adoptRootContainer: ContainerContentsRootAdopter,\n): ContainerContentsStoreWorkflowRuntime {\n return {\n ...createContainerContentsWorkflowRuntimeWithRootAdopter(\n input,\n adoptRootContainer,\n ),\n adoptRootContainer,\n };\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["runtime.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,gCAAgC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AkC,CAC5D,KAAK,CAAC,0BAA0B,CACjC;QACD,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,IAAI,EAAE,KAAK,CAAC,IAAI;KACjB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,KAA4C;IAE5C,OAAO,qDAAqD,CAAC,KAAK,CAAC,CAAC;AACtE,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,2CAA2C,CACzD,KAA4C,EAC5C,kBAAgD;IAEhD,OAAO,iCAAiC,CAAC,KAAK,EAAE;QAC9C,GAAG,qDAAqD,CACtD,KAAK,EACL,kBAAkB,CACnB;QACD,kBAAkB;KACnB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n type DocumentProjectorRegistryInput,\n resolveDocumentProjectorRegistry,\n} from \"../../data/documents/documentKinds\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { inheritPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../data/trustedUserIdentity\";\nimport {\n createDocumentsWorkflowRuntime,\n type DocumentsWorkflowRuntime,\n} from \"../documents\";\nimport type {\n WorkflowRuntimeAuthInput,\n WorkflowRuntimeCryptoInput,\n WorkflowRuntimeInfraInput,\n WorkflowRuntimeStateInput,\n WorkflowRuntimeUtilInput,\n} from \"../runtimeInput\";\n\ntype DocumentsWorkflowRuntimeInput = Parameters<\n typeof createDocumentsWorkflowRuntime\n>[0];\n\ntype ContainerContentsWorkflowApi = ApiClient &\n DocumentsWorkflowRuntimeInput[\"apiClient\"];\n\nexport interface ContainerContentsWorkflowRuntimeAuth\n extends WorkflowRuntimeAuthInput {}\n\nexport interface ContainerContentsWorkflowRuntimeCrypto\n extends WorkflowRuntimeCryptoInput {}\n\nexport interface ContainerContentsWorkflowRuntimeInfra\n extends Omit<WorkflowRuntimeInfraInput, \"dbStatus\"> {\n readonly dbStatus: string;\n}\n\ninterface ContainerContentsWorkflowRuntimeInputInfra\n extends Omit<ContainerContentsWorkflowRuntimeInfra, \"documentProjectors\"> {\n readonly documentProjectors: DocumentProjectorRegistryInput;\n}\n\nexport interface ContainerContentsWorkflowRuntimeState\n extends WorkflowRuntimeStateInput {}\n\nexport interface ContainerContentsWorkflowRuntimeUtil\n extends Omit<WorkflowRuntimeUtilInput, \"logError\"> {\n // Store recovery is best-effort, so hosts may retain the causal error without\n // making structured error logging mandatory for general workflow runtimes.\n readonly logError?: WorkflowRuntimeUtilInput[\"logError\"] | undefined;\n}\n\nexport interface ContainerContentsRootAdoptionInput {\n readonly domainScope: ContainerContentsWorkflowRuntimeState[\"domainScope\"];\n readonly expectedContainerId: string;\n readonly nextContainerId: string;\n readonly organizationId: string;\n readonly userId: string;\n}\n\nexport type ContainerContentsRootAdopter = (\n input: ContainerContentsRootAdoptionInput,\n) => boolean | \"already-adopted\";\n\nexport interface ContainerContentsWorkflowRuntimeGroups {\n readonly auth: ContainerContentsWorkflowRuntimeAuth;\n readonly crypto: ContainerContentsWorkflowRuntimeCrypto;\n readonly infra: ContainerContentsWorkflowRuntimeInfra;\n readonly state: ContainerContentsWorkflowRuntimeState;\n readonly util: ContainerContentsWorkflowRuntimeUtil;\n}\n\nexport interface ContainerContentsWorkflowRuntimeInputGroups {\n readonly auth: ContainerContentsWorkflowRuntimeAuth;\n readonly crypto: ContainerContentsWorkflowRuntimeCrypto;\n readonly infra: ContainerContentsWorkflowRuntimeInputInfra;\n readonly state: ContainerContentsWorkflowRuntimeState;\n readonly util: ContainerContentsWorkflowRuntimeUtil;\n}\n\nexport interface ContainerContentsWorkflowRuntimeInput\n extends ContainerContentsWorkflowRuntimeInputGroups {\n /** Private host custody, inherited by container and derived document runtimes. */\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n readonly apiClient: ContainerContentsWorkflowApi;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface ContainerContentsWorkflowRuntime\n extends ContainerContentsWorkflowRuntimeGroups,\n Pick<ContainerContentsWorkflowRuntimeInput, \"apiClient\"> {\n readonly adoptRootContainer?: ContainerContentsRootAdopter | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n}\n\nexport interface ContainerContentsStoreWorkflowRuntime\n extends ContainerContentsWorkflowRuntime {\n readonly adoptRootContainer: ContainerContentsRootAdopter;\n}\n\nexport interface ContainerContentsWorkflowSqlRuntime {\n readonly auth?: {\n readonly organizationId?: string | null | undefined;\n };\n readonly infra: {\n readonly execSql: ExecSql;\n };\n}\n\nfunction documentsRuntimeInput(\n runtime: ContainerContentsWorkflowRuntime,\n containerId: string | null,\n): DocumentsWorkflowRuntimeInput {\n return inheritPrincipalHistoryProtection(runtime, {\n apiClient: runtime.apiClient,\n auth: runtime.auth,\n crypto: runtime.crypto,\n infra: runtime.infra,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n state: { ...runtime.state, containerId },\n util: runtime.util,\n });\n}\n\nexport function createContainerContentsDocumentsRuntime(\n runtime: ContainerContentsWorkflowRuntime,\n containerId: string | null,\n): DocumentsWorkflowRuntime {\n return createDocumentsWorkflowRuntime(\n documentsRuntimeInput(runtime, containerId),\n );\n}\n\nfunction createContainerContentsWorkflowRuntimeWithRootAdopter(\n input: ContainerContentsWorkflowRuntimeInput,\n adoptRootContainer?: ContainerContentsRootAdopter | undefined,\n): ContainerContentsWorkflowRuntime {\n const documentProjectors = resolveDocumentProjectorRegistry(\n input.infra.documentProjectors,\n );\n const infra = {\n ...input.infra,\n documentProjectors,\n };\n\n return inheritPrincipalHistoryProtection(input, {\n ...(adoptRootContainer ? { adoptRootContainer } : {}),\n apiClient: input.apiClient,\n auth: input.auth,\n crypto: input.crypto,\n infra,\n resolveTrustedUserIdentity: requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n ),\n state: input.state,\n util: input.util,\n });\n}\n\nexport function createContainerContentsWorkflowRuntime(\n input: ContainerContentsWorkflowRuntimeInput,\n): ContainerContentsWorkflowRuntime {\n return createContainerContentsWorkflowRuntimeWithRootAdopter(input);\n}\n\n/** Internal store runtime with the session-root adoption capability wired. */\nexport function createContainerContentsStoreWorkflowRuntime(\n input: ContainerContentsWorkflowRuntimeInput,\n adoptRootContainer: ContainerContentsRootAdopter,\n): ContainerContentsStoreWorkflowRuntime {\n return inheritPrincipalHistoryProtection(input, {\n ...createContainerContentsWorkflowRuntimeWithRootAdopter(\n input,\n adoptRootContainer,\n ),\n adoptRootContainer,\n });\n}\n"]}
@@ -98,6 +98,7 @@ async function commitMissingGroupGrantPolicy(input) {
98
98
  throw new Error("Container group share requires principal policy signing context");
99
99
  }
100
100
  const policyApi = {
101
+ recoverPendingPrincipalMutation: input.apiClient.recoverPendingPrincipalMutation?.bind(input.apiClient),
101
102
  commitOrganizationGroupPolicy: input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),
102
103
  getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(input.apiClient),
103
104
  };
@@ -198,6 +199,9 @@ function loadShareGroupPolicy(input) {
198
199
  });
199
200
  }
200
201
  export async function shareRemoteContainerWithGroup(input) {
202
+ if (input.stillCurrent?.() === false)
203
+ return null;
204
+ await input.apiClient.recoverPendingPrincipalMutation?.(input.author.organizationId);
201
205
  if (input.stillCurrent?.() === false)
202
206
  return null;
203
207
  const resolveProjectionUserKey = requireProjectionUserKeyResolver(input.resolveProjectionUserKey, "Remote container share");
@@ -1 +1 @@
1
- {"version":3,"file":"share.js","sourceRoot":"","sources":["share.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,sCAAsC,EACtC,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iEAAiE,CAAC;AAC1H,OAAO,EAAE,y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AA2E;IAC3E,yEAAyE;IACzE,0EAA0E;IAC1E,sDAAsD;IACtD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,EAAE,CAAC;QACrC,MAAM,yBAAyB,CAC7B,KAAK,CAAC,OAAO,EACb,uBAAuB,CAAC,MAAM,EAC9B,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EACxB,KAAK,CAAC,MAAM,CAAC,cAAc,EAC3B,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CACrC,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,IAAI,CAAC;IAElD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n ContainerMutationAuthor,\n ContainerShareApi,\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport { createGroupMetadataAccess } from \"../../organizations/groupMetadataAccess\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { preparePrincipalContainerRematerializationBatch } from \"../../organizations/principalContainerRematerialization\";\nimport { setOrganizationGroupContainerGrant } from \"../../organizations/principalPolicy\";\nimport type { GroupPolicyNameReader } from \"../../organizations/principalPolicyRequest\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport { projectionWithCurrentAncestors } from \"./shareAncestorRepair\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport {\n advanceVerifiedSharePolicies,\n type ContainerManagedPrincipalShareApi,\n loadVerifiedGroupSharePrincipalPolicy,\n} from \"./sharePrincipalPolicy\";\n\nclass ContainerShareGenerationExpiredError extends Error {}\n\nasync function buildCurrentContainerSharePlan(\n input: Parameters<typeof buildMaterializedContainerSharePlan>[0],\n): Promise<MaterializedContainerSharePlan | null> {\n return nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerSharePlan(input),\n );\n}\n\n/** The container's projection, with any lazily stale chain above it repaired. */\nasync function resolveShareProjection(\n input: Omit<\n Parameters<typeof projectionWithCurrentAncestors>[0],\n \"previousProjection\" | \"resolveProjectionUserKey\"\n > & { previousProjection?: ContainerWriterProjectionResponse | undefined },\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<ContainerWriterProjectionResponse | null> {\n const servedProjection =\n input.previousProjection ??\n (await input.apiClient.getContainerWriterProjection(input.containerId));\n if (!servedProjection || input.stillCurrent?.() === false) return null;\n const previousProjection = await projectionWithCurrentAncestors({\n ...input,\n previousProjection: servedProjection,\n resolveProjectionUserKey,\n });\n return input.stillCurrent?.() === false ? null : previousProjection;\n}\n\nexport async function shareRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n} | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const recipientIdentity = await resolveTrustedUserIdentity(\n input.recipientUserId,\n );\n if (!recipientIdentity || input.stillCurrent?.() === false) {\n return null;\n }\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n recipient: {\n recipientEncapsulationPublicKey: recipientIdentity.encapsulationPublicKey,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n}\n\ninterface RemoteContainerGroupShareInput {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerManagedPrincipalShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n /**\n * The display name the user chose the group by, checked against the name\n * committed in the verified group policy so a relabeled read-model row\n * cannot redirect the share onto another group. `null` is reserved for the\n * grant-preserving re-wrap: a share that would mint a new grant without a\n * name is refused.\n */\n expectedGroupName: string | null;\n readEncryptedName?: GroupPolicyNameReader | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RemoteContainerGroupShareResult {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n}\n\nfunction isMaterializedContainerSharePlan(\n value: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >[\"plans\"][number],\n): value is MaterializedContainerSharePlan {\n return value.plan.body.eventType === \"container.grant\";\n}\n\nasync function prepareMissingGroupGrantMutations(input: {\n currentPolicy: PrincipalPolicyBundleResponse;\n nextPolicy: VerifiedPrincipalPolicy;\n shareInput: RemoteContainerGroupShareInput;\n}) {\n const { currentPolicy, nextPolicy, shareInput } = input;\n return preparePrincipalContainerRematerializationBatch({\n reportSecurityIncident: shareInput.reportSecurityIncident,\n apiClient: shareInput.apiClient,\n author: shareInput.author,\n execSql: shareInput.execSql,\n grants: [\n ...new Map(\n [...currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: shareInput.recipientGroupId,\n nextPolicy,\n resolveTrustedUserIdentity: shareInput.resolveTrustedUserIdentity,\n stillCurrent: shareInput.stillCurrent,\n targetSecretKey: shareInput.targetSecretKey,\n warmReferencedPrincipalPolicies: shareInput.warmReferencedPrincipalPolicies,\n });\n}\n\nasync function commitMissingGroupGrantPolicy(\n input: RemoteContainerGroupShareInput,\n): Promise<{\n preparedTarget: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >;\n storedPolicy: Awaited<ReturnType<typeof setOrganizationGroupContainerGrant>>;\n} | null> {\n const signingKeyPair = input.signingKeyPair;\n if (!signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n const policyApi = {\n commitOrganizationGroupPolicy:\n input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),\n getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(\n input.apiClient,\n ),\n };\n let preparedTarget:\n | Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >\n | undefined;\n try {\n const storedPolicy = await setOrganizationGroupContainerGrant({\n accessLevel: input.accessLevel,\n apiClient: policyApi,\n assertCanCommit: () => {\n if (input.stillCurrent?.() === false) {\n throw new ContainerShareGenerationExpiredError();\n }\n },\n containerId: input.containerId,\n execSql: input.execSql,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n prepareContainerMutations: async ({ currentPolicy, nextPolicy }) => {\n preparedTarget = await prepareMissingGroupGrantMutations({\n currentPolicy,\n nextPolicy,\n shareInput: input,\n });\n return preparedTarget;\n },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.author.signerUserId,\n signingFingerprint: input.author.signerKeyFingerprint,\n signingKeyPair,\n });\n if (!preparedTarget) {\n throw new Error(\"Container group share preparation is incomplete\");\n }\n return { preparedTarget, storedPolicy };\n } catch (error) {\n if (\n error instanceof ContainerShareGenerationExpiredError ||\n isProjectionVerificationCancelledError(error)\n ) {\n return null;\n }\n throw error;\n }\n}\n\nasync function commitMissingGroupGrant(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (!input.signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n if (input.stillCurrent?.() === false) return null;\n const committed = await commitMissingGroupGrantPolicy(input);\n if (!committed) return null;\n const { preparedTarget, storedPolicy } = committed;\n const targetIndex = preparedTarget?.plans.findIndex(\n (planned) => planned.plan.containerId === input.containerId,\n );\n const response =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : storedPolicy.containerMutations[targetIndex];\n const targetPlan =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : preparedTarget?.plans[targetIndex];\n if (\n !targetPlan ||\n !response ||\n !isMaterializedContainerSharePlan(targetPlan)\n ) {\n throw new Error(\"Container group share acknowledgement is incomplete\");\n }\n return {\n containerKey: targetPlan.containerKey,\n plan: targetPlan.plan,\n response,\n };\n}\n\n// Only a re-wrap of an existing signed grant may run without the chosen name;\n// minting a grant is exactly the operation the name binding protects.\nfunction assertGrantMintNamed(expectedGroupName: string | null): void {\n if (expectedGroupName === null) {\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n }\n}\n\nfunction loadShareGroupPolicy(input: RemoteContainerGroupShareInput) {\n return loadVerifiedGroupSharePrincipalPolicy({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedGroupName: input.expectedGroupName ?? undefined,\n readEncryptedName:\n input.readEncryptedName ??\n createGroupMetadataAccess({\n ...input,\n organizationId: input.author.organizationId,\n verifyMetadataContainer: createGroupMetadataContainerVerifier({\n ...input,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n }),\n }).readName,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function shareRemoteContainerWithGroup(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const verifiedPrincipalPolicy = await loadShareGroupPolicy(input);\n if (input.stillCurrent?.() === false) return null;\n await advanceVerifiedSharePolicies(\n input.execSql,\n verifiedPrincipalPolicy,\n input.stillCurrent,\n );\n if (input.stillCurrent?.() === false) return null;\n\n const signedGrant = verifiedPrincipalPolicy.policy.grants.find(\n (grant) => grant.containerId === input.containerId,\n );\n if (!signedGrant || signedGrant.accessLevel !== input.accessLevel) {\n assertGrantMintNamed(input.expectedGroupName);\n return commitMissingGroupGrant(input);\n }\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n principalPolicyCache: principalPolicyCacheForVerifiedPolicies(\n verifiedPrincipalPolicy.checkpointPolicies,\n ),\n previousProjection,\n recipient: {\n principalPolicy: verifiedPrincipalPolicy.policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n const result = await submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: verifiedPrincipalPolicy.checkpointPolicies,\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n if (!result) return null;\n\n // Keep the previously cached group epoch available until the old container\n // wrap has been unwrapped and the replacement has committed. Root has no\n // parent fallback, so caching the rotated policy any earlier destroys the\n // only local path to the KEK that must be re-wrapped.\n if (input.stillCurrent?.() !== false) {\n await savePrincipalPolicyBundle(\n input.execSql,\n verifiedPrincipalPolicy.bundle,\n new Date().toISOString(),\n input.author.organizationId,\n { stillCurrent: input.stillCurrent },\n );\n }\n if (input.stillCurrent?.() === false) return null;\n\n return result;\n}\n"]}
1
+ {"version":3,"file":"share.js","sourceRoot":"","sources":["share.ts"],"names":[],"mappings":"AAgBA,OAAO,EACL,sCAAsC,EACtC,wCAAwC,EAGxC,gCAAgC,GACjC,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,uCAAuC,EAAE,MAAM,iEAAiE,CAAC;AAC1H,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AAGjG,OAAO,EACL,kCAAkC,GAEnC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACpF,OAAO,EAAE,oCAAoC,EAAE,MAAM,qDAAqD,CAAC;AAC3G,OAAO,EAAE,+CAA+C,EAAE,MAAM,yDAAyD,CAAC;AAC1H,OAAO,EAAE,kCAAkC,EAAE,MAAM,qCAAqC,CAAC;AAEzF,OAAO,EACL,mCAAmC,EACnC,4BAA4B,GAC7B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,8BAA8B,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,mCAAmC,EAAE,MAAM,wBAAwB,CAAC;AAC7E,OAAO,EACL,4BAA4B,EAE5B,qCAAqC,GACtC,MAAM,wBAAwB,CAAC;AAEhC,MAAM,oCAAqC,SAAQ,KAAK;CAAG;AAE3D,KAAK,UAAU,8BAA8B,CAC3C,KAAgE;IAEhE,OAAO,wCAAwC,CAAC,GAAG,EAAE,CACnD,mCAAmC,CAAC,KAAK,CAAC,CAC3C,CAAC;AACJ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B,CAAC","sourcesContent":["import type {\n ContainerAccessLevel,\n SigningKeyPair,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type {\n ContainerMutationAuthor,\n ContainerShareApi,\n ContainerSharePlan,\n MaterializedContainerSharePlan,\n} from \"../../../data/containers/shared/types\";\nimport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n requireProjectionUserKeyResolver,\n} from \"../../../data/keyingProjectionVerification\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../data/keyingProjectionVerification/principalPolicyCache\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport type { SecurityIncidentReporter } from \"../../../data/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport {\n requireTrustedUserIdentityResolver,\n type TrustedUserIdentityResolver,\n} from \"../../../data/trustedUserIdentity\";\nimport { createGroupMetadataAccess } from \"../../organizations/groupMetadataAccess\";\nimport { createGroupMetadataContainerVerifier } from \"../../organizations/groupMetadataContainerAuthority\";\nimport { preparePrincipalContainerRematerializationBatch } from \"../../organizations/principalContainerRematerialization\";\nimport { setOrganizationGroupContainerGrant } from \"../../organizations/principalPolicy\";\nimport type { GroupPolicyNameReader } from \"../../organizations/principalPolicyRequest\";\nimport {\n submitAcknowledgedContainerMutation,\n submitPlainContainerMutation,\n} from \"./mutationSubmit\";\nimport { projectionWithCurrentAncestors } from \"./shareAncestorRepair\";\nimport { buildMaterializedContainerSharePlan } from \"./shareMaterialization\";\nimport {\n advanceVerifiedSharePolicies,\n type ContainerManagedPrincipalShareApi,\n loadVerifiedGroupSharePrincipalPolicy,\n} from \"./sharePrincipalPolicy\";\n\nclass ContainerShareGenerationExpiredError extends Error {}\n\nasync function buildCurrentContainerSharePlan(\n input: Parameters<typeof buildMaterializedContainerSharePlan>[0],\n): Promise<MaterializedContainerSharePlan | null> {\n return nullOnProjectionVerificationCancellation(() =>\n buildMaterializedContainerSharePlan(input),\n );\n}\n\n/** The container's projection, with any lazily stale chain above it repaired. */\nasync function resolveShareProjection(\n input: Omit<\n Parameters<typeof projectionWithCurrentAncestors>[0],\n \"previousProjection\" | \"resolveProjectionUserKey\"\n > & { previousProjection?: ContainerWriterProjectionResponse | undefined },\n resolveProjectionUserKey: ProjectionUserKeyResolver,\n): Promise<ContainerWriterProjectionResponse | null> {\n const servedProjection =\n input.previousProjection ??\n (await input.apiClient.getContainerWriterProjection(input.containerId));\n if (!servedProjection || input.stillCurrent?.() === false) return null;\n const previousProjection = await projectionWithCurrentAncestors({\n ...input,\n previousProjection: servedProjection,\n resolveProjectionUserKey,\n });\n return input.stillCurrent?.() === false ? null : previousProjection;\n}\n\nexport async function shareRemoteContainer(input: {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<{\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n} | null> {\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const resolveTrustedUserIdentity = requireTrustedUserIdentityResolver(\n input.resolveTrustedUserIdentity,\n );\n const recipientIdentity = await resolveTrustedUserIdentity(\n input.recipientUserId,\n );\n if (!recipientIdentity || input.stillCurrent?.() === false) {\n return null;\n }\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n previousProjection,\n recipient: {\n recipientEncapsulationPublicKey: recipientIdentity.encapsulationPublicKey,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n return submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: [],\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n}\n\ninterface RemoteContainerGroupShareInput {\n reportSecurityIncident: SecurityIncidentReporter;\n accessLevel: ContainerAccessLevel;\n apiClient: ContainerManagedPrincipalShareApi;\n author: ContainerMutationAuthor;\n containerId: string;\n eventId?: string | undefined;\n execSql: ExecSql;\n /**\n * The display name the user chose the group by, checked against the name\n * committed in the verified group policy so a relabeled read-model row\n * cannot redirect the share onto another group. `null` is reserved for the\n * grant-preserving re-wrap: a share that would mint a new grant without a\n * name is refused.\n */\n expectedGroupName: string | null;\n readEncryptedName?: GroupPolicyNameReader | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n previousProjection?: ContainerWriterProjectionResponse | undefined;\n recipientGroupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n signedAt?: string | undefined;\n signingKeyPair?: SigningKeyPair | null | undefined;\n stillCurrent?: (() => boolean) | undefined;\n targetSecretKey: Uint8Array;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}\n\ninterface RemoteContainerGroupShareResult {\n containerKey: Uint8Array;\n plan: ContainerSharePlan;\n response: ContainerMutationResponse;\n}\n\nfunction isMaterializedContainerSharePlan(\n value: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >[\"plans\"][number],\n): value is MaterializedContainerSharePlan {\n return value.plan.body.eventType === \"container.grant\";\n}\n\nasync function prepareMissingGroupGrantMutations(input: {\n currentPolicy: PrincipalPolicyBundleResponse;\n nextPolicy: VerifiedPrincipalPolicy;\n shareInput: RemoteContainerGroupShareInput;\n}) {\n const { currentPolicy, nextPolicy, shareInput } = input;\n return preparePrincipalContainerRematerializationBatch({\n reportSecurityIncident: shareInput.reportSecurityIncident,\n apiClient: shareInput.apiClient,\n author: shareInput.author,\n execSql: shareInput.execSql,\n grants: [\n ...new Map(\n [...currentPolicy.currentGrants, ...nextPolicy.grants].map(\n (grant) => [grant.containerId, grant] as const,\n ),\n ).values(),\n ],\n groupId: shareInput.recipientGroupId,\n nextPolicy,\n resolveTrustedUserIdentity: shareInput.resolveTrustedUserIdentity,\n stillCurrent: shareInput.stillCurrent,\n targetSecretKey: shareInput.targetSecretKey,\n warmReferencedPrincipalPolicies: shareInput.warmReferencedPrincipalPolicies,\n });\n}\n\nasync function commitMissingGroupGrantPolicy(\n input: RemoteContainerGroupShareInput,\n): Promise<{\n preparedTarget: Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >;\n storedPolicy: Awaited<ReturnType<typeof setOrganizationGroupContainerGrant>>;\n} | null> {\n const signingKeyPair = input.signingKeyPair;\n if (!signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n const policyApi = {\n recoverPendingPrincipalMutation:\n input.apiClient.recoverPendingPrincipalMutation?.bind(input.apiClient),\n commitOrganizationGroupPolicy:\n input.apiClient.commitOrganizationGroupPolicy.bind(input.apiClient),\n getCurrentPrincipalPolicy: input.apiClient.getCurrentPrincipalPolicy.bind(\n input.apiClient,\n ),\n };\n let preparedTarget:\n | Awaited<\n ReturnType<typeof preparePrincipalContainerRematerializationBatch>\n >\n | undefined;\n try {\n const storedPolicy = await setOrganizationGroupContainerGrant({\n accessLevel: input.accessLevel,\n apiClient: policyApi,\n assertCanCommit: () => {\n if (input.stillCurrent?.() === false) {\n throw new ContainerShareGenerationExpiredError();\n }\n },\n containerId: input.containerId,\n execSql: input.execSql,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n prepareContainerMutations: async ({ currentPolicy, nextPolicy }) => {\n preparedTarget = await prepareMissingGroupGrantMutations({\n currentPolicy,\n nextPolicy,\n shareInput: input,\n });\n return preparedTarget;\n },\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n signerUserId: input.author.signerUserId,\n signingFingerprint: input.author.signerKeyFingerprint,\n signingKeyPair,\n });\n if (!preparedTarget) {\n throw new Error(\"Container group share preparation is incomplete\");\n }\n return { preparedTarget, storedPolicy };\n } catch (error) {\n if (\n error instanceof ContainerShareGenerationExpiredError ||\n isProjectionVerificationCancelledError(error)\n ) {\n return null;\n }\n throw error;\n }\n}\n\nasync function commitMissingGroupGrant(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (!input.signingKeyPair) {\n throw new Error(\n \"Container group share requires principal policy signing context\",\n );\n }\n if (input.stillCurrent?.() === false) return null;\n const committed = await commitMissingGroupGrantPolicy(input);\n if (!committed) return null;\n const { preparedTarget, storedPolicy } = committed;\n const targetIndex = preparedTarget?.plans.findIndex(\n (planned) => planned.plan.containerId === input.containerId,\n );\n const response =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : storedPolicy.containerMutations[targetIndex];\n const targetPlan =\n targetIndex === undefined || targetIndex < 0\n ? undefined\n : preparedTarget?.plans[targetIndex];\n if (\n !targetPlan ||\n !response ||\n !isMaterializedContainerSharePlan(targetPlan)\n ) {\n throw new Error(\"Container group share acknowledgement is incomplete\");\n }\n return {\n containerKey: targetPlan.containerKey,\n plan: targetPlan.plan,\n response,\n };\n}\n\n// Only a re-wrap of an existing signed grant may run without the chosen name;\n// minting a grant is exactly the operation the name binding protects.\nfunction assertGrantMintNamed(expectedGroupName: string | null): void {\n if (expectedGroupName === null) {\n throw new Error(\n \"Minting a group grant requires the chosen group name; only a re-wrap of an existing signed grant may omit it\",\n );\n }\n}\n\nfunction loadShareGroupPolicy(input: RemoteContainerGroupShareInput) {\n return loadVerifiedGroupSharePrincipalPolicy({\n apiClient: input.apiClient,\n execSql: input.execSql,\n expectedGroupName: input.expectedGroupName ?? undefined,\n readEncryptedName:\n input.readEncryptedName ??\n createGroupMetadataAccess({\n ...input,\n organizationId: input.author.organizationId,\n verifyMetadataContainer: createGroupMetadataContainerVerifier({\n ...input,\n organizationId: input.author.organizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n }),\n }).readName,\n groupId: input.recipientGroupId,\n organizationId: input.author.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n}\n\nexport async function shareRemoteContainerWithGroup(\n input: RemoteContainerGroupShareInput,\n): Promise<RemoteContainerGroupShareResult | null> {\n if (input.stillCurrent?.() === false) return null;\n await input.apiClient.recoverPendingPrincipalMutation?.(\n input.author.organizationId,\n );\n if (input.stillCurrent?.() === false) return null;\n const resolveProjectionUserKey = requireProjectionUserKeyResolver(\n input.resolveProjectionUserKey,\n \"Remote container share\",\n );\n const previousProjection = await resolveShareProjection(\n input,\n resolveProjectionUserKey,\n );\n if (!previousProjection) return null;\n const verifiedPrincipalPolicy = await loadShareGroupPolicy(input);\n if (input.stillCurrent?.() === false) return null;\n await advanceVerifiedSharePolicies(\n input.execSql,\n verifiedPrincipalPolicy,\n input.stillCurrent,\n );\n if (input.stillCurrent?.() === false) return null;\n\n const signedGrant = verifiedPrincipalPolicy.policy.grants.find(\n (grant) => grant.containerId === input.containerId,\n );\n if (!signedGrant || signedGrant.accessLevel !== input.accessLevel) {\n assertGrantMintNamed(input.expectedGroupName);\n return commitMissingGroupGrant(input);\n }\n\n const materializedPlan = await buildCurrentContainerSharePlan({\n accessLevel: input.accessLevel,\n author: input.author,\n eventId: input.eventId,\n execSql: input.execSql,\n knownContainerKeks: input.knownContainerKeks,\n principalPolicyCache: principalPolicyCacheForVerifiedPolicies(\n verifiedPrincipalPolicy.checkpointPolicies,\n ),\n previousProjection,\n recipient: {\n principalPolicy: verifiedPrincipalPolicy.policy,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n },\n resolveProjectionUserKey,\n signedAt: input.signedAt,\n stillCurrent: input.stillCurrent,\n targetSecretKey: input.targetSecretKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n if (!materializedPlan) return null;\n const result = await submitAcknowledgedContainerMutation({\n reportSecurityIncident: input.reportSecurityIncident,\n recitationPolicies: verifiedPrincipalPolicy.checkpointPolicies,\n apiClient: input.apiClient,\n author: input.author,\n containerKey: materializedPlan.containerKey,\n execSql: input.execSql,\n plan: materializedPlan.plan,\n stillCurrent: input.stillCurrent,\n submit: () =>\n submitPlainContainerMutation(() =>\n input.apiClient.shareContainer(\n input.containerId,\n materializedPlan.plan.request,\n {\n expectedPaymentRequiredOrganizationId: input.author.organizationId,\n },\n ),\n ),\n });\n if (!result) return null;\n\n // Keep the previously cached group epoch available until the old container\n // wrap has been unwrapped and the replacement has committed. Root has no\n // parent fallback, so caching the rotated policy any earlier destroys the\n // only local path to the KEK that must be re-wrapped.\n if (input.stillCurrent?.() !== false) {\n await savePrincipalPolicyBundle(\n input.execSql,\n verifiedPrincipalPolicy.bundle,\n new Date().toISOString(),\n input.author.organizationId,\n { stillCurrent: input.stillCurrent },\n );\n }\n if (input.stillCurrent?.() === false) return null;\n\n return result;\n}\n"]}
@@ -7,6 +7,7 @@ import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
7
7
  import type { TrustedUserIdentityResolver } from "../../../data/trustedUserIdentity/index.js";
8
8
  import { type GroupPolicyNameReader } from "../../organizations/principalPolicyRequest.js";
9
9
  export interface ContainerManagedPrincipalShareApi extends ContainerShareApi, Pick<ApiClient, "evictContainerWriterProjection" | "getContainerWriterProjectionResult"> {
10
+ readonly recoverPendingPrincipalMutation?: ((organizationId: string) => Promise<void>) | undefined;
10
11
  commitOrganizationGroupPolicy: (organizationId: string, groupId: string, input: CommitOrganizationGroupPolicyRequest) => Promise<CommitOrganizationGroupPolicyResponse | null>;
11
12
  getCurrentPrincipalPolicy: (principalType: ManagedPrincipalKind, principalId: string) => Promise<PrincipalPolicyBundleResponse | null>;
12
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"sharePrincipalPolicy.js","sourceRoot":"","sources":["sharePrincipalPolicy.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAKxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AACjG,OAAO,EAAE,qCAAqC,EAAE,MAAM,+DAA+D,CAAC;AACtH,OAAO,EAAE,mCAAmC,EAAE,MAAM,uEAAuE,CAAC;AAC5H,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EACL,kCAAkC,EAClC,yDAAyD,GAC1D,MAAM,sDAAsD,CAAC;AAG9D,OAAO,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AACtF,OAAO,EAEL,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,qCAAqC,EACrC,mCA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M,QAAQ,GACZ,MAAM,yDAAyD,CAAC;QAC9D,MAAM;QACN,iBAAiB,EAAE,kBAAkB;QACrC,qBAAqB,EAAE,KAAK,IAAI,EAAE,CAChC,uBAAuB,CAAC,iBAAiB;QAC3C,eAAe;QACf,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;QACjB,uCAAuC,CACrC,QAAQ,CAAC,KAAK,EACd,sDAAsD,CACvD,CAAC;IACJ,CAAC;IACD,0BAA0B,CAAC,MAAM,EAAE,uBAAuB,CAAC,UAAU,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,iBAAiB,KAAK,SAAS,EAAE,CAAC;QAC1C,MAAM,oBAAoB,CAAC;YACzB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,MAAM;YACN,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;SAC3C,CAAC,CAAC;IACL,CAAC;IAED,MAAM,kBAAkB,GAAG,MAAM,2BAA2B,CAAC;QAC3D,MAAM;QACN,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,kBAAkB,EAAE,uBAAuB;QAC3C,MAAM,EAAE,QAAQ,CAAC,KAAK;QACtB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,OAAO;QACL,MAAM;QACN,kBAAkB;QAClB,iBAAiB,EAAE,qCAAqC,CACtD,uBAAuB,CACxB,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC;QAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ManagedPrincipalKind,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { CommitOrganizationGroupPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n CommitOrganizationGroupPolicyResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerShareApi } from \"../../../data/containers/shared/types\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../../data/persistence/keyingCheckpointPersistence\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../../data/persistence/principalPolicyReferencePersistence\";\nimport { retainVerifiedPrincipalPolicyBundle } from \"../../../data/persistence/verifiedPrincipalPolicyRetentionPersistence\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMetadataBinding } from \"../../organizations/groupMetadataBinding\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../../organizations/principalPolicyRequest\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../../principals/externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n} from \"../../principals/policyVerification\";\n\nexport interface ContainerManagedPrincipalShareApi\n extends ContainerShareApi,\n Pick<\n ApiClient,\n \"evictContainerWriterProjection\" | \"getContainerWriterProjectionResult\"\n > {\n commitOrganizationGroupPolicy: (\n organizationId: string,\n groupId: string,\n input: CommitOrganizationGroupPolicyRequest,\n ) => Promise<CommitOrganizationGroupPolicyResponse | null>;\n getCurrentPrincipalPolicy: (\n principalType: ManagedPrincipalKind,\n principalId: string,\n ) => Promise<PrincipalPolicyBundleResponse | null>;\n}\n\nexport interface VerifiedSharePrincipalPolicy {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly checkpointPolicies: readonly VerifiedPrincipalPolicy[];\n readonly dependencyBundles: readonly PrincipalPolicyBundleResponse[];\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\nasync function retainVerifiedSharePolicies(input: {\n bundle: PrincipalPolicyBundleResponse;\n execSql: ExecSql;\n organizationId: string;\n organizationPolicy: VerifiedExternalAdminPolicy | null;\n policy: VerifiedPrincipalPolicy;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const retainedAt = new Date().toISOString();\n if (input.organizationPolicy) {\n for (const entry of externalAdminPolicyPersistenceEntries(\n input.organizationPolicy,\n )) {\n await retainVerifiedPrincipalPolicyBundle({\n ...entry,\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n }\n }\n await retainVerifiedPrincipalPolicyBundle({\n bundle: input.bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n policy: input.policy,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n return [\n ...(input.organizationPolicy\n ? externalAdminPolicyPersistenceEntries(input.organizationPolicy).map(\n (entry) => entry.policy,\n )\n : []),\n input.policy,\n ];\n}\n\n/**\n * Commits the verification a loadVerifiedGroupSharePrincipalPolicy call\n * deferred: advances the keying checkpoints for the verified policies and\n * caches the dependency bundles they were verified against.\n */\nexport async function advanceVerifiedSharePolicies(\n execSql: ExecSql,\n verified: Pick<\n VerifiedSharePrincipalPolicy,\n \"checkpointPolicies\" | \"dependencyBundles\" | \"organizationId\"\n >,\n stillCurrent?: (() => boolean) | undefined,\n): Promise<void> {\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql,\n organizationId: verified.organizationId,\n policies: verified.checkpointPolicies,\n stillCurrent,\n });\n if (stillCurrent?.() === false) return;\n for (const bundle of verified.dependencyBundles) {\n await savePrincipalPolicyBundle(\n execSql,\n bundle,\n new Date().toISOString(),\n verified.organizationId,\n { stillCurrent },\n );\n if (stillCurrent?.() === false) return;\n }\n}\n\nfunction assertGroupPolicyTarget(\n bundle: PrincipalPolicyBundleResponse,\n groupId: string,\n): void {\n if (\n bundle.currentState.principalType !== \"group\" ||\n bundle.currentState.principalId !== groupId\n ) {\n throw new Error(\"Container share principal policy target mismatch\");\n }\n}\n\nfunction signerPublicKeyLoadErrorMessage(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): string {\n switch (code) {\n case \"fingerprint-mismatch\":\n return \"principal policy signer key fingerprint mismatch\";\n case \"not-found\":\n return \"principal policy signer key could not be loaded\";\n }\n}\n\nasync function loadGroupSharePolicyBundle(input: {\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n groupId: string;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n}): Promise<PrincipalPolicyBundleResponse> {\n if (\n input.expectedGroupHead &&\n (input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId)\n ) {\n throw new Error(\"Container share expected group policy target mismatch\");\n }\n const bundleFromCache = input.expectedGroupHead\n ? await loadPrincipalPolicyBundleForReference(\n input.execSql,\n input.expectedGroupHead,\n input.localCheckpoint,\n )\n : null;\n let bundle = bundleFromCache;\n bundle ??= await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n input.groupId,\n );\n if (!bundle) {\n throw new Error(\"Container share principal policy could not be loaded\");\n }\n assertGroupPolicyTarget(bundle, input.groupId);\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedGroupHead,\n )\n ) {\n throw new Error(\n \"Container share group policy does not match the signed organization directory\",\n );\n }\n return bundle;\n}\n\n/**\n * The chosen group label does not match the name in the group's verified\n * policy. A KeyingVerificationError (so it is reported as an incident), with\n * its own class so a caller can tell this refusal from every other\n * `object_mismatch` and say what happened.\n */\nexport class GroupShareNameMismatchError extends KeyingVerificationError {\n constructor(message: string) {\n super(\"object_mismatch\", message);\n this.name = \"GroupShareNameMismatchError\";\n }\n}\n\n/**\n * The share picker labels groups from the organization read model, which a\n * compromised server can relabel, so the name the user chose must equal the\n * name committed in the target's verified policy. Names compare by their\n * canonical key so look-alike spellings count as the same name. Uniqueness of\n * signed names within an organization is enforced where names enter — group\n * creation verifies every group in the signed directory — so a single\n * verified match identifies the group.\n */\nasync function assertShareGroupName(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n bundle: PrincipalPolicyBundleResponse;\n expectedGroupName: string;\n}): Promise<void> {\n // The label comes from the untrusted read model. Signed names never carry\n // an invisible code point, so a label that does is a look-alike that would\n // only match after canonicalization strips it; refuse it outright.\n const mismatch = await groupPolicyNameMismatch(\n input.bundle,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n if (mismatch === \"forbidden_characters\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name contains control or format characters\",\n );\n }\n if (mismatch === \"name_mismatch\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name does not match the signed group policy\",\n );\n }\n}\n\nexport async function loadVerifiedGroupSharePrincipalPolicy(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n /**\n * The display name the user chose the group by. The read model that labels\n * groups is a server projection; only the name committed in the signed\n * group payload can confirm the share lands on the group the user saw.\n */\n expectedGroupName?: string | undefined;\n groupId: string;\n organizationId: string;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedSharePrincipalPolicy> {\n const organizationAdminPolicy = await loadOrganizationExternalAdminPolicy({\n execSql: input.execSql,\n getCurrentPrincipalPolicy: (principalType, principalId) =>\n input.apiClient.getCurrentPrincipalPolicy(principalType, principalId),\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!organizationAdminPolicy) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const committedGroupHead = requireOrganizationGroupHead(\n organizationAdminPolicy.descriptor,\n input.groupId,\n );\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(input.expectedGroupHead, committedGroupHead)\n ) {\n throw new Error(\n \"Container share expected group head conflicts with the signed organization directory\",\n );\n }\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.groupId,\n );\n const bundle = await loadGroupSharePolicyBundle({\n ...input,\n expectedGroupHead: committedGroupHead,\n localCheckpoint,\n });\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(signerPublicKeyLoadErrorMessage(signerPublicKeys.error));\n }\n\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: committedGroupHead,\n loadExternalAuthority: async () =>\n organizationAdminPolicy.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Container share principal policy verification failed\",\n );\n }\n assertGroupMetadataBinding(bundle, organizationAdminPolicy.descriptor);\n if (input.expectedGroupName !== undefined) {\n await assertShareGroupName({\n readEncryptedName: input.readEncryptedName,\n bundle,\n expectedGroupName: input.expectedGroupName,\n });\n }\n\n const checkpointPolicies = await retainVerifiedSharePolicies({\n bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n organizationPolicy: organizationAdminPolicy,\n policy: verified.value,\n stillCurrent: input.stillCurrent,\n });\n return {\n bundle,\n checkpointPolicies,\n dependencyBundles: externalAdminPolicyPersistenceEntries(\n organizationAdminPolicy,\n ).map((entry) => entry.bundle),\n organizationId: input.organizationId,\n policy: verified.value,\n };\n}\n"]}
1
+ {"version":3,"file":"sharePrincipalPolicy.js","sourceRoot":"","sources":["sharePrincipalPolicy.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,GAKxB,MAAM,mBAAmB,CAAC;AAO3B,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,6BAA6B,EAAE,MAAM,uDAAuD,CAAC;AACtG,OAAO,EAAE,yBAAyB,EAAE,MAAM,sDAAsD,CAAC;AACjG,OAAO,EAAE,qCAAqC,EAAE,MAAM,+DAA+D,CAAC;AACtH,OAAO,EAAE,mCAAmC,EAAE,MAAM,uEAAuE,CAAC;AAC5H,OAAO,EACL,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,0DAA0D,CAAC;AAClE,OAAO,EACL,kCAAkC,EAClC,yDAAyD,GAC1D,MAAM,sDAAsD,CAAC;AAG9D,OAAO,EAAE,0BAA0B,EAAE,MAAM,0CAA0C,CAAC;AACtF,OAAO,EAEL,uBAAuB,GACxB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EACL,qCAAqC,EACrC,mCAAmC,GAEpC,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,sCAAsC,GAEvC,MAAM,qCAAqC,CAAC;AA8B7C,KAAK,UAAU,2BAA2B,CAAC,KAO1C;IACC,MAAM,UAAU,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC5C,IAAI,KAAK,CAAC,kBAAkB,EAAE,CAAC;QAC7B,KAAK,MAAM,KAA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AC;QACjB,uCAAuC,CACrC,QAAQ,CAAC,KAAK,EACd,sDAAsD,CACvD,CAAC;IACJ,CAAC;IACD,0BAA0B,CAAC,MAAM,EAAE,uBAAuB,CAAC,UAAU,CAAC,CAAC;IACvE,IAAI,KAAK,CAAC,iBAAiB,KAAK,SAAS,EAAE,CAAC;QAC1C,MAAM,oBAAoB,CAAC;YACzB,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;YAC1C,MAAM;YACN,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;SAC3C,CAAC,CAAC;IACL,CAAC;IAED,MAAM,kBAAkB,GAAG,MAAM,2BAA2B,CAAC;QAC3D,MAAM;QACN,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,kBAAkB,EAAE,uBAAuB;QAC3C,MAAM,EAAE,QAAQ,CAAC,KAAK;QACtB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,OAAO;QACL,MAAM;QACN,kBAAkB;QAClB,iBAAiB,EAAE,qCAAqC,CACtD,uBAAuB,CACxB,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,MAAM,CAAC;QAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport {\n KeyingVerificationError,\n type ManagedPrincipalKind,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { CommitOrganizationGroupPolicyRequest } from \"@tearleads/validators/request\";\nimport type {\n CommitOrganizationGroupPolicyResponse,\n PrincipalPolicyBundleResponse,\n} from \"@tearleads/validators/response\";\nimport type { ContainerShareApi } from \"../../../data/containers/shared/types\";\nimport { throwKeyingVerificationErrorWithContext } from \"../../../data/keyingProjectionVerification/error\";\nimport { advanceKeyingCheckpointsAtomically } from \"../../../data/persistence/keyingCheckpointAdvancePersistence\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../../data/persistence/keyingCheckpointPersistence\";\nimport { savePrincipalPolicyBundle } from \"../../../data/persistence/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../../data/persistence/principalPolicyReferencePersistence\";\nimport { retainVerifiedPrincipalPolicyBundle } from \"../../../data/persistence/verifiedPrincipalPolicyRetentionPersistence\";\nimport {\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport {\n principalPolicyReferenceFromBundle,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { assertGroupMetadataBinding } from \"../../organizations/groupMetadataBinding\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../../organizations/principalPolicyRequest\";\nimport {\n externalAdminPolicyPersistenceEntries,\n loadOrganizationExternalAdminPolicy,\n type VerifiedExternalAdminPolicy,\n} from \"../../principals/externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n} from \"../../principals/policyVerification\";\n\nexport interface ContainerManagedPrincipalShareApi\n extends ContainerShareApi,\n Pick<\n ApiClient,\n \"evictContainerWriterProjection\" | \"getContainerWriterProjectionResult\"\n > {\n readonly recoverPendingPrincipalMutation?:\n | ((organizationId: string) => Promise<void>)\n | undefined;\n commitOrganizationGroupPolicy: (\n organizationId: string,\n groupId: string,\n input: CommitOrganizationGroupPolicyRequest,\n ) => Promise<CommitOrganizationGroupPolicyResponse | null>;\n getCurrentPrincipalPolicy: (\n principalType: ManagedPrincipalKind,\n principalId: string,\n ) => Promise<PrincipalPolicyBundleResponse | null>;\n}\n\nexport interface VerifiedSharePrincipalPolicy {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly checkpointPolicies: readonly VerifiedPrincipalPolicy[];\n readonly dependencyBundles: readonly PrincipalPolicyBundleResponse[];\n readonly organizationId: string;\n readonly policy: VerifiedPrincipalPolicy;\n}\n\nasync function retainVerifiedSharePolicies(input: {\n bundle: PrincipalPolicyBundleResponse;\n execSql: ExecSql;\n organizationId: string;\n organizationPolicy: VerifiedExternalAdminPolicy | null;\n policy: VerifiedPrincipalPolicy;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy[]> {\n const retainedAt = new Date().toISOString();\n if (input.organizationPolicy) {\n for (const entry of externalAdminPolicyPersistenceEntries(\n input.organizationPolicy,\n )) {\n await retainVerifiedPrincipalPolicyBundle({\n ...entry,\n execSql: input.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n }\n }\n await retainVerifiedPrincipalPolicyBundle({\n bundle: input.bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n policy: input.policy,\n stillCurrent: input.stillCurrent,\n updatedAt: retainedAt,\n });\n return [\n ...(input.organizationPolicy\n ? externalAdminPolicyPersistenceEntries(input.organizationPolicy).map(\n (entry) => entry.policy,\n )\n : []),\n input.policy,\n ];\n}\n\n/**\n * Commits the verification a loadVerifiedGroupSharePrincipalPolicy call\n * deferred: advances the keying checkpoints for the verified policies and\n * caches the dependency bundles they were verified against.\n */\nexport async function advanceVerifiedSharePolicies(\n execSql: ExecSql,\n verified: Pick<\n VerifiedSharePrincipalPolicy,\n \"checkpointPolicies\" | \"dependencyBundles\" | \"organizationId\"\n >,\n stillCurrent?: (() => boolean) | undefined,\n): Promise<void> {\n await advanceKeyingCheckpointsAtomically({\n access: [],\n execSql,\n organizationId: verified.organizationId,\n policies: verified.checkpointPolicies,\n stillCurrent,\n });\n if (stillCurrent?.() === false) return;\n for (const bundle of verified.dependencyBundles) {\n await savePrincipalPolicyBundle(\n execSql,\n bundle,\n new Date().toISOString(),\n verified.organizationId,\n { stillCurrent },\n );\n if (stillCurrent?.() === false) return;\n }\n}\n\nfunction assertGroupPolicyTarget(\n bundle: PrincipalPolicyBundleResponse,\n groupId: string,\n): void {\n if (\n bundle.currentState.principalType !== \"group\" ||\n bundle.currentState.principalId !== groupId\n ) {\n throw new Error(\"Container share principal policy target mismatch\");\n }\n}\n\nfunction signerPublicKeyLoadErrorMessage(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): string {\n switch (code) {\n case \"fingerprint-mismatch\":\n return \"principal policy signer key fingerprint mismatch\";\n case \"not-found\":\n return \"principal policy signer key could not be loaded\";\n }\n}\n\nasync function loadGroupSharePolicyBundle(input: {\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n groupId: string;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n}): Promise<PrincipalPolicyBundleResponse> {\n if (\n input.expectedGroupHead &&\n (input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId)\n ) {\n throw new Error(\"Container share expected group policy target mismatch\");\n }\n const bundleFromCache = input.expectedGroupHead\n ? await loadPrincipalPolicyBundleForReference(\n input.execSql,\n input.expectedGroupHead,\n input.localCheckpoint,\n )\n : null;\n let bundle = bundleFromCache;\n bundle ??= await input.apiClient.getCurrentPrincipalPolicy(\n \"group\",\n input.groupId,\n );\n if (!bundle) {\n throw new Error(\"Container share principal policy could not be loaded\");\n }\n assertGroupPolicyTarget(bundle, input.groupId);\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(bundle),\n input.expectedGroupHead,\n )\n ) {\n throw new Error(\n \"Container share group policy does not match the signed organization directory\",\n );\n }\n return bundle;\n}\n\n/**\n * The chosen group label does not match the name in the group's verified\n * policy. A KeyingVerificationError (so it is reported as an incident), with\n * its own class so a caller can tell this refusal from every other\n * `object_mismatch` and say what happened.\n */\nexport class GroupShareNameMismatchError extends KeyingVerificationError {\n constructor(message: string) {\n super(\"object_mismatch\", message);\n this.name = \"GroupShareNameMismatchError\";\n }\n}\n\n/**\n * The share picker labels groups from the organization read model, which a\n * compromised server can relabel, so the name the user chose must equal the\n * name committed in the target's verified policy. Names compare by their\n * canonical key so look-alike spellings count as the same name. Uniqueness of\n * signed names within an organization is enforced where names enter — group\n * creation verifies every group in the signed directory — so a single\n * verified match identifies the group.\n */\nasync function assertShareGroupName(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n bundle: PrincipalPolicyBundleResponse;\n expectedGroupName: string;\n}): Promise<void> {\n // The label comes from the untrusted read model. Signed names never carry\n // an invisible code point, so a label that does is a look-alike that would\n // only match after canonicalization strips it; refuse it outright.\n const mismatch = await groupPolicyNameMismatch(\n input.bundle,\n input.expectedGroupName,\n input.readEncryptedName,\n );\n if (mismatch === \"forbidden_characters\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name contains control or format characters\",\n );\n }\n if (mismatch === \"name_mismatch\") {\n throw new GroupShareNameMismatchError(\n \"Container share group name does not match the signed group policy\",\n );\n }\n}\n\nexport async function loadVerifiedGroupSharePrincipalPolicy(input: {\n readEncryptedName?: GroupPolicyNameReader | undefined;\n apiClient: ContainerManagedPrincipalShareApi;\n execSql: ExecSql;\n expectedGroupHead?: ReferencedPrincipalHead | undefined;\n /**\n * The display name the user chose the group by. The read model that labels\n * groups is a server projection; only the name committed in the signed\n * group payload can confirm the share lands on the group the user saw.\n */\n expectedGroupName?: string | undefined;\n groupId: string;\n organizationId: string;\n resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<VerifiedSharePrincipalPolicy> {\n const organizationAdminPolicy = await loadOrganizationExternalAdminPolicy({\n execSql: input.execSql,\n getCurrentPrincipalPolicy: (principalType, principalId) =>\n input.apiClient.getCurrentPrincipalPolicy(principalType, principalId),\n organizationId: input.organizationId,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n if (!organizationAdminPolicy) {\n throw new Error(\"Organization admin authority could not be verified\");\n }\n const committedGroupHead = requireOrganizationGroupHead(\n organizationAdminPolicy.descriptor,\n input.groupId,\n );\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(input.expectedGroupHead, committedGroupHead)\n ) {\n throw new Error(\n \"Container share expected group head conflicts with the signed organization directory\",\n );\n }\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.groupId,\n );\n const bundle = await loadGroupSharePolicyBundle({\n ...input,\n expectedGroupHead: committedGroupHead,\n localCheckpoint,\n });\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n throw new Error(signerPublicKeyLoadErrorMessage(signerPublicKeys.error));\n }\n\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: committedGroupHead,\n loadExternalAuthority: async () =>\n organizationAdminPolicy.externalAuthority,\n localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) {\n throwKeyingVerificationErrorWithContext(\n verified.error,\n \"Container share principal policy verification failed\",\n );\n }\n assertGroupMetadataBinding(bundle, organizationAdminPolicy.descriptor);\n if (input.expectedGroupName !== undefined) {\n await assertShareGroupName({\n readEncryptedName: input.readEncryptedName,\n bundle,\n expectedGroupName: input.expectedGroupName,\n });\n }\n\n const checkpointPolicies = await retainVerifiedSharePolicies({\n bundle,\n execSql: input.execSql,\n organizationId: input.organizationId,\n organizationPolicy: organizationAdminPolicy,\n policy: verified.value,\n stillCurrent: input.stillCurrent,\n });\n return {\n bundle,\n checkpointPolicies,\n dependencyBundles: externalAdminPolicyPersistenceEntries(\n organizationAdminPolicy,\n ).map((entry) => entry.bundle),\n organizationId: input.organizationId,\n policy: verified.value,\n };\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { type ContainerWriterProjectionResponse, type DocumentCreateResponse, type DocumentWriterProjectionResponse } from "../../internal/validators/response/index.js";
1
+ import { type ContainerWriterProjectionResponse, type DocumentCreateResponse } from "../../internal/validators/response/index.js";
2
2
  import type { CreateRemoteDocumentResult, DocumentCreateApi, DocumentCreateAuthor, MaterializedDocumentCreatePlan, ProjectionVerificationOptions } from "../../data/documents/shared/types.js";
3
3
  import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../../data/keyingProjectionVerification.js";
4
4
  import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
@@ -16,19 +16,7 @@ export declare function buildMaterializedDocumentCreatePlan(input: {
16
16
  signedAt?: string | undefined;
17
17
  targetSecretKey: Uint8Array;
18
18
  } & ProjectionVerificationOptions): Promise<MaterializedDocumentCreatePlan>;
19
- /**
20
- * Build the writer projection a document-create response establishes, from the
21
- * container projection the create was authored against plus the manifest,
22
- * content-key bundle, and KEK targets the server just returned. This is the
23
- * same material a cold `GET /documents/:id/writer-projection` would yield, so
24
- * seeding it lets the first read after a create resolve locally. Shared by the
25
- * plain document-create path and the container-with-metadata-document path,
26
- * whose response carries an equivalent `DocumentCreateResponse`.
27
- */
28
- export declare function documentWriterProjectionFromCreateResponse(input: {
29
- containerProjection: ContainerWriterProjectionResponse;
30
- response: DocumentCreateResponse;
31
- }): DocumentWriterProjectionResponse;
19
+ export { documentWriterProjectionFromCreateResponse } from "./createProjection.js";
32
20
  interface RemoteDocumentCreateInput {
33
21
  apiClient: DocumentCreateApi;
34
22
  author: DocumentCreateAuthor;
@@ -66,4 +54,3 @@ type DocumentCreateSubmission = {
66
54
  readonly status: number | null;
67
55
  };
68
56
  export declare function isStaleDocumentCreateTargetConflict(submission: DocumentCreateSubmission): boolean;
69
- export {};