@tearleads/client-sdk 0.1.226 → 0.1.231

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 (253) hide show
  1. package/Tearleads.js +1 -1
  2. package/Tearleads.js.map +1 -1
  3. package/client/containerContents/documentDiscovery.js +4 -1
  4. package/client/containerContents/documentDiscovery.js.map +1 -1
  5. package/client/containerContents/index.d.ts +1 -1
  6. package/client/containerContents/index.js +4 -2
  7. package/client/containerContents/index.js.map +1 -1
  8. package/client/deviceFirst/index.js +1 -1
  9. package/client/deviceFirst/index.js.map +1 -1
  10. package/client/documents/index.js +6 -2
  11. package/client/documents/index.js.map +1 -1
  12. package/client/identity/index.js +1 -1
  13. package/client/identity/index.js.map +1 -1
  14. package/client/identity/userIdentities.d.ts +1 -1
  15. package/client/identity/userIdentities.js +1 -1
  16. package/client/identity/userIdentities.js.map +1 -1
  17. package/client/index.d.ts +2 -0
  18. package/client/index.js +2 -0
  19. package/client/index.js.map +1 -1
  20. package/client/organizations/index.js +1 -1
  21. package/client/organizations/index.js.map +1 -1
  22. package/client/organizations/organizationMemberships.d.ts +1 -1
  23. package/client/organizations/organizationMemberships.js +1 -1
  24. package/client/organizations/organizationMemberships.js.map +1 -1
  25. package/client/organizations/principalMutations.js +1 -1
  26. package/client/organizations/principalMutations.js.map +1 -1
  27. package/client/organizations/recipientAdmission.d.ts +1 -1
  28. package/client/organizations/recipientAdmission.js +1 -1
  29. package/client/organizations/recipientAdmission.js.map +1 -1
  30. package/client/runtime/apiVersion.js +1 -1
  31. package/client/runtime/apiVersion.js.map +1 -1
  32. package/client/runtime/containerContentsRuntime.d.ts +8 -0
  33. package/client/runtime/containerContentsRuntime.js +14 -0
  34. package/client/runtime/containerContentsRuntime.js.map +1 -0
  35. package/client/runtime/database.js +1 -1
  36. package/client/runtime/database.js.map +1 -1
  37. package/client/runtime/documentsRuntime.d.ts +5 -0
  38. package/client/runtime/documentsRuntime.js +10 -0
  39. package/client/runtime/documentsRuntime.js.map +1 -0
  40. package/client/runtime/events.js +1 -1
  41. package/client/runtime/events.js.map +1 -1
  42. package/client/runtime/network.js +1 -1
  43. package/client/runtime/network.js.map +1 -1
  44. package/client/runtime/runtimeIdentityResolution.js +1 -1
  45. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  46. package/client/runtime/syncBillingGate.js +1 -1
  47. package/client/runtime/syncBillingGate.js.map +1 -1
  48. package/client/runtime/workflowRuntime.d.ts +5 -2
  49. package/client/runtime/workflowRuntime.js +6 -2
  50. package/client/runtime/workflowRuntime.js.map +1 -1
  51. package/client/securityIncidents/index.d.ts +1 -1
  52. package/client/securityIncidents/index.js +2 -2
  53. package/client/securityIncidents/index.js.map +1 -1
  54. package/client/session/index.js +1 -1
  55. package/client/session/index.js.map +1 -1
  56. package/client/session/sessionLoginRefusal.js +1 -1
  57. package/client/session/sessionLoginRefusal.js.map +1 -1
  58. package/client/session/sessionRootAuthority.js +1 -1
  59. package/client/session/sessionRootAuthority.js.map +1 -1
  60. package/data/documents/shared/projection/freshProjectionRetry.js +1 -1
  61. package/data/documents/shared/projection/freshProjectionRetry.js.map +1 -1
  62. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +1 -1
  63. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  64. package/data/keyingProjectionVerification/checkpoints/heldContainerHeads.js.map +1 -0
  65. package/data/keyingProjectionVerification/error.js +1 -57
  66. package/data/keyingProjectionVerification/error.js.map +1 -1
  67. package/data/persistence/container-contents/documentContainerProjectionPersistence.d.ts +6 -2
  68. package/data/persistence/container-contents/documentContainerProjectionPersistence.js +10 -1
  69. package/data/persistence/container-contents/documentContainerProjectionPersistence.js.map +1 -1
  70. package/data/persistence/documents/documentDeletionPort.d.ts +28 -0
  71. package/data/persistence/documents/documentDeletionPort.js +2 -0
  72. package/data/persistence/documents/documentDeletionPort.js.map +1 -0
  73. package/data/persistence/documents/documentsPersistence.d.ts +1 -0
  74. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  75. package/data/persistence/documents/internal/documentDeletionPersistence.js +7 -7
  76. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  77. package/data/persistence/documents/types.d.ts +2 -15
  78. package/data/persistence/documents/types.js.map +1 -1
  79. package/data/principals/organizationPolicyRequest.d.ts +12 -0
  80. package/data/principals/organizationPolicyRequest.js +71 -0
  81. package/data/principals/organizationPolicyRequest.js.map +1 -0
  82. package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.d.ts +3 -3
  83. package/{workflows/organizations/principalPolicy → data/principals}/principalPolicyRequest.js +3 -3
  84. package/data/principals/principalPolicyRequest.js.map +1 -0
  85. package/{workflows/principals/policyVerification.js → data/principals/principalPolicyVerification.js} +4 -4
  86. package/data/principals/principalPolicyVerification.js.map +1 -0
  87. package/data/shared/securityIncidents.d.ts +18 -1
  88. package/data/shared/securityIncidents.js +58 -1
  89. package/data/shared/securityIncidents.js.map +1 -1
  90. package/index.d.ts +5 -5
  91. package/index.js +3 -3
  92. package/index.js.map +1 -1
  93. package/package.json +1 -1
  94. package/stores/container-contents/hydration/backgroundHydration.js +1 -1
  95. package/stores/container-contents/hydration/backgroundHydration.js.map +1 -1
  96. package/stores/container-contents/operations/reportShareFailure.js +1 -1
  97. package/stores/container-contents/operations/reportShareFailure.js.map +1 -1
  98. package/stores/container-contents/operations/shareOperations.js +1 -1
  99. package/stores/container-contents/operations/shareOperations.js.map +1 -1
  100. package/stores/container-contents/systemContainers/systemContainerHydration.js +1 -1
  101. package/stores/container-contents/systemContainers/systemContainerHydration.js.map +1 -1
  102. package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js +1 -1
  103. package/stores/documents/documentStore/attachmentUpload/attachmentUploadAttempt.js.map +1 -1
  104. package/stores/documents/documentStore/persistence.js +1 -0
  105. package/stores/documents/documentStore/persistence.js.map +1 -1
  106. package/stores/documents/documentStore/sync/index.js +1 -1
  107. package/stores/documents/documentStore/sync/index.js.map +1 -1
  108. package/stores/documents/documentStore/sync/syncRequest.js +1 -0
  109. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  110. package/workflows/blobs/hydration/hydrationResults.js +2 -1
  111. package/workflows/blobs/hydration/hydrationResults.js.map +1 -1
  112. package/workflows/blobs/verification/attachmentDecryptor.js +1 -1
  113. package/workflows/blobs/verification/attachmentDecryptor.js.map +1 -1
  114. package/workflows/container-contents/container-state/create/createAdoption.js +1 -1
  115. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  116. package/workflows/container-contents/container-state/create/createIntentSync.js +1 -1
  117. package/workflows/container-contents/container-state/create/createIntentSync.js.map +1 -1
  118. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -1
  119. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  120. package/workflows/container-contents/container-state/organizationHost.d.ts +54 -0
  121. package/workflows/container-contents/container-state/organizationHost.js +2 -0
  122. package/workflows/container-contents/container-state/organizationHost.js.map +1 -0
  123. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -1
  124. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  125. package/workflows/container-contents/container-state/remote.js +2 -4
  126. package/workflows/container-contents/container-state/remote.js.map +1 -1
  127. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
  128. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  129. package/workflows/container-contents/container-state/share/groupShareEpoch.js +1 -2
  130. package/workflows/container-contents/container-state/share/groupShareEpoch.js.map +1 -1
  131. package/workflows/container-contents/container-state/types.js.map +1 -1
  132. package/workflows/container-contents/documentLinks/index.js +1 -1
  133. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  134. package/workflows/container-contents/documentMove/documentMoveIntentSync.js +1 -1
  135. package/workflows/container-contents/documentMove/documentMoveIntentSync.js.map +1 -1
  136. package/workflows/container-contents/index.d.ts +1 -0
  137. package/workflows/container-contents/index.js.map +1 -1
  138. package/workflows/container-contents/info/documentInfo.d.ts +1 -1
  139. package/workflows/container-contents/info/documentInfo.js +1 -1
  140. package/workflows/container-contents/info/documentInfo.js.map +1 -1
  141. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  142. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  143. package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js +1 -2
  144. package/workflows/container-contents/remoteHydration/destination/destinationRootReload.js.map +1 -1
  145. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +3 -4
  146. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  147. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js +1 -1
  148. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerState.js.map +1 -1
  149. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  150. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  151. package/workflows/container-contents/runtime.d.ts +5 -0
  152. package/workflows/container-contents/runtime.js +3 -0
  153. package/workflows/container-contents/runtime.js.map +1 -1
  154. package/workflows/container-contents/syncPause/documentRemoval.js +2 -0
  155. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
  156. package/workflows/container-contents/tombstones/documentPurge.js +5 -2
  157. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  158. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +1 -1
  159. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  160. package/workflows/containers/child/mutationSubmit.js +1 -1
  161. package/workflows/containers/child/mutationSubmit.js.map +1 -1
  162. package/workflows/containers/child/recite.js +1 -1
  163. package/workflows/containers/child/recite.js.map +1 -1
  164. package/workflows/containers/child/recitePlan.js.map +1 -1
  165. package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js +1 -1
  166. package/workflows/containers/rematerialization/acknowledgePrincipalContainerRematerialization.js.map +1 -1
  167. package/workflows/documents/documentMutationCommit.d.ts +2 -1
  168. package/workflows/documents/documentMutationCommit.js +1 -0
  169. package/workflows/documents/documentMutationCommit.js.map +1 -1
  170. package/workflows/documents/documentPersistGuards.js +2 -1
  171. package/workflows/documents/documentPersistGuards.js.map +1 -1
  172. package/workflows/documents/purge/persistedDocumentRemoval.d.ts +2 -1
  173. package/workflows/documents/purge/persistedDocumentRemoval.js +2 -2
  174. package/workflows/documents/purge/persistedDocumentRemoval.js.map +1 -1
  175. package/workflows/documents/runtime.d.ts +5 -0
  176. package/workflows/documents/runtime.js +1 -0
  177. package/workflows/documents/runtime.js.map +1 -1
  178. package/workflows/documents/sync/syncSubmittedResult.js +1 -1
  179. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  180. package/workflows/documents/syncPlan/syncContentKeys.js +1 -1
  181. package/workflows/documents/syncPlan/syncContentKeys.js.map +1 -1
  182. package/workflows/organizations/containerContentsHost.js +14 -0
  183. package/workflows/organizations/containerContentsHost.js.map +1 -0
  184. package/workflows/organizations/groupMetadata/groupMetadataAccess.d.ts +1 -1
  185. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  186. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +1 -1
  187. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js +1 -1
  188. package/workflows/organizations/groupNames/currentOrganizationGroupNames.js.map +1 -1
  189. package/workflows/organizations/groupNames/groupMembershipName.d.ts +1 -1
  190. package/workflows/organizations/groupNames/groupMembershipName.js +1 -1
  191. package/workflows/organizations/groupNames/groupMembershipName.js.map +1 -1
  192. package/workflows/organizations/groupNames/groupNameUniqueness.js +2 -2
  193. package/workflows/organizations/groupNames/groupNameUniqueness.js.map +1 -1
  194. package/workflows/organizations/groupPolicy/groupPolicyRequests.js +1 -1
  195. package/workflows/organizations/groupPolicy/groupPolicyRequests.js.map +1 -1
  196. package/workflows/organizations/groupPolicy/groupPolicyVerification.js +1 -1
  197. package/workflows/organizations/groupPolicy/groupPolicyVerification.js.map +1 -1
  198. package/workflows/organizations/groupShare/currentShareGrantMutation.js +1 -1
  199. package/workflows/organizations/groupShare/currentShareGrantMutation.js.map +1 -1
  200. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -1
  201. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +1 -1
  202. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  203. package/workflows/organizations/groupShare/sharePrincipalPolicy.d.ts +1 -1
  204. package/workflows/organizations/groupShare/sharePrincipalPolicy.js +2 -2
  205. package/workflows/organizations/groupShare/sharePrincipalPolicy.js.map +1 -1
  206. package/workflows/organizations/groupShare/shareWithGroup.d.ts +1 -1
  207. package/workflows/organizations/groupShare/shareWithGroup.js.map +1 -1
  208. package/workflows/organizations/groups/createCurrentOrganizationGroup.js +1 -1
  209. package/workflows/organizations/groups/createCurrentOrganizationGroup.js.map +1 -1
  210. package/workflows/organizations/groups/groupCreation.js +1 -1
  211. package/workflows/organizations/groups/groupCreation.js.map +1 -1
  212. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  213. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js +1 -1
  214. package/workflows/organizations/policyHistory/loadPolicyHistoryDetails.js.map +1 -1
  215. package/workflows/organizations/principalPolicy/index.d.ts +2 -2
  216. package/workflows/organizations/principalPolicy/index.js +1 -1
  217. package/workflows/organizations/principalPolicy/index.js.map +1 -1
  218. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js +1 -1
  219. package/workflows/principals/acknowledgements/acknowledgedPrincipalCurrents.js.map +1 -1
  220. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js +1 -1
  221. package/workflows/principals/acknowledgements/initialPrincipalCurrentPublication.js.map +1 -1
  222. package/workflows/principals/externalAdminPolicy.js +1 -1
  223. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  224. package/workflows/principals/historyRecovery/principalHistoryPageAppend.js +1 -1
  225. package/workflows/principals/historyRecovery/principalHistoryPageAppend.js.map +1 -1
  226. package/workflows/principals/policyCache/index.d.ts +1 -1
  227. package/workflows/principals/policyCache/index.js +3 -2
  228. package/workflows/principals/policyCache/index.js.map +1 -1
  229. package/workflows/principals/policyCache/principalPolicyCacheValidation.js +1 -1
  230. package/workflows/principals/policyCache/principalPolicyCacheValidation.js.map +1 -1
  231. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +1 -1
  232. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  233. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js +1 -1
  234. package/workflows/principals/publicHistory/publicPrincipalHistoryPage.js.map +1 -1
  235. package/workflows/principals/runtimePolicyRecovery.d.ts +1 -1
  236. package/workflows/principals/runtimePolicyRecovery.js +1 -1
  237. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  238. package/workflows/principals/runtimeProjectionPolicyRecovery.js +1 -1
  239. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  240. package/workflows/registration/index.d.ts +2 -1
  241. package/workflows/registration/index.js +1 -1
  242. package/workflows/registration/index.js.map +1 -1
  243. package/workflows/registration/organizationProvisioning.d.ts +1 -12
  244. package/workflows/registration/organizationProvisioning.js +2 -70
  245. package/workflows/registration/organizationProvisioning.js.map +1 -1
  246. package/workflows/registration/persistRegistrationBootstrap.js +2 -0
  247. package/workflows/registration/persistRegistrationBootstrap.js.map +1 -1
  248. package/data/containers/shared/heldContainerHeads.js.map +0 -1
  249. package/workflows/organizations/principalPolicy/principalPolicyRequest.js.map +0 -1
  250. package/workflows/principals/policyVerification.js.map +0 -1
  251. /package/data/{containers/shared → keyingProjectionVerification/checkpoints}/heldContainerHeads.js +0 -0
  252. /package/{client/runtime → data/shared}/listenerSet.js +0 -0
  253. /package/{client/runtime → data/shared}/listenerSet.js.map +0 -0
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB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BAAiB,EAAE,KAAK,CAAC,SAAS;gBAClC,eAAe,EAAE,KAAK,CAAC,eAAe;gBACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;aACpD,CAAC,EACF,CAAC;gBACD,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../policyVerification\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCacheValidation.js","sourceRoot":"","sources":["principalPolicyCacheValidation.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EACL,+BAA+B,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,KAAK,CAAC,eAAe;gBACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;aACpD,CAAC,EACF,CAAC;gBACD,MAAM,IAAI,oCAAoC,CAC5C,6CAA6C,CAC9C,CAAC;YACJ,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC;QACD,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,gBAAgB,EAAE,gBAAgB,CAAC,gBAAgB;KACpD,CAAC,CAAC;IACL,IAAI,CAAC,QAAQ,CAAC,EAAE;QAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAC,KAAK,EAAE,EAAE,EAAE,KAAK,EAAE,CAAC;IAC9D,OAAO;QACL,mBAAmB,EAAE,uBAAuB;YAC1C,CAAC,CAAC,MAAM,KAAK,CAAC,uBAAuB,EAAE;YACvC,CAAC,CAAC,IAAI;QACR,EAAE,EAAE,IAAI;QACR,MAAM,EAAE,QAAQ,CAAC,KAAK;KACvB,CAAC;AACJ,CAAC","sourcesContent":["import {\n type KeyingVerificationCode,\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n PrincipalPolicyBundleResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n externalAuthorityCouldAuthorize,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n type PrincipalPolicySignerPublicKeyLoadErrorCode,\n principalPolicyStates,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/shared/dependencyUnavailable\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { VerifiedExternalAdminPolicy } from \"../externalAdminPolicy\";\n\ninterface PrincipalPolicyValidationFailure {\n readonly code: KeyingVerificationCode;\n readonly message: string;\n}\n\nfunction getBundleReferenceFailure(\n reference: ReferencedPrincipalStateResponse,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n const states = principalPolicyStates(bundle);\n const hasReferencedPrincipal = states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId,\n );\n if (!hasReferencedPrincipal) {\n return {\n code: \"object_mismatch\",\n message: \"bundle principal does not match referenced principal\",\n };\n }\n if (\n !states.some(\n (state) =>\n state.principalType === reference.principalType &&\n state.principalId === reference.principalId &&\n state.version === reference.version &&\n state.keyEpoch === reference.keyEpoch &&\n state.stateHash === reference.stateHash &&\n state.keyFingerprint === reference.keyFingerprint,\n )\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"bundle chain does not contain referenced principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.principalType !==\n bundle.currentState.principalType ||\n bundle.currentMemberEnvelopes.principalId !==\n bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"member envelope principal does not match current principal\",\n };\n }\n if (\n bundle.currentMemberEnvelopes.stateHash !== bundle.currentState.stateHash\n ) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope state hash does not match current principal\",\n };\n }\n if (bundle.currentMemberEnvelopes.epoch !== bundle.currentState.keyEpoch) {\n return {\n code: \"hash_mismatch\",\n message: \"member envelope epoch does not match current principal\",\n };\n }\n if (\n bundle.currentPayload.principalType !== bundle.currentState.principalType ||\n bundle.currentPayload.principalId !== bundle.currentState.principalId\n ) {\n return {\n code: \"object_mismatch\",\n message: \"payload principal does not match current principal\",\n };\n }\n if (bundle.currentPayload.stateHash !== bundle.currentState.stateHash) {\n return {\n code: \"hash_mismatch\",\n message: \"payload state hash does not match current principal\",\n };\n }\n return null;\n}\n\nfunction getCheckpointFailure(\n checkpoint: PrincipalPolicyCheckpoint | null,\n bundle: PrincipalPolicyBundleResponse,\n): PrincipalPolicyValidationFailure | null {\n if (!checkpoint) {\n return null;\n }\n const current = bundle.currentState;\n if (current.version < checkpoint.version) {\n return {\n code: \"rollback\",\n message: \"principal policy state is older than the local checkpoint\",\n };\n }\n if (\n current.version === checkpoint.version &&\n current.stateHash !== checkpoint.stateHash\n ) {\n return {\n code: \"equivocation\",\n message: \"principal policy state conflicts with the local checkpoint\",\n };\n }\n if (current.version === checkpoint.version) {\n return null;\n }\n const checkpointState = principalPolicyStates(bundle).find(\n (state) => state.version === checkpoint.version,\n );\n return checkpointState?.stateHash === checkpoint.stateHash\n ? null\n : {\n code: \"stale_predecessor\",\n message: \"principal policy chain does not extend the local checkpoint\",\n };\n}\n\nfunction signerPublicKeyLoadFailure(\n code: PrincipalPolicySignerPublicKeyLoadErrorCode,\n): PrincipalPolicyValidationFailure {\n switch (code) {\n case \"fingerprint-mismatch\":\n return {\n code: \"signer_mismatch\",\n message: \"signer key fingerprint does not match state signer\",\n };\n case \"not-found\":\n // The identity source throws for transport failures, so an absent\n // signer here is the server asserting the cited user does not exist.\n return {\n code: \"missing_dependency\",\n message: \"signer identity is unknown to the server\",\n };\n }\n}\n\nfunction verificationError(\n failure: PrincipalPolicyValidationFailure,\n): KeyingVerificationError {\n return new KeyingVerificationError(failure.code, failure.message);\n}\n\nexport async function validatePrincipalPolicyBundleForCache(input: {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly loadExternalAdminPolicy: () => Promise<VerifiedExternalAdminPolicy | null>;\n readonly localCheckpoint: PrincipalPolicyCheckpoint | null;\n readonly reference: ReferencedPrincipalStateResponse;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n /** The cache operation's lifetime, checked inside every pin write. */\n readonly stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | {\n readonly externalAdminPolicy: VerifiedExternalAdminPolicy | null;\n readonly ok: true;\n readonly policy: VerifiedPrincipalPolicy;\n }\n | { readonly error: KeyingVerificationError; readonly ok: false }\n> {\n const referenceFailure = getBundleReferenceFailure(\n input.reference,\n input.bundle,\n );\n if (referenceFailure) {\n return { error: verificationError(referenceFailure), ok: false };\n }\n const checkpointFailure = getCheckpointFailure(\n input.localCheckpoint,\n input.bundle,\n );\n if (checkpointFailure) {\n return { error: verificationError(checkpointFailure), ok: false };\n }\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: input.bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signerPublicKeys) {\n return {\n error: verificationError(\n signerPublicKeyLoadFailure(signerPublicKeys.error),\n ),\n ok: false,\n };\n }\n\n let usedExternalAdminPolicy = false;\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle: input.bundle,\n expectedReference: input.reference,\n loadExternalAuthority: async () => {\n usedExternalAdminPolicy = true;\n const authority = (await input.loadExternalAdminPolicy())\n ?.externalAuthority;\n if (authority) return authority;\n // The loader returns null when the organization's Admins policy could\n // not be fetched, and an honest server always serves it. When that\n // evidence is all the chain lacks, the gap is availability, not a\n // refused signer, so it must not surface as an incident. A chain no\n // evidence could authorize keeps its unauthorized refusal.\n if (\n await externalAuthorityCouldAuthorize({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n bundle: input.bundle,\n expectedReference: input.reference,\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n })\n ) {\n throw new ProjectionDependencyUnavailableError(\n \"Organization Admins evidence is unavailable\",\n );\n }\n return null;\n },\n localCheckpoint: input.localCheckpoint,\n signerPublicKeys: signerPublicKeys.signerPublicKeys,\n });\n if (!verified.ok) return { error: verified.error, ok: false };\n return {\n externalAdminPolicy: usedExternalAdminPolicy\n ? await input.loadExternalAdminPolicy()\n : null,\n ok: true,\n policy: verified.value,\n };\n}\n"]}
@@ -4,7 +4,7 @@ import { KeyingCheckpointRepository } from "../../../data/persistence/keyingChec
4
4
  import { PrincipalPolicyBundleRepository } from "../../../data/persistence/principalPolicy/principalPolicyBundleRepository.js";
5
5
  import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, } from "../../../data/principalContracts/organizationAuthorityDescriptor.js";
6
6
  import { verifyOrganizationAdminPolicy } from "../../../data/principalContracts/principalPolicyAdminSigners.js";
7
- import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../policyVerification.js";
7
+ import { collectPrincipalPolicySignerPublicKeys, publishVerifiedPrincipalPolicy, } from "../../../data/principals/principalPolicyVerification.js";
8
8
  export function directoryBindsGroupReference(directory, policy, reference) {
9
9
  const head = directory?.descriptor.groupHeads.find((head) => head.principalId === reference.principalId);
10
10
  // A newer directory head authenticates its verified predecessors too.
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,8DAA8D,CAAC;AAI7G,OAAO,EACL,sCAAsC,EACtC,8BAA8B,GAC/B,MAAM,uBAAuB,CAAC;AAY/B,MAAM,UAAU,4BAA4B,CAC1C,SAAyC,EACzC,MAA+B,EAC/B,SAAkC;IAElC,MAAM,IAAI,GAAG,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,IAAI,CAChD,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,WAAW,KAAK,SAAS,CAAC,WAAW,CACrD,CAAC;IACF,sEAAsE;IACtE,2EAA2E;IAC3E,OAAO,CACL,CAAC,CAAC,IAAI;QACN,IAAI,CAAC,OAAO,IAAI,SAAS,CAAC,OAAO;QACjC,IAAI,CAAC,OAAO,KAAK,MAAM,CAAC,OAAO;QAC/B,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B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../policyVerification\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = PrincipalPolicyBundleResponse | null;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
1
+ {"version":3,"file":"principalPolicyOrganizationScope.js","sourceRoot":"","sources":["principalPolicyOrganizationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,kCAAkC,EAAE,MAAM,4CAA4C,CAAC;AAChG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,+BAA+B,EAAE,MAAM,2EAA2E,CAAC;AAC5H,OAAO,EAEL,oCAAoC,EACpC,6BAA6B,GAC9B,MAAM,kEAAkE,CAAC;AAC1E,OAAO,EAAE,6BAA6B,EAAE,MAAM,8DAA8D,CAAC;AAC7G,OAAO,EACL,sCAAsC,EACtC,8BAA8B,GAC/B,MAAM,sDAAsD,CAAC;AAe9D,MAAM,UAAU,4BAA4B,CAC1C,SAAyC,EACzC,MAA+B,EAC/B,SAAkC;IAElC,MAAM,IAAI,GAAG,SAAS,EAAE,UAAU,CAAC,UAAU,CAAC,IAAI,CAChD,CAAC,IAAI,EAAE,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,6CAA6C,CAC9C,CAAC;QACJ,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,KAAK,EAAE,UAAU,EAAE,CAAC;IACxD,CAAC,CAAC;IACF,OAAO,CAAC,MAAM,EAAE,EAAE;QAChB,IAAI,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QAC/B,IAAI,CAAC,OAAO,EAAE,CAAC;YACb,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,IAAI,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;QAC5B,CAAC;QACD,OAAO,OAAO,CAAC;IACjB,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { principalPolicyHeadMeetsCheckpoint } from \"../../../data/keyingProjectionVerification\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../../data/persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n type OrganizationAuthorityDescriptor,\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n} from \"../../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { verifyOrganizationAdminPolicy } from \"../../../data/principalContracts/principalPolicyAdminSigners\";\nimport {\n collectPrincipalPolicySignerPublicKeys,\n publishVerifiedPrincipalPolicy,\n} from \"../../../data/principals/principalPolicyVerification\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { CurrentPrincipalPolicyReader } from \"../currentPrincipalPolicyReader\";\n\nexport interface VerifiedPolicyDirectory {\n readonly bundle: PrincipalPolicyBundleResponse;\n readonly policy: VerifiedPrincipalPolicy;\n readonly descriptor: OrganizationAuthorityDescriptor;\n}\n\nexport type PolicyDirectoryLoader = (\n remote: boolean,\n) => Promise<VerifiedPolicyDirectory | null>;\n\nexport function directoryBindsGroupReference(\n directory: VerifiedPolicyDirectory | null,\n policy: VerifiedPrincipalPolicy,\n reference: ReferencedPrincipalHead,\n): boolean {\n const head = directory?.descriptor.groupHeads.find(\n (head) => head.principalId === reference.principalId,\n );\n // A newer directory head authenticates its verified predecessors too.\n // Requiring equality with a historical manifest citation bricks old reads.\n return (\n !!head &&\n head.version >= reference.version &&\n head.version === policy.version &&\n [policy.state, ...(policy.history ?? []).map((entry) => entry.state)].some(\n (state) => principalHeadMatchesReference(state, head),\n )\n );\n}\n\ntype StoredPolicyBundle = PrincipalPolicyBundleResponse | null;\n\nfunction bundleMeetingCheckpoint(\n bundle: StoredPolicyBundle,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): StoredPolicyBundle {\n return bundle &&\n principalPolicyHeadMeetsCheckpoint(bundle.currentState, checkpoint)\n ? bundle\n : null;\n}\n\nfunction assertSignerFingerprintMatches(error: string): void {\n if (error === \"fingerprint-mismatch\")\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n \"organization directory signer fingerprint does not match\",\n );\n}\n\nexport function createPolicyDirectoryLoader(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly currentPolicyReader: CurrentPrincipalPolicyReader;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n}): PolicyDirectoryLoader {\n const memo = new Map<boolean, Promise<VerifiedPolicyDirectory | null>>();\n const load = async (\n remote: boolean,\n ): Promise<VerifiedPolicyDirectory | null> => {\n const checkpoint = await new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\n let bundle = remote\n ? null\n : await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n bundle = bundleMeetingCheckpoint(bundle, checkpoint);\n bundle ??= await input.currentPolicyReader.getCurrentPrincipalPolicy(\n \"organization\",\n input.organizationId,\n );\n if (!bundle) return null;\n const signers = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in signers) {\n assertSignerFingerprintMatches(signers.error);\n return null;\n }\n const verified = await verifyOrganizationAdminPolicy({\n bundle,\n localCheckpoint: checkpoint,\n organizationId: input.organizationId,\n signerPublicKeys: signers.signerPublicKeys,\n });\n if (!verified.ok) throw verified.error;\n await publishVerifiedPrincipalPolicy({\n bundle,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n stillCurrent: input.stillCurrent,\n });\n let descriptor: OrganizationAuthorityDescriptor;\n try {\n descriptor = parseOrganizationAuthorityDescriptor(\n bundle.currentPayload.ciphertext,\n );\n } catch {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"organization directory payload is invalid\",\n );\n }\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization directory scope does not match\",\n );\n return { bundle, policy: verified.value, descriptor };\n };\n return (remote) => {\n let pending = memo.get(remote);\n if (!pending) {\n pending = load(remote);\n memo.set(remote, pending);\n }\n return pending;\n };\n}\n"]}
@@ -3,7 +3,7 @@ import { assertProjectionVerificationCurrent } from "../../../data/keyingProject
3
3
  import { preparePrincipalHistoryEvidencePage } from "../../../data/persistence/principalHistory/principalHistoryEvidencePersistence.js";
4
4
  import { PrincipalHistoryRepository } from "../../../data/persistence/principalHistory/principalHistoryRepository.js";
5
5
  import { principalHistoryStageProtection } from "../../../data/principals/principalHistoryStageProtection.js";
6
- import { collectPrincipalPolicySignerPublicKeys } from "../policyVerification.js";
6
+ import { collectPrincipalPolicySignerPublicKeys } from "../../../data/principals/principalPolicyVerification.js";
7
7
  import { loadPublicHistoryAuthority, publicHistoryAuthorityJson, publicHistoryAuthorityReference, } from "./publicPrincipalHistoryAuthority.js";
8
8
  export class PublicPrincipalHistoryPrefixDisconnectedError extends Error {
9
9
  verificationError;
@@ -1 +1 @@
1
- {"version":3,"file":"publicPrincipalHistoryPage.js","sourceRoot":"","sources":["publicPrincipalHistoryPage.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,gFAAgF,CAAC;AACrI,OAAO,EAAE,0BAA0B,EAAE,MAAM,uEAAuE,CAAC;AACnH,OAAO,EAAE,+BAA+B,EAAE,MAAM,0DAA0D,CAAC;AAC3G,OAAO,EAAE,sCAAsC,EAAE,MAAM,uBAAuB,CAAC;AAC/E,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,EAC1B,+BAA+B,GAChC,MAAM,mCAAmC,CAAC;AAM3C,MAAM,OAAO,6CAA8C,SAAQ,KAAK;IACjD;IAArB,YAAqB,iBAA0C;QAC7D,KAAK,CAAC,iBAAiB,CAAC,OAAO,CAAC,CAAC;QADd,sBAAiB,GAAjB,iBAAiB,CAAyB;QAE7D,IAAI,CAAC,IAAI,GAAG,+CAA+C,CAAC;IAC9D,CAAC;CACF;AAED,SAAS,0BAA0B,CACjC,KAAoC,EACpC,OAAkD;IAElD,IACE,KAAK,CAAC,YAAY;QAClB,OAAO,CAAC,IAAI,CACV,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC;YAC7B,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,IAAI,KAAK,OAAO,CAAC,CAC7D;QAED,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,4DAA4D,CAC7D,CAAC;IACJ,IACE,OAAO,CAAC,IAAI,CACV,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAC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ACF,IAAI,CAAC,MAAM,CAAC,EAAE;QAAE,MAAM,MAAM,CAAC,KAAK,CAAC;IACnC,MAAM,KAAK,GAAG,EAAE,GAAG,GAAG,EAAE,QAAQ,EAAE,MAAM,CAAC,KAAK,EAAE,CAAC;IACjD,MAAM,IAAI,0BAA0B,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,yBAAyB,CAC3E;QACE,KAAK,EAAE,KAAK;QACZ,QAAQ,EAAE,MAAM,mCAAmC,CAAC;YAClD,aAAa,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;YAC3C,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO;YACP,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;SACjC,CAAC;QACF,gBAAgB,EAAE,QAAQ,CAAC,KAAK,EAAE,QAAQ,IAAI,IAAI;QAClD,YAAY;KACb,CACF,CAAC;IACF,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO;QACL,GAAG,QAAQ;QACX,YAAY,EAAE,GAAG,CAAC,YAAY;QAC9B,KAAK;QACL,kBAAkB,EAAE,+BAA+B,CACjD,QAAQ,CAAC,kBAAkB,EAC3B,UAAU,CACX;QACD,aAAa,EAAE,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;KACnD,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyStateChainEntry,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicySnapshotPage } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHistoryStageProtection } from \"../../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../policyVerification\";\nimport {\n loadPublicHistoryAuthority,\n publicHistoryAuthorityJson,\n publicHistoryAuthorityReference,\n} from \"./publicPrincipalHistoryAuthority\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryTypes\";\n\nexport class PublicPrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PublicPrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\nfunction assertPublicAuthorityScope(\n input: PublicPrincipalHistoryOptions,\n entries: readonly PrincipalPolicyStateChainEntry[],\n): void {\n if (\n input.strictAdmins &&\n entries.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public Admins history must contain only direct admin users\",\n );\n if (\n entries.some(\n ({ state }) =>\n state.externalAuthority &&\n state.externalAuthority.principalId !== input.authorityGroupId,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history cites an authority outside its directory binding\",\n );\n}\n\nexport async function appendPublicPrincipalHistoryPage(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n page: PrincipalPolicySnapshotPage,\n): Promise<PublicPrincipalHistoryProgress> {\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n const complete = page.historyPage.nextAfterVersion === null;\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: page.currentState,\n projection: page.currentProjection,\n grants: page.currentGrants,\n });\n assertPublicAuthorityScope(input, entries);\n const predecessor = progress.verifier.getLatestAcceptedProjection();\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: page,\n // The page's first signer must be the identity the last accepted state\n // committed; nothing is pinned before the history reaches its head.\n predecessor,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Public history signer identity is unavailable or mismatched\",\n );\n const references = entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n );\n const externalAuthority = await loadPublicHistoryAuthority(input, references);\n assertProjectionVerificationCurrent(stillCurrent);\n const appended = await progress.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PublicPrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n assertProjectionVerificationCurrent(stillCurrent);\n const row = {\n id: progress.id,\n organizationId: input.organizationId,\n currentJson: publicHistoryAuthorityJson(\n publicHistoryAuthorityReference(progress.authorityReference, references),\n ),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const sealed = await progress.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.source.head,\n row,\n ),\n );\n if (!sealed.ok) throw sealed.error;\n const saved = { ...row, progress: sealed.value };\n await new PrincipalHistoryRepository(input.execSql).savePrincipalHistoryStage(\n {\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId: progress.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: progress.saved?.progress ?? null,\n stillCurrent,\n },\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n ...progress,\n afterVersion: row.afterVersion,\n saved,\n authorityReference: publicHistoryAuthorityReference(\n progress.authorityReference,\n references,\n ),\n completedHead: complete ? input.source.head : null,\n };\n}\n"]}
1
+ {"version":3,"file":"publicPrincipalHistoryPage.js","sourceRoot":"","sources":["publicPrincipalHistoryPage.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,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AAE,KAAK;QACZ,QAAQ,EAAE,MAAM,mCAAmC,CAAC;YAClD,aAAa,EAAE,QAAQ,CAAC,KAAK,CAAC,aAAa;YAC3C,OAAO,EAAE,QAAQ,CAAC,OAAO;YACzB,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO;YACP,KAAK,EAAE,QAAQ,CAAC,KAAK,CAAC,UAAU;SACjC,CAAC;QACF,gBAAgB,EAAE,QAAQ,CAAC,KAAK,EAAE,QAAQ,IAAI,IAAI;QAClD,YAAY;KACb,CACF,CAAC;IACF,mCAAmC,CAAC,YAAY,CAAC,CAAC;IAClD,OAAO;QACL,GAAG,QAAQ;QACX,YAAY,EAAE,GAAG,CAAC,YAAY;QAC9B,KAAK;QACL,kBAAkB,EAAE,+BAA+B,CACjD,QAAQ,CAAC,kBAAkB,EAC3B,UAAU,CACX;QACD,aAAa,EAAE,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI;KACnD,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyStateChainEntry,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicySnapshotPage } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../../data/persistence/principalHistory/principalHistoryEvidencePersistence\";\nimport { PrincipalHistoryRepository } from \"../../../data/persistence/principalHistory/principalHistoryRepository\";\nimport { principalHistoryStageProtection } from \"../../../data/principals/principalHistoryStageProtection\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../../../data/principals/principalPolicyVerification\";\nimport {\n loadPublicHistoryAuthority,\n publicHistoryAuthorityJson,\n publicHistoryAuthorityReference,\n} from \"./publicPrincipalHistoryAuthority\";\nimport type {\n PublicPrincipalHistoryOptions,\n PublicPrincipalHistoryProgress,\n} from \"./publicPrincipalHistoryTypes\";\n\nexport class PublicPrincipalHistoryPrefixDisconnectedError extends Error {\n constructor(readonly verificationError: KeyingVerificationError) {\n super(verificationError.message);\n this.name = \"PublicPrincipalHistoryPrefixDisconnectedError\";\n }\n}\n\nfunction assertPublicAuthorityScope(\n input: PublicPrincipalHistoryOptions,\n entries: readonly PrincipalPolicyStateChainEntry[],\n): void {\n if (\n input.strictAdmins &&\n entries.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Public Admins history must contain only direct admin users\",\n );\n if (\n entries.some(\n ({ state }) =>\n state.externalAuthority &&\n state.externalAuthority.principalId !== input.authorityGroupId,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Public history cites an authority outside its directory binding\",\n );\n}\n\nexport async function appendPublicPrincipalHistoryPage(\n input: PublicPrincipalHistoryOptions,\n progress: PublicPrincipalHistoryProgress,\n page: PrincipalPolicySnapshotPage,\n): Promise<PublicPrincipalHistoryProgress> {\n const stillCurrent = () => !input.signal?.aborted && input.stillCurrent();\n const complete = page.historyPage.nextAfterVersion === null;\n const entries = [...page.previousStates];\n if (complete)\n entries.push({\n state: page.currentState,\n projection: page.currentProjection,\n grants: page.currentGrants,\n });\n assertPublicAuthorityScope(input, entries);\n const predecessor = progress.verifier.getLatestAcceptedProjection();\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: page,\n // The page's first signer must be the identity the last accepted state\n // committed; nothing is pinned before the history reaches its head.\n predecessor,\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n });\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Public history signer identity is unavailable or mismatched\",\n );\n const references = entries.flatMap(({ state }) =>\n state.externalAuthority ? [state.externalAuthority] : [],\n );\n const externalAuthority = await loadPublicHistoryAuthority(input, references);\n assertProjectionVerificationCurrent(stillCurrent);\n const appended = await progress.verifier.append({\n entries,\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) {\n if (appended.error.code === \"stale_predecessor\")\n throw new PublicPrincipalHistoryPrefixDisconnectedError(appended.error);\n throw appended.error;\n }\n assertProjectionVerificationCurrent(stillCurrent);\n const row = {\n id: progress.id,\n organizationId: input.organizationId,\n currentJson: publicHistoryAuthorityJson(\n publicHistoryAuthorityReference(progress.authorityReference, references),\n ),\n afterVersion: appended.value.throughVersion - (complete ? 1 : 0),\n complete,\n };\n const sealed = await progress.verifier.exportProgress(\n await principalHistoryStageProtection(\n input.protection,\n input.source.head,\n row,\n ),\n );\n if (!sealed.ok) throw sealed.error;\n const saved = { ...row, progress: sealed.value };\n await new PrincipalHistoryRepository(input.execSql).savePrincipalHistoryStage(\n {\n stage: saved,\n evidence: await preparePrincipalHistoryEvidencePage({\n indexRootHash: appended.value.indexRootHash,\n scopeId: progress.scopeId,\n organizationId: input.organizationId,\n entries,\n nodes: appended.value.indexNodes,\n }),\n previousProgress: progress.saved?.progress ?? null,\n stillCurrent,\n },\n );\n assertProjectionVerificationCurrent(stillCurrent);\n return {\n ...progress,\n afterVersion: row.afterVersion,\n saved,\n authorityReference: publicHistoryAuthorityReference(\n progress.authorityReference,\n references,\n ),\n completedHead: complete ? input.source.head : null,\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import type { PrincipalPolicyPageCurrent } from "../../internal/api-client/index.js";
2
2
  import { type PrincipalPolicyResolveRequest, type ResolvedPrincipalPolicyEvidence } from "../../data/keyingProjectionVerification/types.js";
3
3
  import type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
4
- import type { SecurityIncidentReporter } from "../../data/shared/securityIncidents.js";
4
+ import { type SecurityIncidentReporter } from "../../data/shared/securityIncidents.js";
5
5
  import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
6
6
  import type { TrustedUserIdentityResolver } from "../../data/trustedUserIdentity/index.js";
7
7
  import type { RecoveredPrincipalHistoryPage } from "./historyRecovery/loadRecoveredPrincipalHistoryPage.js";
@@ -1,8 +1,8 @@
1
1
  import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
- import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
3
2
  import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectionVerification/types.js";
4
3
  import { getOrCreatePrincipalPolicyCoordinator, } from "../../data/principals/principalPolicyCoordinator.js";
5
4
  import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
5
+ import { runWithSecurityIncidentReporting, } from "../../data/shared/securityIncidents.js";
6
6
  import { PrincipalHistoryRecoveryRaceError, PrincipalPolicyHistoryReadError, } from "./historyRecovery/principalHistoryRecoveryTypes.js";
7
7
  import { apiPrincipalPolicyPageReader, } from "./principalPolicyHistoryReader.js";
8
8
  import { createPrincipalCurrentRecoveryBatch } from "./recoveryOperation/principalCurrentRecoveryBatch.js";
@@ -1 +1 @@
1
- {"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,gCAAgC,EAAE,MAAM,+CAA+C,CAAC;AACjG,OAAO,EACL,mCAAmC,GAGpC,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EACL,qCAAqC,GAEtC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAK/F,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAChC,MAAM,iDAAiD,CAAC;AAEzD,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,mDAAmD,CAAC;AACxG,OAAO,EAAE,mCAAmC,EAAE,MAAM,sDAAsD,CAAC;AAC3G,OAAO,EAAE,0BAA0B,EAAE,MAAM,2CAA2C,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CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyResolveRequest,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport {\n getOrCreatePrincipalPolicyCoordinator,\n type PrincipalPolicyCoordinator,\n} from \"../../data/principals/principalPolicyCoordinator\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { RecoveredPrincipalHistoryPage } from \"./historyRecovery/loadRecoveredPrincipalHistoryPage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./historyRecovery/principalHistoryRecoveryTypes\";\nimport type { ScopedPrincipalPolicyRecovery } from \"./historyRecovery/recoverScopedPrincipalPolicyHistory\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyHistoryReader,\n} from \"./principalPolicyHistoryReader\";\nimport { createPrincipalCurrentRecoveryBatch } from \"./recoveryOperation/principalCurrentRecoveryBatch\";\nimport { recoverWithPrincipalLocalPreference } from \"./recoveryOperation/principalRecoveryLocalPreference\";\nimport { resumeAfterSupersededStage } from \"./recoveryOperation/supersededStageResume\";\n\n/**\n * The slices of one runtime snapshot a `PrincipalPolicyService` reads. Each\n * service method reads them when it is called and its resolvers per request,\n * as the snapshot's other consumers do. The lease is the snapshot's bound\n * history custody; the service never binds one itself.\n */\nexport interface PrincipalPolicyCollaborators {\n readonly apiClient: Partial<PrincipalPolicyHistoryReader>;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: {\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly log?: ((message: string) => void) | undefined;\n };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface ResolvedPrincipalPolicyCurrent\n extends ResolvedPrincipalPolicyEvidence {\n readonly current: PrincipalPolicyPageCurrent;\n /** Rows end at the selected reference; current/policy may describe a newer recovered head. */\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\nexport interface PrincipalPolicyCurrentRequest\n extends Omit<PrincipalPolicyResolveRequest, \"reference\"> {\n readonly reference?: PrincipalPolicyResolveRequest[\"reference\"] | undefined;\n /** A read-model caller has selected this exact signed head; not a freshness read. */\n readonly preferLocalCurrent?: boolean | undefined;\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\nexport type PrincipalPolicyCurrentResolver = (\n input: PrincipalPolicyCurrentRequest,\n) => Promise<ResolvedPrincipalPolicyCurrent>;\n\ntype PrincipalCurrentRecoveryBatch = ReturnType<\n typeof createPrincipalCurrentRecoveryBatch\n>;\n\n/**\n * Operation batches belong to the database's coordinator, keyed by the\n * operation token, so every resolver and warmer one operation creates for that\n * database shares one authenticated view. A batch dies with its token (the end\n * of the pass or workflow) and its entries with any organization hint.\n */\nconst operationBatches = new WeakMap<\n PrincipalPolicyCoordinator,\n WeakMap<object, PrincipalCurrentRecoveryBatch>\n>();\n\nfunction operationRecoveryBatch(\n coordinator: PrincipalPolicyCoordinator,\n operation: object | undefined,\n): PrincipalCurrentRecoveryBatch {\n if (!operation) return createPrincipalCurrentRecoveryBatch();\n let batches = operationBatches.get(coordinator);\n if (!batches) {\n batches = new WeakMap();\n operationBatches.set(coordinator, batches);\n }\n let batch = batches.get(operation);\n if (!batch) {\n batch = createPrincipalCurrentRecoveryBatch();\n batches.set(operation, batch);\n }\n return batch;\n}\n\n/** One recovery attempt for a resolver request through the operation's batch. */\nfunction recoverPolicyCurrent(\n batch: ReturnType<typeof createPrincipalCurrentRecoveryBatch>,\n options: Parameters<\n ReturnType<typeof createPrincipalCurrentRecoveryBatch>[\"discover\"]\n >[0],\n input: PrincipalPolicyCurrentRequest,\n): Promise<ScopedPrincipalPolicyRecovery> {\n return input.reference\n ? recoverWithPrincipalLocalPreference(\n batch.recover,\n {\n ...options,\n reference: input.reference,\n historyPage: input.historyPage,\n },\n input.preferLocalCurrent === true || input.preferLocalHistory === true,\n input.preferLocalHistory === true,\n )\n : batch.discover(options);\n}\n\n/** Keep current artifacts with their verified evidence and private snapshot lifetime. */\nexport function createPrincipalPolicyCurrentResolver(\n policies: PrincipalPolicyCollaborators,\n): PrincipalPolicyCurrentResolver | undefined {\n const lease = policies.withPrincipalHistoryProtection;\n const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);\n if (!lease || !historyReader) return undefined;\n const coordinator = getOrCreatePrincipalPolicyCoordinator(\n policies.infra.execSql,\n );\n return (input) =>\n coordinator.queueRecovery(input.organizationId, () =>\n runWithSecurityIncidentReporting(\n policies.util.reportSecurityIncident,\n {\n objectId: input.reference?.principalId ?? input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n assertHistoryPageRequest(input);\n const offline = policies.state?.online === false;\n try {\n const options = {\n historyReader,\n execSql: policies.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const result = await resumeAfterSupersededStage(\n () =>\n recoverPolicyCurrent(\n operationRecoveryBatch(coordinator, input.recoveryBatch),\n options,\n input,\n ),\n stillCurrent,\n );\n // Reused evidence stays bound to every producer lifetime.\n const resultCurrent = () =>\n stillCurrent() && result.stillCurrent();\n assertProjectionVerificationCurrent(resultCurrent);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\n stillCurrent: resultCurrent,\n };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n error instanceof PrincipalHistoryRecoveryRaceError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n\nfunction assertHistoryPageRequest(input: PrincipalPolicyCurrentRequest) {\n if (!input.historyPage) return;\n const before = input.historyPage.beforeVersion;\n if (\n !input.reference ||\n (before !== undefined &&\n (!Number.isSafeInteger(before) ||\n before <= 1 ||\n before > input.reference.version + 1))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"History display requires a selected head and an in-range cursor\",\n );\n}\n"]}
1
+ {"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,mCAAmC,GAGpC,MAAM,+CAA+C,CAAC;AAEvD,OAAO,EACL,qCAAqC,GAEtC,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EACL,gCAAgC,GAEjC,MAAM,qCAAqC,CAAC;AAI7C,OAAO,EACL,iCAAiC,EACjC,+BAA+B,GAChC,MAAM,iDAAiD,CAAC;AAEzD,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,mCAAmC,EAAE,MAAM,mDAAmD,CAAC;AACxG,OAAO,EAAE,mCAAmC,EAAE,MAAM,sDAAsD,CAAC;AAC3G,OAAO,EAAE,0BAA0B,EAAE,MAAM,2CAA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ACN,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyResolveRequest,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport {\n getOrCreatePrincipalPolicyCoordinator,\n type PrincipalPolicyCoordinator,\n} from \"../../data/principals/principalPolicyCoordinator\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport {\n runWithSecurityIncidentReporting,\n type SecurityIncidentReporter,\n} from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { RecoveredPrincipalHistoryPage } from \"./historyRecovery/loadRecoveredPrincipalHistoryPage\";\nimport {\n PrincipalHistoryRecoveryRaceError,\n PrincipalPolicyHistoryReadError,\n} from \"./historyRecovery/principalHistoryRecoveryTypes\";\nimport type { ScopedPrincipalPolicyRecovery } from \"./historyRecovery/recoverScopedPrincipalPolicyHistory\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyHistoryReader,\n} from \"./principalPolicyHistoryReader\";\nimport { createPrincipalCurrentRecoveryBatch } from \"./recoveryOperation/principalCurrentRecoveryBatch\";\nimport { recoverWithPrincipalLocalPreference } from \"./recoveryOperation/principalRecoveryLocalPreference\";\nimport { resumeAfterSupersededStage } from \"./recoveryOperation/supersededStageResume\";\n\n/**\n * The slices of one runtime snapshot a `PrincipalPolicyService` reads. Each\n * service method reads them when it is called and its resolvers per request,\n * as the snapshot's other consumers do. The lease is the snapshot's bound\n * history custody; the service never binds one itself.\n */\nexport interface PrincipalPolicyCollaborators {\n readonly apiClient: Partial<PrincipalPolicyHistoryReader>;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: {\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly log?: ((message: string) => void) | undefined;\n };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\nexport interface ResolvedPrincipalPolicyCurrent\n extends ResolvedPrincipalPolicyEvidence {\n readonly current: PrincipalPolicyPageCurrent;\n /** Rows end at the selected reference; current/policy may describe a newer recovered head. */\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\nexport interface PrincipalPolicyCurrentRequest\n extends Omit<PrincipalPolicyResolveRequest, \"reference\"> {\n readonly reference?: PrincipalPolicyResolveRequest[\"reference\"] | undefined;\n /** A read-model caller has selected this exact signed head; not a freshness read. */\n readonly preferLocalCurrent?: boolean | undefined;\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\nexport type PrincipalPolicyCurrentResolver = (\n input: PrincipalPolicyCurrentRequest,\n) => Promise<ResolvedPrincipalPolicyCurrent>;\n\ntype PrincipalCurrentRecoveryBatch = ReturnType<\n typeof createPrincipalCurrentRecoveryBatch\n>;\n\n/**\n * Operation batches belong to the database's coordinator, keyed by the\n * operation token, so every resolver and warmer one operation creates for that\n * database shares one authenticated view. A batch dies with its token (the end\n * of the pass or workflow) and its entries with any organization hint.\n */\nconst operationBatches = new WeakMap<\n PrincipalPolicyCoordinator,\n WeakMap<object, PrincipalCurrentRecoveryBatch>\n>();\n\nfunction operationRecoveryBatch(\n coordinator: PrincipalPolicyCoordinator,\n operation: object | undefined,\n): PrincipalCurrentRecoveryBatch {\n if (!operation) return createPrincipalCurrentRecoveryBatch();\n let batches = operationBatches.get(coordinator);\n if (!batches) {\n batches = new WeakMap();\n operationBatches.set(coordinator, batches);\n }\n let batch = batches.get(operation);\n if (!batch) {\n batch = createPrincipalCurrentRecoveryBatch();\n batches.set(operation, batch);\n }\n return batch;\n}\n\n/** One recovery attempt for a resolver request through the operation's batch. */\nfunction recoverPolicyCurrent(\n batch: ReturnType<typeof createPrincipalCurrentRecoveryBatch>,\n options: Parameters<\n ReturnType<typeof createPrincipalCurrentRecoveryBatch>[\"discover\"]\n >[0],\n input: PrincipalPolicyCurrentRequest,\n): Promise<ScopedPrincipalPolicyRecovery> {\n return input.reference\n ? recoverWithPrincipalLocalPreference(\n batch.recover,\n {\n ...options,\n reference: input.reference,\n historyPage: input.historyPage,\n },\n input.preferLocalCurrent === true || input.preferLocalHistory === true,\n input.preferLocalHistory === true,\n )\n : batch.discover(options);\n}\n\n/** Keep current artifacts with their verified evidence and private snapshot lifetime. */\nexport function createPrincipalPolicyCurrentResolver(\n policies: PrincipalPolicyCollaborators,\n): PrincipalPolicyCurrentResolver | undefined {\n const lease = policies.withPrincipalHistoryProtection;\n const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);\n if (!lease || !historyReader) return undefined;\n const coordinator = getOrCreatePrincipalPolicyCoordinator(\n policies.infra.execSql,\n );\n return (input) =>\n coordinator.queueRecovery(input.organizationId, () =>\n runWithSecurityIncidentReporting(\n policies.util.reportSecurityIncident,\n {\n objectId: input.reference?.principalId ?? input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n assertHistoryPageRequest(input);\n const offline = policies.state?.online === false;\n try {\n const options = {\n historyReader,\n execSql: policies.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,\n stillCurrent,\n };\n const result = await resumeAfterSupersededStage(\n () =>\n recoverPolicyCurrent(\n operationRecoveryBatch(coordinator, input.recoveryBatch),\n options,\n input,\n ),\n stillCurrent,\n );\n // Reused evidence stays bound to every producer lifetime.\n const resultCurrent = () =>\n stillCurrent() && result.stillCurrent();\n assertProjectionVerificationCurrent(resultCurrent);\n return {\n current: result.current,\n organizationId: input.organizationId,\n policy: result.policy,\n dependencies: result.dependencies,\n historyPage: result.historyPage,\n stillCurrent: resultCurrent,\n };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n error instanceof PrincipalHistoryRecoveryRaceError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n\nfunction assertHistoryPageRequest(input: PrincipalPolicyCurrentRequest) {\n if (!input.historyPage) return;\n const before = input.historyPage.beforeVersion;\n if (\n !input.reference ||\n (before !== undefined &&\n (!Number.isSafeInteger(before) ||\n before <= 1 ||\n before > input.reference.version + 1))\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"History display requires a selected head and an in-range cursor\",\n );\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
- import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
3
2
  import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectionVerification/types.js";
4
3
  import { getOrCreatePrincipalPolicyCoordinator } from "../../data/principals/principalPolicyCoordinator.js";
5
4
  import { ProjectionDependencyUnavailableError } from "../../data/shared/dependencyUnavailable.js";
5
+ import { runWithSecurityIncidentReporting } from "../../data/shared/securityIncidents.js";
6
6
  import { PrincipalPolicyHistoryReadError } from "./historyRecovery/principalHistoryRecoveryTypes.js";
7
7
  import { apiProjectionPolicyHistoryReader } from "./principalPolicyHistoryReader.js";
8
8
  import { recoverProjectionPolicyHistory, } from "./publicHistory/recoverProjectionPolicyHistory.js";
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeProjectionPolicyRecovery.js","sourceRoot":"","sources":["runtimeProjectionPolicyRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE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gCAAgC,CAC9B,aAAa,CAAC,IAAI,CAAC,sBAAsB,EACzC;QACE,QAAQ,EAAE,KAAK,CAAC,cAAc;QAC9B,UAAU,EAAE,WAAW;QACvB,SAAS,EAAE,8BAA8B;QACzC,cAAc,EAAE,KAAK,CAAC,cAAc;KACrC,EACD,GAAG,EAAE,CACH,KAAK,CAAC,KAAK,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,YAAY,EAAE,EAAE,EAAE;QACzD,MAAM,YAAY,GAAG,GAAG,EAAE,CACxB,YAAY,EAAE,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,CAAC;QACrD,mCAAmC,CAAC,YAAY,CAAC,CAAC;QAClD,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,MAAM,yBAAyB,CAAC;gBAC/C,GAAG,KAAK;gBACR,aAAa;gBACb,OAAO,EAAE,aAAa,CAAC,KAAK,CAAC,OAAO;gBACpC,UAAU;gBACV,YAAY;gBACZ,OAAO,EAAE,aAAa,CAAC,KAAK,EAAE,MAAM,KAAK,KAAK;gBAC9C,0BAA0B,EACxB,aAAa,CAAC,0BAA0B;aAC3C,CAAC,CAAC;YACH,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,CAAC;QACpC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,IACE,KAAK,YAAY,+BAA+B;gBAChD,CAAC,KAAK,YAAY,uBAAuB;oBACvC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;gBAEtC,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACF,CAAC;AACN,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { PrincipalPolicyHistoryReadError } from \"./historyRecovery/principalHistoryRecoveryTypes\";\nimport { apiProjectionPolicyHistoryReader } from \"./principalPolicyHistoryReader\";\nimport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./publicHistory/recoverProjectionPolicyHistory\";\nimport { isPrincipalRecoveryOutage } from \"./recoveryOperation/principalRecoveryOutage\";\nimport type { PrincipalPolicyCollaborators } from \"./runtimePolicyRecovery\";\n\nasync function recoverWithOutageFallback(\n options: ProjectionPolicyHistoryRecoveryOptions,\n) {\n try {\n return await recoverProjectionPolicyHistory(options);\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (options.offline || !isPrincipalRecoveryOutage(error)) throw error;\n return recoverProjectionPolicyHistory({ ...options, offline: true });\n }\n}\n\nexport function createProjectionPolicyHistoryResolver(\n collaborators: PrincipalPolicyCollaborators,\n): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n const lease = collaborators.withPrincipalHistoryProtection;\n const historyReader = apiProjectionPolicyHistoryReader(\n collaborators.apiClient,\n );\n if (!lease || !historyReader) return undefined;\n return (input) =>\n getOrCreatePrincipalPolicyCoordinator(\n collaborators.infra.execSql,\n ).queueRecovery(input.organizationId, () =>\n runWithSecurityIncidentReporting(\n collaborators.util.reportSecurityIncident,\n {\n objectId: input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.projection.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n try {\n const policies = await recoverWithOutageFallback({\n ...input,\n historyReader,\n execSql: collaborators.infra.execSql,\n protection,\n stillCurrent,\n offline: collaborators.state?.online === false,\n resolveTrustedUserIdentity:\n collaborators.resolveTrustedUserIdentity,\n });\n return { policies, stillCurrent };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"runtimeProjectionPolicyRecovery.js","sourceRoot":"","sources":["runtimeProjectionPolicyRecovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EACL,mCAAmC,GAEpC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AACzG,OAAO,EAAE,oCAAoC,EAAE,MAAM,yCAAyC,CAAC;AAC/F,OAAO,EAAE,gCAAgC,EAAE,MAAM,qCAAqC,CAAC;AACvF,OAAO,EAAE,+BAA+B,EAAE,MAAM,iDAAiD,CAAC;AAClG,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EAEL,8BAA8B,GAC/B,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,yBAAyB,EAAE,MAAM,6CAA6C,CAAC;AAGxF,KAAK,UAAU,yBAAyB,CACtC,OAA+C;IAE/C,IAAI,CAAC;QACH,OAAO,MAAM,8BAA8B,CAAC,OAAO,CAAC,CAAC;IACvD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC;QAC1D,IAAI,OAAO,CAAC,OAAO,IAAI,CAAC,yBAAyB,CAAC,KAAK,CAAC;YAAE,MAAM,KAAK,CAAC;QACtE,OAAO,8BAA8B,CAAC,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,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,CAAC;YACf,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,IACE,KAAK,YAAY,+BAA+B;gBAChD,CAAC,KAAK,YAAY,uBAAuB;oBACvC,KAAK,CAAC,IAAI,KAAK,oBAAoB,CAAC;gBAEtC,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;YAChE,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC,CAAC,CACL,CACF,CAAC;AACN,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport {\n assertProjectionVerificationCurrent,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { getOrCreatePrincipalPolicyCoordinator } from \"../../data/principals/principalPolicyCoordinator\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/shared/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/shared/securityIncidents\";\nimport { PrincipalPolicyHistoryReadError } from \"./historyRecovery/principalHistoryRecoveryTypes\";\nimport { apiProjectionPolicyHistoryReader } from \"./principalPolicyHistoryReader\";\nimport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./publicHistory/recoverProjectionPolicyHistory\";\nimport { isPrincipalRecoveryOutage } from \"./recoveryOperation/principalRecoveryOutage\";\nimport type { PrincipalPolicyCollaborators } from \"./runtimePolicyRecovery\";\n\nasync function recoverWithOutageFallback(\n options: ProjectionPolicyHistoryRecoveryOptions,\n) {\n try {\n return await recoverProjectionPolicyHistory(options);\n } catch (error) {\n assertProjectionVerificationCurrent(options.stillCurrent);\n if (options.offline || !isPrincipalRecoveryOutage(error)) throw error;\n return recoverProjectionPolicyHistory({ ...options, offline: true });\n }\n}\n\nexport function createProjectionPolicyHistoryResolver(\n collaborators: PrincipalPolicyCollaborators,\n): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n const lease = collaborators.withPrincipalHistoryProtection;\n const historyReader = apiProjectionPolicyHistoryReader(\n collaborators.apiClient,\n );\n if (!lease || !historyReader) return undefined;\n return (input) =>\n getOrCreatePrincipalPolicyCoordinator(\n collaborators.infra.execSql,\n ).queueRecovery(input.organizationId, () =>\n runWithSecurityIncidentReporting(\n collaborators.util.reportSecurityIncident,\n {\n objectId: input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.projection.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n try {\n const policies = await recoverWithOutageFallback({\n ...input,\n historyReader,\n execSql: collaborators.infra.execSql,\n protection,\n stillCurrent,\n offline: collaborators.state?.online === false,\n resolveTrustedUserIdentity:\n collaborators.resolveTrustedUserIdentity,\n });\n return { policies, stillCurrent };\n } catch (error) {\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n error instanceof PrincipalPolicyHistoryReadError ||\n (error instanceof KeyingVerificationError &&\n error.code === \"missing_dependency\")\n )\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n }\n }),\n ),\n );\n}\n"]}
@@ -1,8 +1,9 @@
1
+ export { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
1
2
  export { bootstrapRootContainer } from "./bootstrapRootContainer.js";
2
3
  export { type CreateOrganizationApi, type CreateOrganizationInput, createOrganization, removeNativeSubscriptionRestoreProvisioningAttempt, } from "./organizationCreation/createOrganization.js";
3
4
  export { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "./organizationCreation/organizationProvisioningAttempt.js";
4
5
  export { verifyOrganizationReplacementResponse } from "./organizationCreation/organizationReplacementVerification.js";
5
- export { buildInitialOrganizationPolicyRequest, type ProvisionedSystemContainerSpec, } from "./organizationProvisioning.js";
6
+ export type { ProvisionedSystemContainerSpec } from "./organizationProvisioning.js";
6
7
  export { persistRegistrationBootstrap } from "./persistRegistrationBootstrap.js";
7
8
  export { type RegisterIdentityInput, type RegistrationApi, registerIdentity, } from "./registerIdentity.js";
8
9
  export { principalPolicyBundleFromInitialGroupRequest } from "./registrationPrincipalPolicyPersistence.js";
@@ -1,8 +1,8 @@
1
+ export { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
1
2
  export { bootstrapRootContainer } from "./bootstrapRootContainer.js";
2
3
  export { createOrganization, removeNativeSubscriptionRestoreProvisioningAttempt, } from "./organizationCreation/createOrganization.js";
3
4
  export { loadOrganizationReplacementFinalizationRequest, removeOrganizationProvisioningAttempt, } from "./organizationCreation/organizationProvisioningAttempt.js";
4
5
  export { verifyOrganizationReplacementResponse } from "./organizationCreation/organizationReplacementVerification.js";
5
- export { buildInitialOrganizationPolicyRequest, } from "./organizationProvisioning.js";
6
6
  export { persistRegistrationBootstrap } from "./persistRegistrationBootstrap.js";
7
7
  export { registerIdentity, } from "./registerIdentity.js";
8
8
  export { principalPolicyBundleFromInitialGroupRequest } from "./registrationPrincipalPolicyPersistence.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAGL,kBAAkB,EAClB,kDAAkD,GACnD,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,qCAAqC,EAAE,MAAM,4DAA4D,CAAC;AACnH,OAAO,EACL,qCAAqC,GAEtC,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAGL,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,4CAA4C,EAAE,MAAM,0CAA0C,CAAC;AACxG,OAAO,EACL,kCAAkC,GAEnC,MAAM,yBAAyB,CAAC","sourcesContent":["export { bootstrapRootContainer } from \"./bootstrapRootContainer\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationCreation/createOrganization\";\nexport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"./organizationCreation/organizationProvisioningAttempt\";\nexport { verifyOrganizationReplacementResponse } from \"./organizationCreation/organizationReplacementVerification\";\nexport {\n buildInitialOrganizationPolicyRequest,\n type ProvisionedSystemContainerSpec,\n} from \"./organizationProvisioning\";\nexport { persistRegistrationBootstrap } from \"./persistRegistrationBootstrap\";\nexport {\n type RegisterIdentityInput,\n type RegistrationApi,\n registerIdentity,\n} from \"./registerIdentity\";\nexport { principalPolicyBundleFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nexport {\n createInitialRootMetadataBootstrap,\n type InitialRootMetadataBootstrap,\n} from \"./rootMetadataBootstrap\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,sBAAsB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,EAGL,kBAAkB,EAClB,kDAAkD,GACnD,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,8CAA8C,EAC9C,qCAAqC,GACtC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,qCAAqC,EAAE,MAAM,4DAA4D,CAAC;AAEnH,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAGL,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,4CAA4C,EAAE,MAAM,0CAA0C,CAAC;AACxG,OAAO,EACL,kCAAkC,GAEnC,MAAM,yBAAyB,CAAC","sourcesContent":["export { buildInitialOrganizationPolicyRequest } from \"../../data/principals/organizationPolicyRequest\";\nexport { bootstrapRootContainer } from \"./bootstrapRootContainer\";\nexport {\n type CreateOrganizationApi,\n type CreateOrganizationInput,\n createOrganization,\n removeNativeSubscriptionRestoreProvisioningAttempt,\n} from \"./organizationCreation/createOrganization\";\nexport {\n loadOrganizationReplacementFinalizationRequest,\n removeOrganizationProvisioningAttempt,\n} from \"./organizationCreation/organizationProvisioningAttempt\";\nexport { verifyOrganizationReplacementResponse } from \"./organizationCreation/organizationReplacementVerification\";\nexport type { ProvisionedSystemContainerSpec } from \"./organizationProvisioning\";\nexport { persistRegistrationBootstrap } from \"./persistRegistrationBootstrap\";\nexport {\n type RegisterIdentityInput,\n type RegistrationApi,\n registerIdentity,\n} from \"./registerIdentity\";\nexport { principalPolicyBundleFromInitialGroupRequest } from \"./registrationPrincipalPolicyPersistence\";\nexport {\n createInitialRootMetadataBootstrap,\n type InitialRootMetadataBootstrap,\n} from \"./rootMetadataBootstrap\";\n"]}
@@ -1,5 +1,4 @@
1
- import { type EncapsulationKeyPair, type ReferencedPrincipalHead, type SigningKeyPair } from "../../internal/crypto/index.js";
2
- import type { RegistrationRequest } from "../../internal/validators/request/index.js";
1
+ import { type EncapsulationKeyPair, type SigningKeyPair } from "../../internal/crypto/index.js";
3
2
  import type { OrganizationProvisioningArtifacts } from "./organizationProvisioningArtifacts.js";
4
3
  import { type ProvisionedSystemContainerSpec } from "./provisioningBootstrapBuilders.js";
5
4
  export type { OrganizationProvisioningArtifacts } from "./organizationProvisioningArtifacts.js";
@@ -27,15 +26,5 @@ export interface OrganizationProvisioningArtifactsInput {
27
26
  signingKeyPair: SigningKeyPair;
28
27
  userId: string;
29
28
  }
30
- export declare function buildInitialOrganizationPolicyRequest(input: {
31
- identityTrustDomain: string;
32
- adminGroupId: string;
33
- groupHeads: readonly ReferencedPrincipalHead[];
34
- encapsulationPublicKey: Uint8Array;
35
- memberGroupId: string;
36
- organizationId: string;
37
- signingKeyPair: SigningKeyPair;
38
- userId: string;
39
- }): Promise<RegistrationRequest["initialOrganizationPolicy"]>;
40
29
  /** Builds the signed artifacts shared by registration and org creation. */
41
30
  export declare function buildOrganizationProvisioningArtifacts(input: OrganizationProvisioningArtifactsInput): Promise<OrganizationProvisioningArtifacts>;
@@ -1,82 +1,14 @@
1
1
  // Registration and additional-organization creation build and persist an
2
2
  // organization's founding policies, system containers, and profile documents
3
3
  // through this module.
4
- import { buildPrincipalStateSigningInput, generateKemSeedAndKeyPair, signPrincipalState, toFingerprint, wrapDekForRecipients, } from "../../internal/crypto/index.js";
5
- import { bytesToBase64 } from "../../internal/encoding/index.js";
6
- import { encodeOrganizationAuthorityDescriptor } from "../../data/principalContracts/organizationAuthorityDescriptor.js";
7
- import { createPrincipalProjectionMember } from "../../data/principalContracts/principalIdentityCommitments.js";
4
+ import { toFingerprint, } from "../../internal/crypto/index.js";
5
+ import { buildInitialOrganizationPolicyRequest } from "../../data/principals/organizationPolicyRequest.js";
8
6
  import { resolveDocumentCreateAuthor } from "../documents/index.js";
9
7
  import { groupPolicyMutationHead } from "../organizations/groupPolicy/groupPolicyMutationHead.js";
10
8
  import { buildInitialGroupPolicyRequest, buildInitialMemberGroupPolicyRequest, } from "../organizations/principalPolicy/index.js";
11
9
  import { buildInitialOrganizationMetadataBootstrap, buildInitialRootProvisioning, buildInitialRosterProfileBootstrap, buildInitialSystemContainerBootstrap, } from "./provisioningBootstrapBuilders.js";
12
10
  import { createInitialRootMetadataBootstrap } from "./rootMetadataBootstrap.js";
13
11
  export { persistOrganizationProvisioningState } from "./organizationProvisioningPersistence.js";
14
- export async function buildInitialOrganizationPolicyRequest(input) {
15
- const organizationKem = generateKemSeedAndKeyPair();
16
- const signerUserKeyFingerprint = await toFingerprint(input.signingKeyPair.signingPublicKey);
17
- const userEncapsulationKeyFingerprint = await toFingerprint(input.encapsulationPublicKey);
18
- const projection = [
19
- await createPrincipalProjectionMember({
20
- userId: input.userId,
21
- identityTrustDomain: input.identityTrustDomain,
22
- signingPublicKey: input.signingKeyPair.signingPublicKey,
23
- encapsulationPublicKey: input.encapsulationPublicKey,
24
- }, "admin"),
25
- ];
26
- const payloadCiphertext = encodeOrganizationAuthorityDescriptor({
27
- version: 2,
28
- organizationId: input.organizationId,
29
- adminGroupId: input.adminGroupId,
30
- memberGroupId: input.memberGroupId,
31
- groupHeads: input.groupHeads.map((head) => {
32
- if (head.principalType !== "group") {
33
- throw new Error("Organization directory can contain only group heads");
34
- }
35
- return { ...head, principalType: "group" };
36
- }),
37
- });
38
- const [memberEnvelope] = await wrapDekForRecipients(organizationKem.secretKey, [input.encapsulationPublicKey]);
39
- if (!memberEnvelope) {
40
- throw new Error("Failed to wrap organization key for registering user");
41
- }
42
- const memberEnvelopes = [
43
- {
44
- userId: input.userId,
45
- memberKeyFingerprint: userEncapsulationKeyFingerprint,
46
- kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),
47
- wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),
48
- },
49
- ];
50
- const state = await signPrincipalState(await buildPrincipalStateSigningInput({
51
- principalType: "organization",
52
- principalId: input.organizationId,
53
- version: 1,
54
- prevStateHash: null,
55
- keyEpoch: 1,
56
- encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),
57
- keyFingerprint: await toFingerprint(organizationKem.publicKey),
58
- members: [{ userId: input.userId }],
59
- memberEnvelopes,
60
- projection,
61
- grants: [],
62
- payloadCiphertext,
63
- externalAuthority: null,
64
- signedAt: new Date().toISOString(),
65
- signerUserId: input.userId,
66
- signerUserKeyFingerprint,
67
- }), input.signingKeyPair.signingPrivateKey);
68
- return {
69
- state,
70
- encryptedPayload: {
71
- cipherSuite: "aes-256-gcm",
72
- ciphertext: payloadCiphertext,
73
- ciphertextHash: state.payloadCiphertextHash,
74
- },
75
- projection,
76
- grants: [],
77
- memberEnvelopes,
78
- };
79
- }
80
12
  async function createOrganizationPrincipalPolicies(input) {
81
13
  const organizationId = crypto.randomUUID();
82
14
  const signingFingerprint = await toFingerprint(input.signingKeyPair.signingPublicKey);
@@ -1 +1 @@
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;QACvB,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CAAC;IACH,MAAM,6BAA6B,GACjC,MAAM,yCAAyC,CAAC;QAC9C,MAAM;QACN,WAAW,EAAE,+BAA+B;QAC5C,iBAAiB;QACjB,kBAAkB;QAClB,uBAAuB,EAAE,KAAK,CAAC,uBAAuB;QACtD,aAAa;QACb,uBAAuB;QACvB,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CAAC;IACL,MAAM,yBAAyB,GAAG,MAAM,OAAO,CAAC,GAAG,CACjD,CAAC,KAAK,CAAC,2BAA2B,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CACrD,oCAAoC,CAAC;QACnC,MAAM;QACN,iBAAiB;QACjB,aAAa;QACb,uBAAuB;QACvB,iBAAiB,EAAE,KAAK,CAAC,cAAc,CAAC,iBAAiB;QACzD,IAAI;QACJ,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CACH,CACF,CAAC;IAEF,OAAO;QACL,wBAAwB,EAAE,IAAI;QAC9B,SAAS;QACT,iBAAiB;QACjB,kBAAkB;QAClB,yBAAyB;QACzB,oBAAoB,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO;QAChD,cAAc;QACd,6BAA6B;QAC7B,aAAa;QACb,oBAAoB;QACpB,2BAA2B;QAC3B,sBAAsB;QACtB,yBAAyB;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["// Registration and additional-organization creation build and persist an\n// organization's founding policies, system containers, and profile documents\n// through this module.\nimport {\n buildPrincipalStateSigningInput,\n type EncapsulationKeyPair,\n generateKemSeedAndKeyPair,\n type ReferencedPrincipalHead,\n type SigningKeyPair,\n signPrincipalState,\n toFingerprint,\n wrapDekForRecipients,\n} from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport type {\n CreateOrganizationGroupRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport { encodeOrganizationAuthorityDescriptor } from \"../../data/principalContracts/organizationAuthorityDescriptor\";\nimport { createPrincipalProjectionMember } from \"../../data/principalContracts/principalIdentityCommitments\";\nimport { resolveDocumentCreateAuthor } from \"../documents\";\nimport { groupPolicyMutationHead } from \"../organizations/groupPolicy/groupPolicyMutationHead\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../organizations/principalPolicy\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport {\n buildInitialOrganizationMetadataBootstrap,\n buildInitialRootProvisioning,\n buildInitialRosterProfileBootstrap,\n buildInitialSystemContainerBootstrap,\n type ProvisionedSystemContainerSpec,\n} from \"./provisioningBootstrapBuilders\";\nimport { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\nexport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nexport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nexport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\ninterface OrganizationProvisioningPrincipalPolicies {\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"];\n organizationId: string;\n signingFingerprint: string;\n}\n\n/**\n * The freshly built provisioning artifacts, shared by registration and\n * additional-organization creation. `registerIdentity` generates a new\n * `userId`; creating an additional organization reuses the caller's existing\n * one. Everything here is derived purely from the caller's key material, so it\n * is identical for both flows.\n */\nexport interface OrganizationProvisioningArtifactsInput {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationProfileName?: string | undefined;\n /**\n * App-owned system containers to provision atomically with the organization\n * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and\n * organization-metadata system containers.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n rootContainerId: string;\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}\n\nexport async function buildInitialOrganizationPolicyRequest(input: {\n identityTrustDomain: string;\n adminGroupId: string;\n groupHeads: readonly ReferencedPrincipalHead[];\n encapsulationPublicKey: Uint8Array;\n memberGroupId: string;\n organizationId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<RegistrationRequest[\"initialOrganizationPolicy\"]> {\n const organizationKem = generateKemSeedAndKeyPair();\n const signerUserKeyFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const userEncapsulationKeyFingerprint = await toFingerprint(\n input.encapsulationPublicKey,\n );\n const projection = [\n await createPrincipalProjectionMember(\n {\n userId: input.userId,\n identityTrustDomain: input.identityTrustDomain,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n encapsulationPublicKey: input.encapsulationPublicKey,\n },\n \"admin\",\n ),\n ];\n const payloadCiphertext = encodeOrganizationAuthorityDescriptor({\n version: 2,\n organizationId: input.organizationId,\n adminGroupId: input.adminGroupId,\n memberGroupId: input.memberGroupId,\n groupHeads: input.groupHeads.map((head) => {\n if (head.principalType !== \"group\") {\n throw new Error(\"Organization directory can contain only group heads\");\n }\n return { ...head, principalType: \"group\" };\n }),\n });\n const [memberEnvelope] = await wrapDekForRecipients(\n organizationKem.secretKey,\n [input.encapsulationPublicKey],\n );\n\n if (!memberEnvelope) {\n throw new Error(\"Failed to wrap organization key for registering user\");\n }\n const memberEnvelopes = [\n {\n userId: input.userId,\n memberKeyFingerprint: userEncapsulationKeyFingerprint,\n kemCipherText: bytesToBase64(memberEnvelope.kemCipherText),\n wrappedKey: bytesToBase64(memberEnvelope.wrappedKey),\n },\n ];\n const state = await signPrincipalState(\n await buildPrincipalStateSigningInput({\n principalType: \"organization\",\n principalId: input.organizationId,\n version: 1,\n prevStateHash: null,\n keyEpoch: 1,\n encapsulationPublicKey: bytesToBase64(organizationKem.publicKey),\n keyFingerprint: await toFingerprint(organizationKem.publicKey),\n members: [{ userId: input.userId }],\n memberEnvelopes,\n projection,\n grants: [],\n payloadCiphertext,\n externalAuthority: null,\n signedAt: new Date().toISOString(),\n signerUserId: input.userId,\n signerUserKeyFingerprint,\n }),\n input.signingKeyPair.signingPrivateKey,\n );\n\n return {\n state,\n encryptedPayload: {\n cipherSuite: \"aes-256-gcm\",\n ciphertext: payloadCiphertext,\n ciphertextHash: state.payloadCiphertextHash,\n },\n projection,\n grants: [],\n memberEnvelopes,\n };\n}\n\nasync function createOrganizationPrincipalPolicies(input: {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationMetadataContainerId: string;\n rootContainerId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<OrganizationProvisioningPrincipalPolicies> {\n const organizationId = crypto.randomUUID();\n const signingFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const initialAdminGroup = await buildInitialGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n { containerId: input.rootContainerId, accessLevel: \"admin\" },\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"admin\",\n },\n ],\n name: \"Admins\",\n builtinRole: \"admins\",\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"read\",\n },\n ],\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest(\n {\n identityTrustDomain: input.identityTrustDomain,\n adminGroupId: initialAdminGroup.groupId,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n groupHeads: await Promise.all([\n groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),\n groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),\n ]),\n memberGroupId: initialMemberGroup.groupId,\n organizationId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n },\n );\n\n return {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n };\n}\n\nfunction requireOrganizationProvisioningAuthor(input: {\n readonly organizationId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}) {\n const author = resolveDocumentCreateAuthor({\n auth: { organizationId: input.organizationId, userId: input.userId },\n crypto: {\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n },\n });\n if (!author) {\n throw new Error(\n `Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`,\n );\n }\n return author;\n}\n\n/** Builds the signed artifacts shared by registration and org creation. */\nexport async function buildOrganizationProvisioningArtifacts(\n input: OrganizationProvisioningArtifactsInput,\n): Promise<OrganizationProvisioningArtifacts> {\n const bootstrap = await createInitialRootMetadataBootstrap(\n input.rootContainerId,\n );\n const organizationMetadataContainerId = crypto.randomUUID();\n const {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n } = await createOrganizationPrincipalPolicies({\n ...input,\n organizationMetadataContainerId,\n });\n const author = requireOrganizationProvisioningAuthor({\n organizationId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n\n const {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n } = await buildInitialRootProvisioning({\n adminGroup: initialAdminGroup,\n author,\n bootstrap,\n recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n rootContainerId: input.rootContainerId,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({\n author,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n initialAdminGroup,\n rosterProfileNickname: input.rosterProfileNickname,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const organizationMetadataBootstrap =\n await buildInitialOrganizationMetadataBootstrap({\n author,\n containerId: organizationMetadataContainerId,\n initialAdminGroup,\n initialMemberGroup,\n organizationProfileName: input.organizationProfileName,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const systemContainerBootstraps = await Promise.all(\n (input.provisionedSystemContainers ?? []).map((spec) =>\n buildInitialSystemContainerBootstrap({\n author,\n initialAdminGroup,\n rootContainer,\n rootContainerProjection,\n signingPrivateKey: input.signingKeyPair.signingPrivateKey,\n spec,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n }),\n ),\n );\n\n return {\n replacementAuthorization: null,\n bootstrap,\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer: rootContainer.plan.request,\n organizationId,\n organizationMetadataBootstrap,\n rootContainer,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n rosterProfileBootstrap,\n systemContainerBootstraps,\n };\n}\n"]}
1
+ {"version":3,"file":"organizationProvisioning.js","sourceRoot":"","sources":["organizationProvisioning.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,6EAA6E;AAC7E,uBAAuB;AACvB,OAAO,EAGL,aAAa,GACd,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,qCAAqC,EAAE,MAAM,iDAAiD,CAAC;AACxG,OAAO,EAAE,2BAA2B,EAAE,MAAM,cAAc,CAAC;AAC3D,OAAO,EAAE,uBAAuB,EAAE,MAAM,sDAAsD,CAAC;AAC/F,OAAO,EACL,8BAA8B,EAC9B,oCAAoC,GACrC,MAAM,kCAAkC,CAAC;AAE1C,OAAO,EACL,yCAAyC,EACzC,4BAA4B,EAC5B,kCAAkC,EAClC,oC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,CAAC,IAAI,EAAE,EAAE,CACrD,oCAAoC,CAAC;QACnC,MAAM;QACN,iBAAiB;QACjB,aAAa;QACb,uBAAuB;QACvB,iBAAiB,EAAE,KAAK,CAAC,cAAc,CAAC,iBAAiB;QACzD,IAAI;QACJ,eAAe,EAAE,KAAK,CAAC,oBAAoB,CAAC,SAAS;KACtD,CAAC,CACH,CACF,CAAC;IAEF,OAAO;QACL,wBAAwB,EAAE,IAAI;QAC9B,SAAS;QACT,iBAAiB;QACjB,kBAAkB;QAClB,yBAAyB;QACzB,oBAAoB,EAAE,aAAa,CAAC,IAAI,CAAC,OAAO;QAChD,cAAc;QACd,6BAA6B;QAC7B,aAAa;QACb,oBAAoB;QACpB,2BAA2B;QAC3B,sBAAsB;QACtB,yBAAyB;KAC1B,CAAC;AACJ,CAAC","sourcesContent":["// Registration and additional-organization creation build and persist an\n// organization's founding policies, system containers, and profile documents\n// through this module.\nimport {\n type EncapsulationKeyPair,\n type SigningKeyPair,\n toFingerprint,\n} from \"@tearleads/crypto\";\nimport type {\n CreateOrganizationGroupRequest,\n RegistrationRequest,\n} from \"@tearleads/validators/request\";\nimport { buildInitialOrganizationPolicyRequest } from \"../../data/principals/organizationPolicyRequest\";\nimport { resolveDocumentCreateAuthor } from \"../documents\";\nimport { groupPolicyMutationHead } from \"../organizations/groupPolicy/groupPolicyMutationHead\";\nimport {\n buildInitialGroupPolicyRequest,\n buildInitialMemberGroupPolicyRequest,\n} from \"../organizations/principalPolicy\";\nimport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nimport {\n buildInitialOrganizationMetadataBootstrap,\n buildInitialRootProvisioning,\n buildInitialRosterProfileBootstrap,\n buildInitialSystemContainerBootstrap,\n type ProvisionedSystemContainerSpec,\n} from \"./provisioningBootstrapBuilders\";\nimport { createInitialRootMetadataBootstrap } from \"./rootMetadataBootstrap\";\n\nexport type { OrganizationProvisioningArtifacts } from \"./organizationProvisioningArtifacts\";\nexport { persistOrganizationProvisioningState } from \"./organizationProvisioningPersistence\";\nexport type { ProvisionedSystemContainerSpec } from \"./provisioningBootstrapBuilders\";\n\ninterface OrganizationProvisioningPrincipalPolicies {\n initialAdminGroup: CreateOrganizationGroupRequest;\n initialMemberGroup: CreateOrganizationGroupRequest;\n initialOrganizationPolicy: RegistrationRequest[\"initialOrganizationPolicy\"];\n organizationId: string;\n signingFingerprint: string;\n}\n\n/**\n * The freshly built provisioning artifacts, shared by registration and\n * additional-organization creation. `registerIdentity` generates a new\n * `userId`; creating an additional organization reuses the caller's existing\n * one. Everything here is derived purely from the caller's key material, so it\n * is identical for both flows.\n */\nexport interface OrganizationProvisioningArtifactsInput {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationProfileName?: string | undefined;\n /**\n * App-owned system containers to provision atomically with the organization\n * (e.g. a trash bin). Omitted/empty leaves the org with only the roster and\n * organization-metadata system containers.\n */\n provisionedSystemContainers?:\n | ReadonlyArray<ProvisionedSystemContainerSpec>\n | undefined;\n rootContainerId: string;\n rosterProfileNickname?: string | undefined;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}\n\nasync function createOrganizationPrincipalPolicies(input: {\n identityTrustDomain: string;\n encapsulationKeyPair: EncapsulationKeyPair;\n organizationMetadataContainerId: string;\n rootContainerId: string;\n signingKeyPair: SigningKeyPair;\n userId: string;\n}): Promise<OrganizationProvisioningPrincipalPolicies> {\n const organizationId = crypto.randomUUID();\n const signingFingerprint = await toFingerprint(\n input.signingKeyPair.signingPublicKey,\n );\n const initialAdminGroup = await buildInitialGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n { containerId: input.rootContainerId, accessLevel: \"admin\" },\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"admin\",\n },\n ],\n name: \"Admins\",\n builtinRole: \"admins\",\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialMemberGroup = await buildInitialMemberGroupPolicyRequest({\n identityTrustDomain: input.identityTrustDomain,\n creatorEncapsulationKeyPair: input.encapsulationKeyPair,\n groupId: crypto.randomUUID(),\n grants: [\n {\n containerId: input.organizationMetadataContainerId,\n accessLevel: \"read\",\n },\n ],\n signerUserId: input.userId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n });\n const initialOrganizationPolicy = await buildInitialOrganizationPolicyRequest(\n {\n identityTrustDomain: input.identityTrustDomain,\n adminGroupId: initialAdminGroup.groupId,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n groupHeads: await Promise.all([\n groupPolicyMutationHead(initialAdminGroup.initialGroupPolicy),\n groupPolicyMutationHead(initialMemberGroup.initialGroupPolicy),\n ]),\n memberGroupId: initialMemberGroup.groupId,\n organizationId,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n },\n );\n\n return {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n };\n}\n\nfunction requireOrganizationProvisioningAuthor(input: {\n readonly organizationId: string;\n readonly signingFingerprint: string;\n readonly signingKeyPair: SigningKeyPair;\n readonly userId: string;\n}) {\n const author = resolveDocumentCreateAuthor({\n auth: { organizationId: input.organizationId, userId: input.userId },\n crypto: {\n signingFingerprint: input.signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n },\n });\n if (!author) {\n throw new Error(\n `Organization provisioning document author context is unavailable for user ${input.userId} in organization ${input.organizationId}.`,\n );\n }\n return author;\n}\n\n/** Builds the signed artifacts shared by registration and org creation. */\nexport async function buildOrganizationProvisioningArtifacts(\n input: OrganizationProvisioningArtifactsInput,\n): Promise<OrganizationProvisioningArtifacts> {\n const bootstrap = await createInitialRootMetadataBootstrap(\n input.rootContainerId,\n );\n const organizationMetadataContainerId = crypto.randomUUID();\n const {\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n organizationId,\n signingFingerprint,\n } = await createOrganizationPrincipalPolicies({\n ...input,\n organizationMetadataContainerId,\n });\n const author = requireOrganizationProvisioningAuthor({\n organizationId,\n signingFingerprint,\n signingKeyPair: input.signingKeyPair,\n userId: input.userId,\n });\n\n const {\n rootContainer,\n rootContainerProjection,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n } = await buildInitialRootProvisioning({\n adminGroup: initialAdminGroup,\n author,\n bootstrap,\n recipientEncapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n rootContainerId: input.rootContainerId,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const rosterProfileBootstrap = await buildInitialRosterProfileBootstrap({\n author,\n encapsulationPublicKey: input.encapsulationKeyPair.publicKey,\n initialAdminGroup,\n rosterProfileNickname: input.rosterProfileNickname,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const organizationMetadataBootstrap =\n await buildInitialOrganizationMetadataBootstrap({\n author,\n containerId: organizationMetadataContainerId,\n initialAdminGroup,\n initialMemberGroup,\n organizationProfileName: input.organizationProfileName,\n rootContainer,\n rootContainerProjection,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n });\n const systemContainerBootstraps = await Promise.all(\n (input.provisionedSystemContainers ?? []).map((spec) =>\n buildInitialSystemContainerBootstrap({\n author,\n initialAdminGroup,\n rootContainer,\n rootContainerProjection,\n signingPrivateKey: input.signingKeyPair.signingPrivateKey,\n spec,\n targetSecretKey: input.encapsulationKeyPair.secretKey,\n }),\n ),\n );\n\n return {\n replacementAuthorization: null,\n bootstrap,\n initialAdminGroup,\n initialMemberGroup,\n initialOrganizationPolicy,\n initialRootContainer: rootContainer.plan.request,\n organizationId,\n organizationMetadataBootstrap,\n rootContainer,\n rootMetadataDocument,\n rootMetadataDocumentRequest,\n rosterProfileBootstrap,\n systemContainerBootstraps,\n };\n}\n"]}
@@ -1,6 +1,7 @@
1
1
  import { createDocument, encodeVersionVector, importUpdates, } from "../../internal/loro/index.js";
2
2
  import { createPendingUpdateFields } from "../../data/documents/documentSync.js";
3
3
  import { sqlContainerContentsPersistence, } from "../../data/persistence/container-contents/containerContentsPersistence.js";
4
+ import { deleteDocumentPlacements } from "../../data/persistence/container-contents/documentContainerProjectionPersistence.js";
4
5
  import { primeAuthoredDocumentDiscoveryHeads, } from "../../data/persistence/documents/documentDiscoveryEvidencePersistence.js";
5
6
  import { DOCUMENTS_APP_KIND, sqlDocumentsPersistence, } from "../../data/persistence/documents/documentsPersistence.js";
6
7
  import { documentContainerProjectionTables } from "../../data/sqlite/schema/documentProjectionSchema.js";
@@ -147,6 +148,7 @@ export async function persistInitialDocumentBootstrap(execSql, input) {
147
148
  await persistDocumentState({
148
149
  currentDoc: doc,
149
150
  currentRecord: null,
151
+ deleteDocumentPlacements,
150
152
  documentProjectors: input.documentProjectors ?? [],
151
153
  execSql,
152
154
  localId: input.localId,