@tearleads/client-sdk 0.1.216 → 0.1.218

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 (149) hide show
  1. package/client/containerContents/documentDiscovery.js +6 -4
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/containerContents/index.js +3 -4
  4. package/client/containerContents/index.js.map +1 -1
  5. package/client/deviceFirst/index.js +2 -2
  6. package/client/deviceFirst/index.js.map +1 -1
  7. package/client/documents/index.js +2 -2
  8. package/client/documents/index.js.map +1 -1
  9. package/client/organizations/organizationGroupHistory.js +1 -2
  10. package/client/organizations/organizationGroupHistory.js.map +1 -1
  11. package/client/organizations/organizationGroupNameHydration.js +1 -2
  12. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  13. package/client/organizations/organizationHistory.js +2 -4
  14. package/client/organizations/organizationHistory.js.map +1 -1
  15. package/client/organizations/principalContainerMutations.js +1 -2
  16. package/client/organizations/principalContainerMutations.js.map +1 -1
  17. package/client/organizations/principalMutations.js +1 -2
  18. package/client/organizations/principalMutations.js.map +1 -1
  19. package/client/organizations/rosterAdmissionEvidence.js +1 -2
  20. package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
  21. package/client/runtime/workflowRuntime.d.ts +3 -2
  22. package/client/runtime/workflowRuntime.js +13 -3
  23. package/client/runtime/workflowRuntime.js.map +1 -1
  24. package/data/sync/organizationSyncPauses.d.ts +21 -10
  25. package/data/sync/organizationSyncPauses.js +73 -59
  26. package/data/sync/organizationSyncPauses.js.map +1 -1
  27. package/index.d.ts +1 -1
  28. package/index.js.map +1 -1
  29. package/package.json +1 -1
  30. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  31. package/stores/documents/documentStore/attachments/attachmentHydration.js +3 -2
  32. package/stores/documents/documentStore/attachments/attachmentHydration.js.map +1 -1
  33. package/stores/documents/documentStore/initialization/index.js +2 -2
  34. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  35. package/stores/documents/documentStore/rotation/index.js +1 -2
  36. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  37. package/stores/documents/documentStore/rotation/rotationSettlement.js +1 -1
  38. package/stores/documents/documentStore/rotation/rotationSettlement.js.map +1 -1
  39. package/stores/documents/documentStore/state.js.map +1 -1
  40. package/stores/documents/documentStore/sync/carriedFirstUpdate.js.map +1 -1
  41. package/stores/documents/documentStore/sync/index.js.map +1 -1
  42. package/stores/documents/documentStore/sync/syncAttachments.js +3 -2
  43. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  44. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -2
  45. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  46. package/stores/documents/documentStore/sync/syncRequest.js +3 -2
  47. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  48. package/stores/documents/documentStore/sync/syncRevalidation.js.map +1 -1
  49. package/stores/documents/documentStore/sync/syncSeededCreate.js.map +1 -1
  50. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  51. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  52. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  53. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  54. package/workflows/container-contents/container-state/create/createWithMetadata.js +1 -2
  55. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  56. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +1 -2
  57. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  58. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -2
  59. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  60. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -2
  61. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  62. package/workflows/container-contents/container-state/remote.js +3 -4
  63. package/workflows/container-contents/container-state/remote.js.map +1 -1
  64. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
  65. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  66. package/workflows/container-contents/container-state/share/index.js +2 -3
  67. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  68. package/workflows/container-contents/container-state/types.js.map +1 -1
  69. package/workflows/container-contents/documentLinks/documentLinksMove.js +4 -2
  70. package/workflows/container-contents/documentLinks/documentLinksMove.js.map +1 -1
  71. package/workflows/container-contents/documentLinks/index.js +3 -2
  72. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  73. package/workflows/container-contents/index.d.ts +1 -1
  74. package/workflows/container-contents/index.js +1 -1
  75. package/workflows/container-contents/index.js.map +1 -1
  76. package/workflows/container-contents/metadata/index.d.ts +1 -1
  77. package/workflows/container-contents/metadata/index.js.map +1 -1
  78. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +3 -3
  79. package/workflows/container-contents/metadata/metadataRemoteSync.js +3 -2
  80. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  81. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -2
  82. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  83. package/workflows/container-contents/remoteHydration/index.js +1 -2
  84. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  85. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +4 -2
  86. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  87. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  88. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  89. package/workflows/container-contents/runtime.d.ts +13 -2
  90. package/workflows/container-contents/runtime.js +33 -21
  91. package/workflows/container-contents/runtime.js.map +1 -1
  92. package/workflows/container-contents/syncLane.d.ts +1 -1
  93. package/workflows/container-contents/syncLane.js.map +1 -1
  94. package/workflows/container-contents/syncPause/documentRemoval.js +2 -2
  95. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
  96. package/workflows/container-contents/tombstones/documentPurge.d.ts +2 -3
  97. package/workflows/container-contents/tombstones/documentPurge.js +1 -2
  98. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  99. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +3 -2
  100. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  101. package/workflows/documents/index.d.ts +1 -1
  102. package/workflows/documents/index.js +1 -1
  103. package/workflows/documents/index.js.map +1 -1
  104. package/workflows/documents/runtime.d.ts +12 -1
  105. package/workflows/documents/runtime.js +24 -16
  106. package/workflows/documents/runtime.js.map +1 -1
  107. package/workflows/documents/sync/syncLane.d.ts +1 -1
  108. package/workflows/documents/sync/syncLane.js.map +1 -1
  109. package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -2
  110. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  111. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +5 -4
  112. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js +2 -4
  113. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -1
  114. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js +1 -2
  115. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -1
  116. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  117. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -2
  118. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +2 -2
  119. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  120. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js +4 -8
  121. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js.map +1 -1
  122. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +2 -3
  123. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  124. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
  125. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +2 -2
  126. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
  127. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +2 -2
  128. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  129. package/workflows/principals/index.d.ts +1 -0
  130. package/workflows/principals/index.js.map +1 -1
  131. package/workflows/principals/principalPolicyService.d.ts +64 -0
  132. package/workflows/principals/principalPolicyService.js +117 -0
  133. package/workflows/principals/principalPolicyService.js.map +1 -0
  134. package/workflows/principals/runtimePolicyRecovery.d.ts +13 -10
  135. package/workflows/principals/runtimePolicyRecovery.js +9 -17
  136. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  137. package/workflows/principals/runtimeProjectionPolicyRecovery.js +7 -8
  138. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  139. package/workflows/sync/index.d.ts +1 -1
  140. package/workflows/sync/index.js +1 -1
  141. package/workflows/sync/index.js.map +1 -1
  142. package/data/principals/principalHistoryRuntime.js +0 -12
  143. package/data/principals/principalHistoryRuntime.js.map +0 -1
  144. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.d.ts +0 -16
  145. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js +0 -39
  146. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js.map +0 -1
  147. package/workflows/principals/runtimePolicyWarmer.d.ts +0 -26
  148. package/workflows/principals/runtimePolicyWarmer.js +0 -48
  149. package/workflows/principals/runtimePolicyWarmer.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"currentOrganizationMutationRetention.js","sourceRoot":"","sources":["currentOrganizationMutationRetention.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AACxG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD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QAAQ;oBAC1B,QAAQ,EAAE;wBACR,aAAa,EAAE,KAAK,CAAC,aAAa;wBAClC,YAAY,EAAE,OAAO,CAAC,QAAQ,CAAC,IAAI;wBACnC,UAAU,EAAE,4BAA4B,CACtC,KAAK,CAAC,UAAU,EAChB,KAAK,CAAC,cAAc,EACpB,KAAK,CAAC,SAAS,CAAC,UAAU,CAAC,YAAY,CACxC;wBACD,0BAA0B,EACxB,KAAK,CAAC,OAAO,CAAC,0BAA0B;wBAC1C,qBAAqB,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC;4BAClC,WAAW,EAAE,SAAS;4BACtB,MAAM,EAAE;gCACN;oCACE,IAAI,EAAE,SAAS;oCACf,UAAU,EAAE,KAAK,CAAC,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC,UAAU;iCACrD;6BACF;yBACF,CAAC;qBACH;iBACF;gBACD;oBACE,WAAW;oBACX,OAAO,EAAE,OAAO,CAAC,mBAAmB;oBACpC,QAAQ,EAAE,OAAO,CAAC,oBAAoB;oBACtC,QAAQ,EAAE,KAAK,CAAC,iBAAiB;iBAClC;aACF,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { scopedGroupHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"../../principals/acknowledgements/acknowledgedPrincipalPredecessor\";\nimport type { PrincipalPolicyPageReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../../principals/runtimePolicyRecovery\";\nimport type { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\n/** Couple directory acknowledgements to any newly created group under the same lease. */\nexport async function createCurrentOrganizationMutationRetention(input: {\n readonly runtime: PrincipalPolicyRecoveryRuntime;\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly organizationId: string;\n readonly directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"];\n readonly stillCurrent: () => boolean;\n}) {\n const predecessor = await captureAcknowledgedPrincipalPredecessor({\n ...input.directoryRecovery,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n const retain = async (\n entries: readonly AcknowledgedPrincipalCurrentInput[],\n ) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n entries,\n stillCurrent: input.stillCurrent,\n });\n };\n return {\n retainDirectory: (\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n ) =>\n retain([\n { predecessor, request, response, recovery: input.directoryRecovery },\n ]),\n retainCreatedGroup: (receipt: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly organizationResponse: PrincipalPolicyMutationResponse;\n }) => {\n const adminHead = {\n ...principalPolicyReferenceFromBundle(input.authority.admins.current),\n principalType: \"group\" as const,\n };\n return retain([\n {\n initialGroup: true,\n predecessor: null,\n request: receipt.request,\n response: receipt.response,\n recovery: {\n historyReader: input.historyReader,\n expectedHead: receipt.response.head,\n protection: scopedGroupHistoryProtection(\n input.protection,\n input.organizationId,\n input.authority.descriptor.adminGroupId,\n ),\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n loadExternalAuthority: async () => ({\n currentHead: adminHead,\n states: [\n {\n head: adminHead,\n projection: input.authority.admins.policy.projection,\n },\n ],\n }),\n },\n },\n {\n predecessor,\n request: receipt.organizationRequest,\n response: receipt.organizationResponse,\n recovery: input.directoryRecovery,\n },\n ]);\n },\n };\n}\n"]}
1
+ {"version":3,"file":"currentOrganizationMutationRetention.js","sourceRoot":"","sources":["currentOrganizationMutationRetention.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AACxG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAG1G,OAAO,EAAE,uCAAuC,EAAE,MAAM,oEAAoE,CAAC;AAG7H,OAAO,EAEL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AAE/C,yFAAyF;AACzF,MAAM,CAAC,KAAK,UAAU,0CAA0C,CAAC,KAahE;IACC,MAAM,WAAW,GAAG,MAAM,uCAAuC,CAAC;QAChE,GAAG,KAAK,CAAC,iBAAiB;QAC1B,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,KAAK,EAClB,OAAqD,EACrD,EAAE;QACF,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,mCAAmC,CAAC;YACxC,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;YACpC,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,OAAO;YACP,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO;QACL,eAAe,EAAE,CACf,OAAkC,EAClC,Q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ptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { scopedGroupHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"../../principals/acknowledgements/acknowledgedPrincipalPredecessor\";\nimport type { PrincipalPolicyPageReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\n/** Couple directory acknowledgements to any newly created group under the same lease. */\nexport async function createCurrentOrganizationMutationRetention(input: {\n readonly runtime: {\n readonly infra: { readonly execSql: ExecSql };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n };\n readonly authority: Awaited<\n ReturnType<typeof loadCurrentOrganizationAuthority>\n >;\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly organizationId: string;\n readonly directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"];\n readonly stillCurrent: () => boolean;\n}) {\n const predecessor = await captureAcknowledgedPrincipalPredecessor({\n ...input.directoryRecovery,\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: input.stillCurrent,\n });\n const retain = async (\n entries: readonly AcknowledgedPrincipalCurrentInput[],\n ) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n entries,\n stillCurrent: input.stillCurrent,\n });\n };\n return {\n retainDirectory: (\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n ) =>\n retain([\n { predecessor, request, response, recovery: input.directoryRecovery },\n ]),\n retainCreatedGroup: (receipt: {\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly organizationResponse: PrincipalPolicyMutationResponse;\n }) => {\n const adminHead = {\n ...principalPolicyReferenceFromBundle(input.authority.admins.current),\n principalType: \"group\" as const,\n };\n return retain([\n {\n initialGroup: true,\n predecessor: null,\n request: receipt.request,\n response: receipt.response,\n recovery: {\n historyReader: input.historyReader,\n expectedHead: receipt.response.head,\n protection: scopedGroupHistoryProtection(\n input.protection,\n input.organizationId,\n input.authority.descriptor.adminGroupId,\n ),\n resolveTrustedUserIdentity:\n input.runtime.resolveTrustedUserIdentity,\n loadExternalAuthority: async () => ({\n currentHead: adminHead,\n states: [\n {\n head: adminHead,\n projection: input.authority.admins.policy.projection,\n },\n ],\n }),\n },\n },\n {\n predecessor,\n request: receipt.organizationRequest,\n response: receipt.organizationResponse,\n recovery: input.directoryRecovery,\n },\n ]);\n },\n };\n}\n"]}
@@ -2,13 +2,13 @@ import { assertProjectionVerificationCurrent } from "../../../data/keyingProject
2
2
  import { scopedGroupHistoryProtection } from "../../../data/principals/principalHistoryScopeProtection.js";
3
3
  import { principalPolicyReferenceFromBundle } from "../../../data/principals/principalPolicyAdminSigners.js";
4
4
  import { captureAcknowledgedPrincipalPredecessor } from "../../principals/acknowledgements/acknowledgedPrincipalPredecessor.js";
5
+ import { createCurrentPrincipalMutationLease, } from "../../principals/principalPolicyService.js";
5
6
  import { loadCurrentGroupPolicyMutationContext } from "../groupPolicy/currentGroupPolicyMutationContext.js";
6
7
  import { resolveCurrentGroupMutationReferences } from "./currentGroupMutationReferences.js";
7
- import { createCurrentPrincipalMutationLease } from "./currentPrincipalMutationLease.js";
8
8
  import { retainAcknowledgedPrincipalCurrents, } from "./retainAcknowledgedPrincipalCurrents.js";
9
9
  /** Keep private prefix custody inside the entire mutation and its acknowledgement. */
10
10
  export function createRuntimeCurrentGroupMutation(runtime) {
11
- const lease = createCurrentPrincipalMutationLease(runtime);
11
+ const lease = createCurrentPrincipalMutationLease(runtime.principalPolicies);
12
12
  if (!lease)
13
13
  return undefined;
14
14
  return async (input, work) => {
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeCurrentGroupMutation.js","sourceRoot":"","sources":["runtimeCurrentGroupMutation.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AAEvG,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AACxG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,uCAAuC,EAAE,MAAM,oEAAoE,CAAC;AAG7H,OAAO,EAAE,qCAAqC,EAAE,MAAM,kDAAkD,CAAC;AACzG,OAAO,EAAE,qCAAqC,EAAE,MAAM,kCAAkC,CAAC;AACzF,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AAEtF,OAAO,EAEL,mCAAmC,GACpC,MAAM,uCAAuC,CAAC;AA4C/C,sFAAsF;AACtF,MAAM,UAAU,iCAAiC,CAAC,OAAwB;IACxE,MAAM,KAAK,GAAG,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC3D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,EACV,KAAoB,EACpB,IAAiE,EACrD,EAAE;QACd,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;QACrB,OAAO,KAAK,CACV,KAAK,CAAC,YAAY,EAClB,KAAK,EAAE,EACL,UAAU,EACV,YAAY,EACZ,oBAAoB,EACpB,aAAa,EACb,iBAAiB,GAClB,EAAE,EAAE;YACH,MAAM,SAAS,GAAG,KAAK,EACr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AAE,aAAa;oBACvB,WAAW,EAAE,gBAAgB;oBAC7B,OAAO,EAAE,OAAO,CAAC,OAAO;oBACxB,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,WAAW;iBACvC;gBACD;oBACE,QAAQ,EAAE,iBAAiB;oBAC3B,WAAW,EAAE,oBAAoB;oBACjC,OAAO,EAAE,OAAO,CAAC,mBAAmB;oBACpC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,kBAAkB;iBAC9C;aACF;YACD,WAAW,EAAE;gBACX,GAAG,CAAC,OAAO,CAAC,gBAAgB,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;oBAClD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;oBAC5C,aAAa,EAAE,OAAgB;oBAC/B,YAAY,EAAE,KAAK,CAAC,mBAAmB,IAAI,EAAE;iBAC9C,CAAC,CAAC;gBACH;oBACE,WAAW,EAAE,KAAK,CAAC,OAAO;oBAC1B,aAAa,EAAE,OAAO;oBACtB,YAAY,EAAE,OAAO,CAAC,mBAAmB,IAAI,EAAE;iBAChD;aACF;YACD,YAAY,EAAE,OAAO,CAAC,YAAY;SACnC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO;QACL,cAAc,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE;QAC1E,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { CurrentPolicyReferenceResolver } from \"../../../data/principals/currentPolicyReferenceResolver\";\nimport { scopedGroupHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"../../principals/acknowledgements/acknowledgedPrincipalPredecessor\";\nimport type { PrincipalPolicyPageReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../../principals/runtimePolicyRecovery\";\nimport { loadCurrentGroupPolicyMutationContext } from \"../groupPolicy/currentGroupPolicyMutationContext\";\nimport { resolveCurrentGroupMutationReferences } from \"./currentGroupMutationReferences\";\nimport { createCurrentPrincipalMutationLease } from \"./currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\ntype MutationRuntime = PrincipalPolicyRecoveryRuntime & {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] &\n Pick<PrincipalMutationRecoveryApi, \"recoverPendingPrincipalMutation\">;\n};\n\ntype CurrentMutationContext = Awaited<\n ReturnType<typeof loadCurrentGroupPolicyMutationContext>\n>;\n\nexport type RuntimeCurrentGroupMutationContext = CurrentMutationContext & {\n readonly resolveAuthoredPolicyReferences: CurrentPolicyReferenceResolver;\n readonly loadGroup: (\n groupId: string,\n ) => Promise<RuntimeCurrentGroupMutationContext>;\n readonly groupRetention: Pick<\n AcknowledgedPrincipalCurrentInput,\n \"recovery\" | \"predecessor\"\n >;\n readonly retainAcknowledged: (\n receipt: CurrentMutationReceipt,\n ) => Promise<void>;\n};\n\ninterface CurrentMutationReceipt {\n readonly additionalGroups?:\n | readonly (AcknowledgedPrincipalCurrentInput & {\n readonly retiredContainerIds?: readonly string[] | undefined;\n })[]\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly response: CommitOrganizationGroupPolicyResponse;\n readonly retiredContainerIds?: readonly string[] | undefined;\n}\n\ninterface MutationInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/** Keep private prefix custody inside the entire mutation and its acknowledgement. */\nexport function createRuntimeCurrentGroupMutation(runtime: MutationRuntime) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: MutationInput,\n work: (context: RuntimeCurrentGroupMutationContext) => Promise<T>,\n ): Promise<T> => {\n input = { ...input };\n return lease(\n input.stillCurrent,\n async ({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery,\n }) => {\n const loadGroup = async (\n groupId: string,\n ): Promise<RuntimeCurrentGroupMutationContext> => {\n const context = await loadCurrentGroupPolicyMutationContext({\n ...input,\n groupId,\n execSql: runtime.infra.execSql,\n resolveCurrentPolicy,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n stillCurrent,\n });\n const retention = await createCurrentMutationRetention(\n runtime,\n { ...input, groupId },\n context,\n protection,\n historyReader,\n directoryRecovery(context.organizationCurrent.current),\n );\n return {\n ...context,\n ...retention,\n loadGroup,\n resolveAuthoredPolicyReferences: (current, references) =>\n resolveCurrentGroupMutationReferences({\n current,\n predecessor: context.verifiedCurrentPolicy,\n references,\n readPredecessorReference: context.readPredecessorReference,\n stillCurrent: context.stillCurrent,\n }),\n };\n };\n const context = await loadGroup(input.groupId);\n const result = await work(context);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function createCurrentMutationRetention(\n runtime: MutationRuntime,\n input: MutationInput,\n context: CurrentMutationContext,\n protection: PrincipalPolicyHistoryProgressOptions,\n historyReader: PrincipalPolicyPageReader,\n directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"],\n) {\n const common = {\n historyReader,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n const groupRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"] = {\n ...common,\n expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),\n protection: context.isOrganizationAdminsGroup\n ? protection\n : scopedGroupHistoryProtection(\n protection,\n input.organizationId,\n context.adminGroupId,\n ),\n historyVerification: context.isOrganizationAdminsGroup\n ? \"direct-admins\"\n : \"standard\",\n ...(context.isOrganizationAdminsGroup\n ? {}\n : { loadExternalAuthority: async () => context.externalAuthority }),\n };\n const capture = (recovery: AcknowledgedPrincipalCurrentInput[\"recovery\"]) =>\n captureAcknowledgedPrincipalPredecessor({\n ...recovery,\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: context.stillCurrent,\n });\n const groupPredecessor = await capture(groupRecovery);\n const directoryPredecessor = await capture(directoryRecovery);\n const retainAcknowledged = async (\n receipt: CurrentMutationReceipt,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(context.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n entries: [\n ...(receipt.additionalGroups ?? []),\n {\n recovery: groupRecovery,\n predecessor: groupPredecessor,\n request: receipt.request,\n response: receipt.response.groupPolicy,\n },\n {\n recovery: directoryRecovery,\n predecessor: directoryPredecessor,\n request: receipt.organizationRequest,\n response: receipt.response.organizationPolicy,\n },\n ],\n retirements: [\n ...(receipt.additionalGroups ?? []).map((entry) => ({\n principalId: entry.request.state.principalId,\n principalType: \"group\" as const,\n containerIds: entry.retiredContainerIds ?? [],\n })),\n {\n principalId: input.groupId,\n principalType: \"group\",\n containerIds: receipt.retiredContainerIds ?? [],\n },\n ],\n stillCurrent: context.stillCurrent,\n });\n };\n return {\n groupRetention: { recovery: groupRecovery, predecessor: groupPredecessor },\n retainAcknowledged,\n };\n}\n"]}
1
+ {"version":3,"file":"runtimeCurrentGroupMutation.js","sourceRoot":"","sources":["runtimeCurrentGroupMutation.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,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CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;oBAClD,WAAW,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,WAAW;oBAC5C,aAAa,EAAE,OAAgB;oBAC/B,YAAY,EAAE,KAAK,CAAC,mBAAmB,IAAI,EAAE;iBAC9C,CAAC,CAAC;gBACH;oBACE,WAAW,EAAE,KAAK,CAAC,OAAO;oBAC1B,aAAa,EAAE,OAAO;oBACtB,YAAY,EAAE,OAAO,CAAC,mBAAmB,IAAI,EAAE;iBAChD;aACF;YACD,YAAY,EAAE,OAAO,CAAC,YAAY;SACnC,CAAC,CAAC;IACL,CAAC,CAAC;IACF,OAAO;QACL,cAAc,EAAE,EAAE,QAAQ,EAAE,aAAa,EAAE,WAAW,EAAE,gBAAgB,EAAE;QAC1E,kBAAkB;KACnB,CAAC;AACJ,CAAC","sourcesContent":["import type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport type { CurrentPolicyReferenceResolver } from \"../../../data/principals/currentPolicyReferenceResolver\";\nimport { scopedGroupHistoryProtection } from \"../../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../../data/principals/principalPolicyAdminSigners\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport { captureAcknowledgedPrincipalPredecessor } from \"../../principals/acknowledgements/acknowledgedPrincipalPredecessor\";\nimport type { PrincipalPolicyPageReader } from \"../../principals/principalPolicyHistoryReader\";\nimport {\n createCurrentPrincipalMutationLease,\n type PrincipalPolicyRuntime,\n} from \"../../principals/principalPolicyService\";\nimport { loadCurrentGroupPolicyMutationContext } from \"../groupPolicy/currentGroupPolicyMutationContext\";\nimport { resolveCurrentGroupMutationReferences } from \"./currentGroupMutationReferences\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\nimport {\n type AcknowledgedPrincipalCurrentInput,\n retainAcknowledgedPrincipalCurrents,\n} from \"./retainAcknowledgedPrincipalCurrents\";\n\ntype MutationRuntime = PrincipalPolicyRuntime & {\n readonly apiClient: Pick<\n PrincipalMutationRecoveryApi,\n \"recoverPendingPrincipalMutation\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n};\n\ntype CurrentMutationContext = Awaited<\n ReturnType<typeof loadCurrentGroupPolicyMutationContext>\n>;\n\nexport type RuntimeCurrentGroupMutationContext = CurrentMutationContext & {\n readonly resolveAuthoredPolicyReferences: CurrentPolicyReferenceResolver;\n readonly loadGroup: (\n groupId: string,\n ) => Promise<RuntimeCurrentGroupMutationContext>;\n readonly groupRetention: Pick<\n AcknowledgedPrincipalCurrentInput,\n \"recovery\" | \"predecessor\"\n >;\n readonly retainAcknowledged: (\n receipt: CurrentMutationReceipt,\n ) => Promise<void>;\n};\n\ninterface CurrentMutationReceipt {\n readonly additionalGroups?:\n | readonly (AcknowledgedPrincipalCurrentInput & {\n readonly retiredContainerIds?: readonly string[] | undefined;\n })[]\n | undefined;\n readonly request: PutPrincipalPolicyRequest;\n readonly organizationRequest: PutPrincipalPolicyRequest;\n readonly response: CommitOrganizationGroupPolicyResponse;\n readonly retiredContainerIds?: readonly string[] | undefined;\n}\n\ninterface MutationInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\n/** Keep private prefix custody inside the entire mutation and its acknowledgement. */\nexport function createRuntimeCurrentGroupMutation(runtime: MutationRuntime) {\n const lease = createCurrentPrincipalMutationLease(runtime.principalPolicies);\n if (!lease) return undefined;\n return async <T>(\n input: MutationInput,\n work: (context: RuntimeCurrentGroupMutationContext) => Promise<T>,\n ): Promise<T> => {\n input = { ...input };\n return lease(\n input.stillCurrent,\n async ({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery,\n }) => {\n const loadGroup = async (\n groupId: string,\n ): Promise<RuntimeCurrentGroupMutationContext> => {\n const context = await loadCurrentGroupPolicyMutationContext({\n ...input,\n groupId,\n execSql: runtime.infra.execSql,\n resolveCurrentPolicy,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n stillCurrent,\n });\n const retention = await createCurrentMutationRetention(\n runtime,\n { ...input, groupId },\n context,\n protection,\n historyReader,\n directoryRecovery(context.organizationCurrent.current),\n );\n return {\n ...context,\n ...retention,\n loadGroup,\n resolveAuthoredPolicyReferences: (current, references) =>\n resolveCurrentGroupMutationReferences({\n current,\n predecessor: context.verifiedCurrentPolicy,\n references,\n readPredecessorReference: context.readPredecessorReference,\n stillCurrent: context.stillCurrent,\n }),\n };\n };\n const context = await loadGroup(input.groupId);\n const result = await work(context);\n assertProjectionVerificationCurrent(context.stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function createCurrentMutationRetention(\n runtime: MutationRuntime,\n input: MutationInput,\n context: CurrentMutationContext,\n protection: PrincipalPolicyHistoryProgressOptions,\n historyReader: PrincipalPolicyPageReader,\n directoryRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"],\n) {\n const common = {\n historyReader,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n };\n const groupRecovery: AcknowledgedPrincipalCurrentInput[\"recovery\"] = {\n ...common,\n expectedHead: principalPolicyReferenceFromBundle(context.currentPolicy),\n protection: context.isOrganizationAdminsGroup\n ? protection\n : scopedGroupHistoryProtection(\n protection,\n input.organizationId,\n context.adminGroupId,\n ),\n historyVerification: context.isOrganizationAdminsGroup\n ? \"direct-admins\"\n : \"standard\",\n ...(context.isOrganizationAdminsGroup\n ? {}\n : { loadExternalAuthority: async () => context.externalAuthority }),\n };\n const capture = (recovery: AcknowledgedPrincipalCurrentInput[\"recovery\"]) =>\n captureAcknowledgedPrincipalPredecessor({\n ...recovery,\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n stillCurrent: context.stillCurrent,\n });\n const groupPredecessor = await capture(groupRecovery);\n const directoryPredecessor = await capture(directoryRecovery);\n const retainAcknowledged = async (\n receipt: CurrentMutationReceipt,\n ): Promise<void> => {\n assertProjectionVerificationCurrent(context.stillCurrent);\n await retainAcknowledgedPrincipalCurrents({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n entries: [\n ...(receipt.additionalGroups ?? []),\n {\n recovery: groupRecovery,\n predecessor: groupPredecessor,\n request: receipt.request,\n response: receipt.response.groupPolicy,\n },\n {\n recovery: directoryRecovery,\n predecessor: directoryPredecessor,\n request: receipt.organizationRequest,\n response: receipt.response.organizationPolicy,\n },\n ],\n retirements: [\n ...(receipt.additionalGroups ?? []).map((entry) => ({\n principalId: entry.request.state.principalId,\n principalType: \"group\" as const,\n containerIds: entry.retiredContainerIds ?? [],\n })),\n {\n principalId: input.groupId,\n principalType: \"group\",\n containerIds: receipt.retiredContainerIds ?? [],\n },\n ],\n stillCurrent: context.stillCurrent,\n });\n };\n return {\n groupRetention: { recovery: groupRecovery, predecessor: groupPredecessor },\n retainAcknowledged,\n };\n}\n"]}
@@ -1,11 +1,11 @@
1
1
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
2
2
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
3
+ import { createCurrentPrincipalMutationLease, } from "../../principals/principalPolicyService.js";
3
4
  import { loadCurrentOrganizationMutationAuthority } from "./currentOrganizationMutationAuthority.js";
4
5
  import { createCurrentOrganizationMutationRetention } from "./currentOrganizationMutationRetention.js";
5
- import { createCurrentPrincipalMutationLease } from "./currentPrincipalMutationLease.js";
6
6
  /** Keep directory authoring and exact acknowledgement inside one private lease. */
7
7
  export function createRuntimeCurrentOrganizationMutation(runtime) {
8
- const lease = createCurrentPrincipalMutationLease(runtime);
8
+ const lease = createCurrentPrincipalMutationLease(runtime.principalPolicies);
9
9
  if (!lease)
10
10
  return undefined;
11
11
  return async (input, work) => {
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeCurrentOrganizationMutation.js","sourceRoot":"","sources":["runtimeCurrentOrganizationMutation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AAGpH,OAAO,EAAE,wCAAwC,EAAE,MAAM,wCAAwC,CAAC;AAClG,OAAO,EAAE,0CAA0C,EAAE,MAAM,wCAAwC,CAAC;AACpG,OAAO,EAAE,mCAAmC,EAAE,MAAM,iCAAiC,CAAC;AAmBtF,mFAAmF;AACnF,MAAM,UAAU,wCAAwC,CAAC,OAAgB;IACvE,MAAM,KAAK,GAAG,mCAAmC,CAAC,OAAO,CAAC,CAAC;IAC3D,IAAI,CAAC,KAAK;QAAE,OAAO,SAAS,CAAC;IAC7B,OAAO,KAAK,EACV,KAAY,EACZ,IAAiE,EACrD,EAAE;QACd,MAAM,KAAK,GAAG,EAAE,GAAG,KAAK,EAAE,CAAC;QAC3B,OAAO,KAAK,CACV,KAAK,CAAC,YAAY,EAClB,KAAK,EAAE,EACL,UAAU,EACV,aAAa,EACb,YAAY,EACZ,oBAAoB,EACpB,iBAAiB,GAClB,EAAE,EAAE;YACH,MAAM,EAAE,SAAS,EAAE,GAAG,MAAM,wCAAwC,CAAC;gBACnE,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;gBAC9B,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,YAAY,EAAE,KAAK,CAAC,YAAY;gBAChC,+BAA+B,EAAE,CAAC,cAAc,EAAE,EAAE,CAClD,OAAO,CAAC,SAAS,CAAC,+BAA+B,CAAC,cAAc,CAAC;gBACnE,oBAAoB;gBACpB,YAAY;aACb,CAAC,CAAC;YACH,MAAM,OAAO,GAAG,GAAG,EAAE,CAAC,YAAY,EAAE,IAAI,SAAS,CAAC,YAAY,EAAE,CAAC;YACjE,MAAM,IAAI,0BAA0B,CAClC,OAAO,CAAC,KAAK,CAAC,OAAO,CACtB,CAAC,kCAAkC,CAAC;gBACnC,MAAM,EAAE,EAAE;gBACV,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,QAAQ,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC;gBAC/D,YAAY,EAAE,OAAO;aACtB,CAAC,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACxB,GAAG,SAAS;gBACZ,YAAY,EAAE,OAAO;gBACrB,GAAG,CAAC,MAAM,0CAA0C,CAAC;oBACnD,OAAO;oBACP,SAAS;oBACT,UAAU;oBACV,aAAa;oBACb,cAAc,EAAE,KAAK,CAAC,cAAc;oBACpC,iBAAiB,EAAE,iBAAiB,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC;oBACjE,YAAY,EAAE,OAAO;iBACtB,CAAC,CAAC;aACJ,CAAC,CAAC;YACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;YAC7C,OAAO,MAAM,CAAC;QAChB,CAAC,CACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport type { PrincipalPolicyRecoveryRuntime } from \"../../principals/runtimePolicyRecovery\";\nimport type { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { loadCurrentOrganizationMutationAuthority } from \"./currentOrganizationMutationAuthority\";\nimport { createCurrentOrganizationMutationRetention } from \"./currentOrganizationMutationRetention\";\nimport { createCurrentPrincipalMutationLease } from \"./currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\n\ntype Runtime = PrincipalPolicyRecoveryRuntime & {\n readonly apiClient: PrincipalPolicyRecoveryRuntime[\"apiClient\"] &\n Pick<PrincipalMutationRecoveryApi, \"recoverPendingPrincipalMutation\">;\n};\n\ninterface Input {\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\ntype Authority = Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>;\n\nexport type CurrentOrganizationMutationContext = Authority &\n Awaited<ReturnType<typeof createCurrentOrganizationMutationRetention>>;\n\n/** Keep directory authoring and exact acknowledgement inside one private lease. */\nexport function createRuntimeCurrentOrganizationMutation(runtime: Runtime) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: Input,\n work: (context: CurrentOrganizationMutationContext) => Promise<T>,\n ): Promise<T> => {\n const owned = { ...input };\n return lease(\n owned.stillCurrent,\n async ({\n protection,\n historyReader,\n stillCurrent,\n resolveCurrentPolicy,\n directoryRecovery,\n }) => {\n const { authority } = await loadCurrentOrganizationMutationAuthority({\n execSql: runtime.infra.execSql,\n organizationId: owned.organizationId,\n signerUserId: owned.signerUserId,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n resolveCurrentPolicy,\n stillCurrent,\n });\n const current = () => stillCurrent() && authority.stillCurrent();\n await new KeyingCheckpointRepository(\n runtime.infra.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: owned.organizationId,\n policies: [authority.directory.policy, authority.admins.policy],\n stillCurrent: current,\n });\n const result = await work({\n ...authority,\n stillCurrent: current,\n ...(await createCurrentOrganizationMutationRetention({\n runtime,\n authority,\n protection,\n historyReader,\n organizationId: owned.organizationId,\n directoryRecovery: directoryRecovery(authority.directory.current),\n stillCurrent: current,\n })),\n });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n );\n };\n}\n"]}
1
+ {"version":3,"file":"runtimeCurrentOrganizationMutation.js","sourceRoot":"","sources":["runtimeCurrentOrganizationMutation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AAE,EAAE;gBACV,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,QAAQ,EAAE,CAAC,SAAS,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,MAAM,CAAC;gBAC/D,YAAY,EAAE,OAAO;aACtB,CAAC,CAAC;YACH,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC;gBACxB,GAAG,SAAS;gBACZ,YAAY,EAAE,OAAO;gBACrB,GAAG,CAAC,MAAM,0CAA0C,CAAC;oBACnD,OAAO;oBACP,SAAS;oBACT,UAAU;oBACV,aAAa;oBACb,cAAc,EAAE,KAAK,CAAC,cAAc;oBACpC,iBAAiB,EAAE,iBAAiB,CAAC,SAAS,CAAC,SAAS,CAAC,OAAO,CAAC;oBACjE,YAAY,EAAE,OAAO;iBACtB,CAAC,CAAC;aACJ,CAAC,CAAC;YACH,mCAAmC,CAAC,OAAO,CAAC,CAAC;YAC7C,OAAO,MAAM,CAAC;QAChB,CAAC,CACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport {\n createCurrentPrincipalMutationLease,\n type PrincipalPolicyRuntime,\n} from \"../../principals/principalPolicyService\";\nimport type { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { loadCurrentOrganizationMutationAuthority } from \"./currentOrganizationMutationAuthority\";\nimport { createCurrentOrganizationMutationRetention } from \"./currentOrganizationMutationRetention\";\nimport type { PrincipalMutationRecoveryApi } from \"./principalMutationJournalManagement\";\n\ntype Runtime = PrincipalPolicyRuntime & {\n readonly apiClient: Pick<\n PrincipalMutationRecoveryApi,\n \"recoverPendingPrincipalMutation\"\n >;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n};\n\ninterface Input {\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly stillCurrent: () => boolean;\n}\n\ntype Authority = Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>;\n\nexport type CurrentOrganizationMutationContext = Authority &\n Awaited<ReturnType<typeof createCurrentOrganizationMutationRetention>>;\n\n/** Keep directory authoring and exact acknowledgement inside one private lease. */\nexport function createRuntimeCurrentOrganizationMutation(runtime: Runtime) {\n const lease = createCurrentPrincipalMutationLease(runtime.principalPolicies);\n if (!lease) return undefined;\n return async <T>(\n input: Input,\n work: (context: CurrentOrganizationMutationContext) => Promise<T>,\n ): Promise<T> => {\n const owned = { ...input };\n return lease(\n owned.stillCurrent,\n async ({\n protection,\n historyReader,\n stillCurrent,\n resolveCurrentPolicy,\n directoryRecovery,\n }) => {\n const { authority } = await loadCurrentOrganizationMutationAuthority({\n execSql: runtime.infra.execSql,\n organizationId: owned.organizationId,\n signerUserId: owned.signerUserId,\n recoverPendingPrincipalMutation: (organizationId) =>\n runtime.apiClient.recoverPendingPrincipalMutation(organizationId),\n resolveCurrentPolicy,\n stillCurrent,\n });\n const current = () => stillCurrent() && authority.stillCurrent();\n await new KeyingCheckpointRepository(\n runtime.infra.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: owned.organizationId,\n policies: [authority.directory.policy, authority.admins.policy],\n stillCurrent: current,\n });\n const result = await work({\n ...authority,\n stillCurrent: current,\n ...(await createCurrentOrganizationMutationRetention({\n runtime,\n authority,\n protection,\n historyReader,\n organizationId: owned.organizationId,\n directoryRecovery: directoryRecovery(authority.directory.current),\n stillCurrent: current,\n })),\n });\n assertProjectionVerificationCurrent(current);\n return result;\n },\n );\n };\n}\n"]}
@@ -4,4 +4,5 @@ export { PrincipalPolicyHistoryReadError, type RecoveredPrincipalPolicyHistory,
4
4
  export { recoverPrincipalPolicyHistory } from "./historyRecovery/recoverPrincipalPolicyHistory.js";
5
5
  export { type RecoveredScopedPrincipalPolicyHistory, type RecoverScopedPrincipalPolicyHistoryOptions, recoverScopedPrincipalPolicyHistory, } from "./historyRecovery/recoverScopedPrincipalPolicyHistory.js";
6
6
  export { type CachePrincipalPolicyBundlesOptions, type CacheReferencedPrincipalPoliciesOptions, cachePrincipalPolicyBundles, cacheReferencedPrincipalPolicies, } from "./policyCache/index.js";
7
+ export type { PrincipalPolicyService } from "./principalPolicyService.js";
7
8
  export { type ProjectionPolicyHistoryRecoveryOptions, recoverProjectionPolicyHistory, } from "./publicHistory/recoverProjectionPolicyHistory.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,uCAAuC,GACxC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EACL,+BAA+B,GAGhC,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,6BAA6B,EAAE,MAAM,iDAAiD,CAAC;AAChG,OAAO,EAGL,mCAAmC,GACpC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AACvB,OAAO,EAEL,8BAA8B,GAC/B,MAAM,gDAAgD,CAAC","sourcesContent":["export type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nexport {\n type AcknowledgedPrincipalPredecessor,\n captureAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgements/acknowledgedPrincipalPredecessor\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./historyRecovery/principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./historyRecovery/recoverPrincipalPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./historyRecovery/recoverScopedPrincipalPolicyHistory\";\nexport {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./publicHistory/recoverProjectionPolicyHistory\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,uCAAuC,GACxC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EACL,+BAA+B,GAGhC,MAAM,iDAAiD,CAAC;AACzD,OAAO,EAAE,6BAA6B,EAAE,MAAM,iDAAiD,CAAC;AAChG,OAAO,EAGL,mCAAmC,GACpC,MAAM,uDAAuD,CAAC;AAC/D,OAAO,EAGL,2BAA2B,EAC3B,gCAAgC,GACjC,MAAM,eAAe,CAAC;AAEvB,OAAO,EAEL,8BAA8B,GAC/B,MAAM,gDAAgD,CAAC","sourcesContent":["export type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nexport {\n type AcknowledgedPrincipalPredecessor,\n captureAcknowledgedPrincipalPredecessor,\n} from \"./acknowledgements/acknowledgedPrincipalPredecessor\";\nexport {\n PrincipalPolicyHistoryReadError,\n type RecoveredPrincipalPolicyHistory,\n type RecoverPrincipalPolicyHistoryOptions,\n} from \"./historyRecovery/principalHistoryRecoveryTypes\";\nexport { recoverPrincipalPolicyHistory } from \"./historyRecovery/recoverPrincipalPolicyHistory\";\nexport {\n type RecoveredScopedPrincipalPolicyHistory,\n type RecoverScopedPrincipalPolicyHistoryOptions,\n recoverScopedPrincipalPolicyHistory,\n} from \"./historyRecovery/recoverScopedPrincipalPolicyHistory\";\nexport {\n type CachePrincipalPolicyBundlesOptions,\n type CacheReferencedPrincipalPoliciesOptions,\n cachePrincipalPolicyBundles,\n cacheReferencedPrincipalPolicies,\n} from \"./policyCache\";\nexport type { PrincipalPolicyService } from \"./principalPolicyService\";\nexport {\n type ProjectionPolicyHistoryRecoveryOptions,\n recoverProjectionPolicyHistory,\n} from \"./publicHistory/recoverProjectionPolicyHistory\";\n"]}
@@ -0,0 +1,64 @@
1
+ import type { PrincipalPolicyPageCurrent } from "../../internal/api-client/index.js";
2
+ import type { PrincipalPolicyHistoryProgressOptions } from "../../internal/crypto/index.js";
3
+ import { type ReferencedPrincipalPolicyWarmer } from "../../data/keyingProjectionVerification/types.js";
4
+ import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
5
+ import type { AcknowledgedPrincipalCurrentInput } from "./acknowledgements/acknowledgedPrincipalCurrents.js";
6
+ import { type PrincipalPolicyPageReader } from "./principalPolicyHistoryReader.js";
7
+ import { type PrincipalPolicyCollaborators, type PrincipalPolicyCurrentResolver } from "./runtimePolicyRecovery.js";
8
+ /**
9
+ * The token of one reconciliation pass or user workflow. Every warmer created
10
+ * with it shares one authenticated directory view, discovered once; the view
11
+ * dies with the token, an organization hint, a durable pin past it, or the end
12
+ * of its producing lease. Mint one at the pass or workflow root.
13
+ */
14
+ export type PrincipalPolicyOperation = object;
15
+ export declare function createPrincipalPolicyOperation(): PrincipalPolicyOperation;
16
+ export interface PrincipalPolicyWarmerOptions {
17
+ readonly preferLocalCurrent?: boolean;
18
+ readonly operation?: PrincipalPolicyOperation | undefined;
19
+ }
20
+ /** A runtime snapshot carrying the policy service its producer bound, and its executor. */
21
+ export interface PrincipalPolicyRuntime {
22
+ readonly infra: {
23
+ readonly execSql: ExecSql;
24
+ };
25
+ readonly principalPolicies: PrincipalPolicyService;
26
+ }
27
+ /**
28
+ * Principal Policy: recovers, verifies, and prefetches the principal policy
29
+ * evidence that projections cite. One instance binds one runtime snapshot's
30
+ * API client, executor, online state, reporter, logger, trusted-identity
31
+ * resolver, and the history-protection lease that snapshot bound; every view
32
+ * derived from the snapshot shares it. The collaborators sit in a private
33
+ * field, so a public runtime view carrying the service exposes no custody.
34
+ */
35
+ export declare class PrincipalPolicyService {
36
+ #private;
37
+ constructor(collaborators: PrincipalPolicyCollaborators);
38
+ /** Undefined without history custody or a paged history reader. */
39
+ createCurrentPolicyResolver(): PrincipalPolicyCurrentResolver | undefined;
40
+ /** Undefined without history custody or a projection history reader. */
41
+ createProjectionHistoryResolver(): ReferencedPrincipalPolicyWarmer["resolveProjectionHistory"];
42
+ /**
43
+ * One warmer serves one workflow operation: either the `operation` its root
44
+ * minted, or a fresh one of its own. Its projection collections share one
45
+ * authenticated directory view per operation. Prefetch is best-effort; exact
46
+ * resolution still rejects unavailable evidence.
47
+ */
48
+ createWarmer(options?: PrincipalPolicyWarmerOptions): ReferencedPrincipalPolicyWarmer;
49
+ }
50
+ export interface CurrentPrincipalMutationLeaseContext {
51
+ readonly protection: PrincipalPolicyHistoryProgressOptions;
52
+ readonly stillCurrent: () => boolean;
53
+ readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;
54
+ readonly historyReader: PrincipalPolicyPageReader;
55
+ readonly directoryRecovery: (current: PrincipalPolicyPageCurrent) => AcknowledgedPrincipalCurrentInput["recovery"];
56
+ }
57
+ export type CurrentPrincipalMutationLease = <T>(callerCurrent: () => boolean, work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>) => Promise<T>;
58
+ /**
59
+ * One lifetime fence and private custody boundary for every current-policy
60
+ * mutation. It hands the snapshot's private history protection to `work`, so
61
+ * it stays off the class and out of the package root: a public runtime view
62
+ * carrying the service cannot reach it.
63
+ */
64
+ export declare function createCurrentPrincipalMutationLease(service: PrincipalPolicyService): CurrentPrincipalMutationLease | undefined;
@@ -0,0 +1,117 @@
1
+ import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
+ import { rethrowKeyingVerificationError } from "../../data/keyingProjectionVerification/error.js";
3
+ import { assertProjectionVerificationCurrent, isProjectionVerificationCancelledError, } from "../../data/keyingProjectionVerification/types.js";
4
+ import { directoryHistoryProtection } from "../../data/principals/principalHistoryScopeProtection.js";
5
+ import { principalPolicyReferenceFromBundle } from "../../data/principals/principalPolicyAdminSigners.js";
6
+ import { errorMessage } from "../../data/shared/errorMessage.js";
7
+ import { apiPrincipalPolicyPageReader, } from "./principalPolicyHistoryReader.js";
8
+ import { createPrincipalPolicyCurrentResolver, } from "./runtimePolicyRecovery.js";
9
+ import { createProjectionPolicyHistoryResolver } from "./runtimeProjectionPolicyRecovery.js";
10
+ export function createPrincipalPolicyOperation() {
11
+ return {};
12
+ }
13
+ let collaboratorsOf;
14
+ /**
15
+ * Principal Policy: recovers, verifies, and prefetches the principal policy
16
+ * evidence that projections cite. One instance binds one runtime snapshot's
17
+ * API client, executor, online state, reporter, logger, trusted-identity
18
+ * resolver, and the history-protection lease that snapshot bound; every view
19
+ * derived from the snapshot shares it. The collaborators sit in a private
20
+ * field, so a public runtime view carrying the service exposes no custody.
21
+ */
22
+ export class PrincipalPolicyService {
23
+ #policies;
24
+ static {
25
+ collaboratorsOf = (service) => service.#policies;
26
+ }
27
+ constructor(collaborators) {
28
+ this.#policies = collaborators;
29
+ }
30
+ /** Undefined without history custody or a paged history reader. */
31
+ createCurrentPolicyResolver() {
32
+ return createPrincipalPolicyCurrentResolver(this.#policies);
33
+ }
34
+ /** Undefined without history custody or a projection history reader. */
35
+ createProjectionHistoryResolver() {
36
+ return createProjectionPolicyHistoryResolver(this.#policies);
37
+ }
38
+ /**
39
+ * One warmer serves one workflow operation: either the `operation` its root
40
+ * minted, or a fresh one of its own. Its projection collections share one
41
+ * authenticated directory view per operation. Prefetch is best-effort; exact
42
+ * resolution still rejects unavailable evidence.
43
+ */
44
+ createWarmer(options = {}) {
45
+ const resolve = this.createCurrentPolicyResolver();
46
+ const operation = options.operation ?? createPrincipalPolicyOperation();
47
+ const resolveReference = async (input) => {
48
+ if (!resolve)
49
+ throw new ProjectionDependencyUnavailableError("Principal policies require private paged recovery");
50
+ return resolve({
51
+ ...input,
52
+ recoveryBatch: input.recoveryBatch ?? operation,
53
+ preferLocalCurrent: options.preferLocalCurrent,
54
+ });
55
+ };
56
+ const policies = this.#policies;
57
+ return Object.assign((input) => prefetchReferences(policies, resolveReference, input), {
58
+ resolveReference,
59
+ resolveProjectionHistory: this.createProjectionHistoryResolver(),
60
+ });
61
+ }
62
+ }
63
+ async function prefetchReferences(policies, resolve, input) {
64
+ for (const reference of input.references) {
65
+ try {
66
+ assertProjectionVerificationCurrent(input.stillCurrent);
67
+ const resolved = await resolve({ ...input, reference });
68
+ assertProjectionVerificationCurrent(resolved.stillCurrent);
69
+ }
70
+ catch (error) {
71
+ if (isProjectionVerificationCancelledError(error))
72
+ return;
73
+ // Recovery already reports signature/authority failures. Keep them fatal.
74
+ rethrowKeyingVerificationError(error);
75
+ policies.util.log?.(`Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`);
76
+ }
77
+ }
78
+ }
79
+ /**
80
+ * One lifetime fence and private custody boundary for every current-policy
81
+ * mutation. It hands the snapshot's private history protection to `work`, so
82
+ * it stays off the class and out of the package root: a public runtime view
83
+ * carrying the service cannot reach it.
84
+ */
85
+ export function createCurrentPrincipalMutationLease(service) {
86
+ const policies = collaboratorsOf(service);
87
+ const lease = policies.withPrincipalHistoryProtection;
88
+ const resolveCurrentPolicy = createPrincipalPolicyCurrentResolver(policies);
89
+ const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);
90
+ if (!lease || !resolveCurrentPolicy || !historyReader)
91
+ return undefined;
92
+ return async (callerCurrent, work) => lease(async ({ protection, stillCurrent: leaseCurrent }) => {
93
+ let active = true;
94
+ const stillCurrent = () => active && leaseCurrent() && callerCurrent();
95
+ try {
96
+ assertProjectionVerificationCurrent(stillCurrent);
97
+ const result = await work({
98
+ protection,
99
+ stillCurrent,
100
+ resolveCurrentPolicy,
101
+ historyReader,
102
+ directoryRecovery: (current) => ({
103
+ historyReader,
104
+ expectedHead: principalPolicyReferenceFromBundle(current),
105
+ protection: directoryHistoryProtection(protection),
106
+ resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,
107
+ }),
108
+ });
109
+ assertProjectionVerificationCurrent(stillCurrent);
110
+ return result;
111
+ }
112
+ finally {
113
+ active = false;
114
+ }
115
+ });
116
+ }
117
+ //# sourceMappingURL=principalPolicyService.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyService.js","sourceRoot":"","sources":["principalPolicyService.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,8BAA8B,EAAE,MAAM,+CAA+C,CAAC;AAC/F,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GAEvC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,0BAA0B,EAAE,MAAM,uDAAuD,CAAC;AACnG,OAAO,EAAE,kCAAkC,EAAE,MAAM,mDAAmD,CAAC;AACvG,OAAO,EAAE,YAAY,EAAE,MAAM,gCAAgC,CAAC;AAG9D,OAAO,EACL,4BAA4B,GAE7B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,oCAAoC,GAGrC,MAAM,yBAAyB,CAAC;AACjC,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAc1F,MAAM,UAAU,8BAA8B;IAC5C,OAAO,EAAE,CAAC;AACZ,CAAC;AAaD,IAAI,eAE6B,CAAC;AAElC;;;;;;;GAOG;AACH,MAAM,OAAO,sBAAsB;IACxB,SAAS,CAA+B;IAEjD;QACE,eAAe,GAAG,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,SAAS,CAAC;IACnD,CAAC;IAED,YAAY,aAA2C;QACrD,IAAI,CAAC,SAAS,GAAG,aAAa,CAAC;IACjC,CAAC;IAED,mEAAmE;IACnE,2BAA2B;QACzB,OAAO,oCAAoC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC9D,CAAC;IAED,wEAAwE;IACxE,+BAA+B;QAC7B,OAAO,qCAAqC,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC/D,CAAC;IAED;;;;;OAKG;IACH,YAAY,CACV,UAAwC,EAAE;QAE1C,MAAM,OAAO,GAAG,IAA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AAC;QACjB,CAAC;IACH,CAAC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport type { PrincipalPolicyHistoryProgressOptions } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { rethrowKeyingVerificationError } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n isProjectionVerificationCancelledError,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification/types\";\nimport { directoryHistoryProtection } from \"../../data/principals/principalHistoryScopeProtection\";\nimport { principalPolicyReferenceFromBundle } from \"../../data/principals/principalPolicyAdminSigners\";\nimport { errorMessage } from \"../../data/shared/errorMessage\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { AcknowledgedPrincipalCurrentInput } from \"./acknowledgements/acknowledgedPrincipalCurrents\";\nimport {\n apiPrincipalPolicyPageReader,\n type PrincipalPolicyPageReader,\n} from \"./principalPolicyHistoryReader\";\nimport {\n createPrincipalPolicyCurrentResolver,\n type PrincipalPolicyCollaborators,\n type PrincipalPolicyCurrentResolver,\n} from \"./runtimePolicyRecovery\";\nimport { createProjectionPolicyHistoryResolver } from \"./runtimeProjectionPolicyRecovery\";\n\ntype PolicyResolver = NonNullable<\n ReferencedPrincipalPolicyWarmer[\"resolveReference\"]\n>;\n\n/**\n * The token of one reconciliation pass or user workflow. Every warmer created\n * with it shares one authenticated directory view, discovered once; the view\n * dies with the token, an organization hint, a durable pin past it, or the end\n * of its producing lease. Mint one at the pass or workflow root.\n */\nexport type PrincipalPolicyOperation = object;\n\nexport function createPrincipalPolicyOperation(): PrincipalPolicyOperation {\n return {};\n}\n\nexport interface PrincipalPolicyWarmerOptions {\n readonly preferLocalCurrent?: boolean;\n readonly operation?: PrincipalPolicyOperation | undefined;\n}\n\n/** A runtime snapshot carrying the policy service its producer bound, and its executor. */\nexport interface PrincipalPolicyRuntime {\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n}\n\nlet collaboratorsOf: (\n service: PrincipalPolicyService,\n) => PrincipalPolicyCollaborators;\n\n/**\n * Principal Policy: recovers, verifies, and prefetches the principal policy\n * evidence that projections cite. One instance binds one runtime snapshot's\n * API client, executor, online state, reporter, logger, trusted-identity\n * resolver, and the history-protection lease that snapshot bound; every view\n * derived from the snapshot shares it. The collaborators sit in a private\n * field, so a public runtime view carrying the service exposes no custody.\n */\nexport class PrincipalPolicyService {\n readonly #policies: PrincipalPolicyCollaborators;\n\n static {\n collaboratorsOf = (service) => service.#policies;\n }\n\n constructor(collaborators: PrincipalPolicyCollaborators) {\n this.#policies = collaborators;\n }\n\n /** Undefined without history custody or a paged history reader. */\n createCurrentPolicyResolver(): PrincipalPolicyCurrentResolver | undefined {\n return createPrincipalPolicyCurrentResolver(this.#policies);\n }\n\n /** Undefined without history custody or a projection history reader. */\n createProjectionHistoryResolver(): ReferencedPrincipalPolicyWarmer[\"resolveProjectionHistory\"] {\n return createProjectionPolicyHistoryResolver(this.#policies);\n }\n\n /**\n * One warmer serves one workflow operation: either the `operation` its root\n * minted, or a fresh one of its own. Its projection collections share one\n * authenticated directory view per operation. Prefetch is best-effort; exact\n * resolution still rejects unavailable evidence.\n */\n createWarmer(\n options: PrincipalPolicyWarmerOptions = {},\n ): ReferencedPrincipalPolicyWarmer {\n const resolve = this.createCurrentPolicyResolver();\n const operation = options.operation ?? createPrincipalPolicyOperation();\n const resolveReference: PolicyResolver = async (input) => {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Principal policies require private paged recovery\",\n );\n return resolve({\n ...input,\n recoveryBatch: input.recoveryBatch ?? operation,\n preferLocalCurrent: options.preferLocalCurrent,\n });\n };\n const policies = this.#policies;\n return Object.assign(\n (input: Parameters<ReferencedPrincipalPolicyWarmer>[0]) =>\n prefetchReferences(policies, resolveReference, input),\n {\n resolveReference,\n resolveProjectionHistory: this.createProjectionHistoryResolver(),\n },\n );\n }\n}\n\nasync function prefetchReferences(\n policies: PrincipalPolicyCollaborators,\n resolve: PolicyResolver,\n input: Parameters<ReferencedPrincipalPolicyWarmer>[0],\n): Promise<void> {\n for (const reference of input.references) {\n try {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const resolved = await resolve({ ...input, reference });\n assertProjectionVerificationCurrent(resolved.stillCurrent);\n } catch (error) {\n if (isProjectionVerificationCancelledError(error)) return;\n // Recovery already reports signature/authority failures. Keep them fatal.\n rethrowKeyingVerificationError(error);\n policies.util.log?.(\n `Principal policy prefetch: ${reference.principalId}: ${errorMessage(error)}`,\n );\n }\n }\n}\n\nexport interface CurrentPrincipalMutationLeaseContext {\n readonly protection: PrincipalPolicyHistoryProgressOptions;\n readonly stillCurrent: () => boolean;\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;\n readonly historyReader: PrincipalPolicyPageReader;\n readonly directoryRecovery: (\n current: PrincipalPolicyPageCurrent,\n ) => AcknowledgedPrincipalCurrentInput[\"recovery\"];\n}\n\nexport type CurrentPrincipalMutationLease = <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n) => Promise<T>;\n\n/**\n * One lifetime fence and private custody boundary for every current-policy\n * mutation. It hands the snapshot's private history protection to `work`, so\n * it stays off the class and out of the package root: a public runtime view\n * carrying the service cannot reach it.\n */\nexport function createCurrentPrincipalMutationLease(\n service: PrincipalPolicyService,\n): CurrentPrincipalMutationLease | undefined {\n const policies = collaboratorsOf(service);\n const lease = policies.withPrincipalHistoryProtection;\n const resolveCurrentPolicy = createPrincipalPolicyCurrentResolver(policies);\n const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);\n if (!lease || !resolveCurrentPolicy || !historyReader) return undefined;\n return async <T>(\n callerCurrent: () => boolean,\n work: (context: CurrentPrincipalMutationLeaseContext) => Promise<T>,\n ): Promise<T> =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n let active = true;\n const stillCurrent = () => active && leaseCurrent() && callerCurrent();\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n protection,\n stillCurrent,\n resolveCurrentPolicy,\n historyReader,\n directoryRecovery: (current) => ({\n historyReader,\n expectedHead: principalPolicyReferenceFromBundle(current),\n protection: directoryHistoryProtection(protection),\n resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,\n }),\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n } finally {\n active = false;\n }\n });\n}\n"]}
@@ -1,12 +1,18 @@
1
1
  import type { PrincipalPolicyPageCurrent } from "../../internal/api-client/index.js";
2
- import { type PrincipalPolicyResolveRequest, type ReferencedPrincipalPolicyWarmer, type ResolvedPrincipalPolicyEvidence } from "../../data/keyingProjectionVerification/types.js";
2
+ import { type PrincipalPolicyResolveRequest, type ResolvedPrincipalPolicyEvidence } from "../../data/keyingProjectionVerification/types.js";
3
3
  import type { PrincipalHistoryProtectionLease } from "../../data/principals/principalHistoryProtection.js";
4
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";
8
8
  import { type PrincipalPolicyHistoryReader } from "./principalPolicyHistoryReader.js";
9
- export interface PrincipalPolicyRecoveryRuntime {
9
+ /**
10
+ * The slices of one runtime snapshot a `PrincipalPolicyService` reads. Each
11
+ * service method reads them when it is called and its resolvers per request,
12
+ * as the snapshot's other consumers do. The lease is the snapshot's bound
13
+ * history custody; the service never binds one itself.
14
+ */
15
+ export interface PrincipalPolicyCollaborators {
10
16
  readonly apiClient: Partial<PrincipalPolicyHistoryReader>;
11
17
  readonly infra: {
12
18
  readonly execSql: ExecSql;
@@ -16,20 +22,17 @@ export interface PrincipalPolicyRecoveryRuntime {
16
22
  } | undefined;
17
23
  readonly util: {
18
24
  readonly reportSecurityIncident: SecurityIncidentReporter;
25
+ readonly log?: ((message: string) => void) | undefined;
19
26
  };
20
27
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
21
28
  readonly withPrincipalHistoryProtection?: PrincipalHistoryProtectionLease | undefined;
22
29
  }
23
- /** Keep the private recovery key inside its runtime lease while resolving cited evidence. */
24
- export declare function createRuntimePrincipalPolicyResolver(runtime: PrincipalPolicyRecoveryRuntime, options?: {
25
- readonly preferLocalCurrent?: boolean;
26
- }): ReferencedPrincipalPolicyWarmer["resolveReference"];
27
30
  export interface ResolvedPrincipalPolicyCurrent extends ResolvedPrincipalPolicyEvidence {
28
31
  readonly current: PrincipalPolicyPageCurrent;
29
32
  /** Rows end at the selected reference; current/policy may describe a newer recovered head. */
30
33
  readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;
31
34
  }
32
- interface PrincipalPolicyCurrentRequest extends Omit<PrincipalPolicyResolveRequest, "reference"> {
35
+ export interface PrincipalPolicyCurrentRequest extends Omit<PrincipalPolicyResolveRequest, "reference"> {
33
36
  readonly reference?: PrincipalPolicyResolveRequest["reference"] | undefined;
34
37
  /** A read-model caller has selected this exact signed head; not a freshness read. */
35
38
  readonly preferLocalCurrent?: boolean | undefined;
@@ -37,6 +40,6 @@ interface PrincipalPolicyCurrentRequest extends Omit<PrincipalPolicyResolveReque
37
40
  readonly beforeVersion?: number;
38
41
  } | undefined;
39
42
  }
40
- /** Keep current artifacts with their verified evidence and private runtime lifetime. */
41
- export declare function createRuntimePrincipalPolicyCurrentResolver(runtime: PrincipalPolicyRecoveryRuntime): ((input: PrincipalPolicyCurrentRequest) => Promise<ResolvedPrincipalPolicyCurrent>) | undefined;
42
- export {};
43
+ export type PrincipalPolicyCurrentResolver = (input: PrincipalPolicyCurrentRequest) => Promise<ResolvedPrincipalPolicyCurrent>;
44
+ /** Keep current artifacts with their verified evidence and private snapshot lifetime. */
45
+ export declare function createPrincipalPolicyCurrentResolver(policies: PrincipalPolicyCollaborators): PrincipalPolicyCurrentResolver | undefined;
@@ -2,20 +2,12 @@ import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
2
  import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
3
3
  import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
4
4
  import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectionVerification/types.js";
5
- import { readPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
6
5
  import { getOrCreatePrincipalPolicyCoordinator, } from "../../data/principals/principalPolicyCoordinator.js";
7
6
  import { PrincipalHistoryRecoveryRaceError, PrincipalPolicyHistoryReadError, } from "./historyRecovery/principalHistoryRecoveryTypes.js";
8
7
  import { apiPrincipalPolicyPageReader, } from "./principalPolicyHistoryReader.js";
9
8
  import { createPrincipalCurrentRecoveryBatch } from "./recoveryOperation/principalCurrentRecoveryBatch.js";
10
9
  import { recoverWithPrincipalLocalPreference } from "./recoveryOperation/principalRecoveryLocalPreference.js";
11
10
  import { resumeAfterSupersededStage } from "./recoveryOperation/supersededStageResume.js";
12
- /** Keep the private recovery key inside its runtime lease while resolving cited evidence. */
13
- export function createRuntimePrincipalPolicyResolver(runtime, options = {}) {
14
- const resolve = createRuntimePrincipalPolicyCurrentResolver(runtime);
15
- return resolve
16
- ? (input) => resolve({ ...input, preferLocalCurrent: options.preferLocalCurrent })
17
- : undefined;
18
- }
19
11
  /**
20
12
  * Operation batches belong to the database's coordinator, keyed by the
21
13
  * operation token, so every resolver and warmer one operation creates for that
@@ -48,14 +40,14 @@ function recoverPolicyCurrent(batch, options, input) {
48
40
  }, input.preferLocalCurrent === true || input.preferLocalHistory === true, input.preferLocalHistory === true)
49
41
  : batch.discover(options);
50
42
  }
51
- /** Keep current artifacts with their verified evidence and private runtime lifetime. */
52
- export function createRuntimePrincipalPolicyCurrentResolver(runtime) {
53
- const lease = readPrincipalHistoryProtection(runtime);
54
- const historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);
43
+ /** Keep current artifacts with their verified evidence and private snapshot lifetime. */
44
+ export function createPrincipalPolicyCurrentResolver(policies) {
45
+ const lease = policies.withPrincipalHistoryProtection;
46
+ const historyReader = apiPrincipalPolicyPageReader(policies.apiClient);
55
47
  if (!lease || !historyReader)
56
48
  return undefined;
57
- const coordinator = getOrCreatePrincipalPolicyCoordinator(runtime.infra.execSql);
58
- return (input) => coordinator.queueRecovery(input.organizationId, () => runWithSecurityIncidentReporting(runtime.util.reportSecurityIncident, {
49
+ const coordinator = getOrCreatePrincipalPolicyCoordinator(policies.infra.execSql);
50
+ return (input) => coordinator.queueRecovery(input.organizationId, () => runWithSecurityIncidentReporting(policies.util.reportSecurityIncident, {
59
51
  objectId: input.reference?.principalId ?? input.organizationId,
60
52
  objectKind: "principal",
61
53
  operation: "principal.policy.recover",
@@ -64,15 +56,15 @@ export function createRuntimePrincipalPolicyCurrentResolver(runtime) {
64
56
  const stillCurrent = () => leaseCurrent() && input.stillCurrent?.() !== false;
65
57
  assertProjectionVerificationCurrent(stillCurrent);
66
58
  assertHistoryPageRequest(input);
67
- const offline = runtime.state?.online === false;
59
+ const offline = policies.state?.online === false;
68
60
  try {
69
61
  const options = {
70
62
  historyReader,
71
- execSql: runtime.infra.execSql,
63
+ execSql: policies.infra.execSql,
72
64
  offline,
73
65
  organizationId: input.organizationId,
74
66
  protection,
75
- resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,
67
+ resolveTrustedUserIdentity: policies.resolveTrustedUserIdentity,
76
68
  stillCurrent,
77
69
  };
78
70
  const result = await resumeAfterSupersededStage(() => recoverPolicyCurrent(operationRecoveryBatch(coordinator, input.recoveryBatch), options, input), stillCurrent);
@@ -1 +1 @@
1
- {"version":3,"file":"runtimePolicyRecovery.js","sourceRoot":"","sources":["runtimePolicyRecovery.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D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EAAE,MAAM,CAAC,WAAW;gBAC/B,YAAY,EAAE,aAAa;aAC5B,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,IACE,KAAK,YAAY,+BAA+B;gBAChD,KAAK,YAAY,iCAAiC;gBAClD,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;AAED,SAAS,wBAAwB,CAAC,KAAoC;IACpE,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO;IAC/B,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC;IAC/C,IACE,CAAC,KAAK,CAAC,SAAS;QAChB,CAAC,MAAM,KAAK,SAAS;YACnB,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;gBAC5B,MAAM,IAAI,CAAC;gBACX,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;QAE1C,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,iEAAiE,CAClE,CAAC;AACN,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyResolveRequest,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../../data/keyingProjectionVerification/types\";\nimport type { PrincipalHistoryProtectionLease } from \"../../data/principals/principalHistoryProtection\";\nimport { readPrincipalHistoryProtection } from \"../../data/principals/principalHistoryRuntime\";\nimport {\n getOrCreatePrincipalPolicyCoordinator,\n type PrincipalPolicyCoordinator,\n} from \"../../data/principals/principalPolicyCoordinator\";\nimport type { SecurityIncidentReporter } from \"../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport type { RecoveredPrincipalHistoryPage } from \"./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\nexport interface PrincipalPolicyRecoveryRuntime {\n readonly apiClient: Partial<PrincipalPolicyHistoryReader>;\n readonly infra: { readonly execSql: ExecSql };\n readonly state?: { readonly online: boolean } | undefined;\n readonly util: { readonly reportSecurityIncident: SecurityIncidentReporter };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly withPrincipalHistoryProtection?:\n | PrincipalHistoryProtectionLease\n | undefined;\n}\n\n/** Keep the private recovery key inside its runtime lease while resolving cited evidence. */\nexport function createRuntimePrincipalPolicyResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n options: { readonly preferLocalCurrent?: boolean } = {},\n): ReferencedPrincipalPolicyWarmer[\"resolveReference\"] {\n const resolve = createRuntimePrincipalPolicyCurrentResolver(runtime);\n return resolve\n ? (input) =>\n resolve({ ...input, preferLocalCurrent: options.preferLocalCurrent })\n : undefined;\n}\n\nexport interface ResolvedPrincipalPolicyCurrent\n extends ResolvedPrincipalPolicyEvidence {\n readonly current: PrincipalPolicyPageCurrent;\n /** Rows end at the selected reference; current/policy may describe a newer recovered head. */\n readonly historyPage?: RecoveredPrincipalHistoryPage | undefined;\n}\n\ninterface PrincipalPolicyCurrentRequest\n extends Omit<PrincipalPolicyResolveRequest, \"reference\"> {\n readonly reference?: PrincipalPolicyResolveRequest[\"reference\"] | undefined;\n /** A read-model caller has selected this exact signed head; not a freshness read. */\n readonly preferLocalCurrent?: boolean | undefined;\n readonly historyPage?: { readonly beforeVersion?: number } | undefined;\n}\n\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 runtime lifetime. */\nexport function createRuntimePrincipalPolicyCurrentResolver(\n runtime: PrincipalPolicyRecoveryRuntime,\n):\n | ((\n input: PrincipalPolicyCurrentRequest,\n ) => Promise<ResolvedPrincipalPolicyCurrent>)\n | undefined {\n const lease = readPrincipalHistoryProtection(runtime);\n const historyReader = apiPrincipalPolicyPageReader(runtime.apiClient);\n if (!lease || !historyReader) return undefined;\n const coordinator = getOrCreatePrincipalPolicyCoordinator(\n runtime.infra.execSql,\n );\n return (input) =>\n coordinator.queueRecovery(input.organizationId, () =>\n runWithSecurityIncidentReporting(\n runtime.util.reportSecurityIncident,\n {\n objectId: input.reference?.principalId ?? input.organizationId,\n objectKind: \"principal\",\n operation: \"principal.policy.recover\",\n organizationId: input.organizationId,\n },\n () =>\n lease(async ({ protection, stillCurrent: leaseCurrent }) => {\n const stillCurrent = () =>\n leaseCurrent() && input.stillCurrent?.() !== false;\n assertProjectionVerificationCurrent(stillCurrent);\n assertHistoryPageRequest(input);\n const offline = runtime.state?.online === false;\n try {\n const options = {\n historyReader,\n execSql: runtime.infra.execSql,\n offline,\n organizationId: input.organizationId,\n protection,\n resolveTrustedUserIdentity: runtime.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,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,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;AAK1D,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,CAAC;AA6CvF;;;;;GAKG;AACH,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAGjC,CAAC;AAEJ,SAAS,sBAAsB,CAC7B,WAAuC,EACvC,SAA6B;IAE7B,IAAI,CAAC,SAAS;QAAE,OAAO,mCAAmC,EAAE,CAAC;IAC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Aa,CAAC,CAAC;YACnD,OAAO;gBACL,OAAO,EAAE,MAAM,CAAC,OAAO;gBACvB,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,MAAM,EAAE,MAAM,CAAC,MAAM;gBACrB,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,WAAW,EAAE,MAAM,CAAC,WAAW;gBAC/B,YAAY,EAAE,aAAa;aAC5B,CAAC;QACJ,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,IACE,KAAK,YAAY,+BAA+B;gBAChD,KAAK,YAAY,iCAAiC;gBAClD,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;AAED,SAAS,wBAAwB,CAAC,KAAoC;IACpE,IAAI,CAAC,KAAK,CAAC,WAAW;QAAE,OAAO;IAC/B,MAAM,MAAM,GAAG,KAAK,CAAC,WAAW,CAAC,aAAa,CAAC;IAC/C,IACE,CAAC,KAAK,CAAC,SAAS;QAChB,CAAC,MAAM,KAAK,SAAS;YACnB,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC;gBAC5B,MAAM,IAAI,CAAC;gBACX,MAAM,GAAG,KAAK,CAAC,SAAS,CAAC,OAAO,GAAG,CAAC,CAAC,CAAC;QAE1C,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,iEAAiE,CAClE,CAAC;AACN,CAAC","sourcesContent":["import type { PrincipalPolicyPageCurrent } from \"@tearleads/api-client\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { runWithSecurityIncidentReporting } from \"../../data/keyingProjectionVerification/error\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyResolveRequest,\n type 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 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"]}
@@ -2,7 +2,6 @@ import { KeyingVerificationError } from "../../internal/crypto/index.js";
2
2
  import { ProjectionDependencyUnavailableError } from "../../data/keyingProjectionVerification/dependencyUnavailable.js";
3
3
  import { runWithSecurityIncidentReporting } from "../../data/keyingProjectionVerification/error.js";
4
4
  import { assertProjectionVerificationCurrent, } from "../../data/keyingProjectionVerification/types.js";
5
- import { readPrincipalHistoryProtection } from "../../data/principals/principalHistoryRuntime.js";
6
5
  import { getOrCreatePrincipalPolicyCoordinator } from "../../data/principals/principalPolicyCoordinator.js";
7
6
  import { PrincipalPolicyHistoryReadError } from "./historyRecovery/principalHistoryRecoveryTypes.js";
8
7
  import { apiProjectionPolicyHistoryReader } from "./principalPolicyHistoryReader.js";
@@ -19,12 +18,12 @@ async function recoverWithOutageFallback(options) {
19
18
  return recoverProjectionPolicyHistory({ ...options, offline: true });
20
19
  }
21
20
  }
22
- export function createRuntimeProjectionPolicyResolver(runtime) {
23
- const lease = readPrincipalHistoryProtection(runtime);
24
- const historyReader = apiProjectionPolicyHistoryReader(runtime.apiClient);
21
+ export function createProjectionPolicyHistoryResolver(collaborators) {
22
+ const lease = collaborators.withPrincipalHistoryProtection;
23
+ const historyReader = apiProjectionPolicyHistoryReader(collaborators.apiClient);
25
24
  if (!lease || !historyReader)
26
25
  return undefined;
27
- return (input) => getOrCreatePrincipalPolicyCoordinator(runtime.infra.execSql).queueRecovery(input.organizationId, () => runWithSecurityIncidentReporting(runtime.util.reportSecurityIncident, {
26
+ return (input) => getOrCreatePrincipalPolicyCoordinator(collaborators.infra.execSql).queueRecovery(input.organizationId, () => runWithSecurityIncidentReporting(collaborators.util.reportSecurityIncident, {
28
27
  objectId: input.organizationId,
29
28
  objectKind: "principal",
30
29
  operation: "principal.projection.recover",
@@ -36,11 +35,11 @@ export function createRuntimeProjectionPolicyResolver(runtime) {
36
35
  const policies = await recoverWithOutageFallback({
37
36
  ...input,
38
37
  historyReader,
39
- execSql: runtime.infra.execSql,
38
+ execSql: collaborators.infra.execSql,
40
39
  protection,
41
40
  stillCurrent,
42
- offline: runtime.state?.online === false,
43
- resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,
41
+ offline: collaborators.state?.online === false,
42
+ resolveTrustedUserIdentity: collaborators.resolveTrustedUserIdentity,
44
43
  });
45
44
  return { policies, stillCurrent };
46
45
  }