@tearleads/client-sdk 0.1.16 → 0.1.18

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 (158) hide show
  1. package/client/index.d.ts +1 -1
  2. package/client/index.js.map +1 -1
  3. package/client/organizations/currentPrincipalMutations.js +96 -0
  4. package/client/organizations/currentPrincipalMutations.js.map +1 -0
  5. package/client/organizations/index.d.ts +1 -1
  6. package/client/organizations/index.js +4 -3
  7. package/client/organizations/index.js.map +1 -1
  8. package/client/organizations/organizationGroupHistory.js +44 -0
  9. package/client/organizations/organizationGroupHistory.js.map +1 -0
  10. package/client/organizations/organizationGroupNameHydration.js +7 -1
  11. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  12. package/client/organizations/organizationGroupPresentation.d.ts +1 -0
  13. package/client/organizations/organizationGroupPresentation.js +16 -2
  14. package/client/organizations/organizationGroupPresentation.js.map +1 -1
  15. package/client/organizations/organizationReadModels.d.ts +1 -1
  16. package/client/organizations/organizationReadModels.js +11 -1
  17. package/client/organizations/organizationReadModels.js.map +1 -1
  18. package/client/organizations/organizationsTypes.d.ts +8 -5
  19. package/client/organizations/organizationsTypes.js.map +1 -1
  20. package/client/organizations/principalContainerMutations.js +2 -0
  21. package/client/organizations/principalContainerMutations.js.map +1 -1
  22. package/client/organizations/principalMutations.d.ts +4 -308
  23. package/client/organizations/principalMutations.js +165 -87
  24. package/client/organizations/principalMutations.js.map +1 -1
  25. package/client/principalMutationApi.d.ts +1 -1
  26. package/client/principalMutationApi.js +5 -13
  27. package/client/principalMutationApi.js.map +1 -1
  28. package/client/principalMutationDispatch.js +54 -0
  29. package/client/principalMutationDispatch.js.map +1 -0
  30. package/data/persistence/principalCurrentAcknowledgementPersistence.d.ts +2 -2
  31. package/data/persistence/principalCurrentAcknowledgementPersistence.js +21 -14
  32. package/data/persistence/principalCurrentAcknowledgementPersistence.js.map +1 -1
  33. package/data/principals/currentPolicyReferenceResolver.js +2 -0
  34. package/data/principals/currentPolicyReferenceResolver.js.map +1 -0
  35. package/data/principals/principalHistoryScopeProtection.js +23 -0
  36. package/data/principals/principalHistoryScopeProtection.js.map +1 -0
  37. package/data/principals/principalMutationJournal.d.ts +2 -5
  38. package/data/principals/principalMutationJournal.js +3 -20
  39. package/data/principals/principalMutationJournal.js.map +1 -1
  40. package/data/principals/principalMutationJournalShape.d.ts +26 -0
  41. package/data/principals/principalMutationJournalShape.js +46 -0
  42. package/data/principals/principalMutationJournalShape.js.map +1 -0
  43. package/data/principals/principalPolicyAdminSigners.js.map +1 -1
  44. package/index.d.ts +2 -2
  45. package/index.js.map +1 -1
  46. package/internal/api-client/ApiClient.d.ts +267 -3
  47. package/internal/api-client/ApiClient.js +11 -29
  48. package/internal/api-client/ApiClient.js.map +1 -1
  49. package/internal/api-client/principalPolicyRequests.d.ts +266 -1
  50. package/internal/api-client/principalPolicyRequests.js +43 -1
  51. package/internal/api-client/principalPolicyRequests.js.map +1 -1
  52. package/internal/crypto/index.d.ts +1 -1
  53. package/internal/crypto/index.js +1 -1
  54. package/internal/crypto/index.js.map +1 -1
  55. package/internal/crypto/keying/index.d.ts +1 -0
  56. package/internal/crypto/keying/index.js +1 -0
  57. package/internal/crypto/keying/index.js.map +1 -1
  58. package/internal/crypto/keying/principalPolicyCurrentPredecessorReferences.d.ts +8 -0
  59. package/internal/crypto/keying/principalPolicyCurrentPredecessorReferences.js +46 -0
  60. package/internal/crypto/keying/principalPolicyCurrentPredecessorReferences.js.map +1 -0
  61. package/internal/validators/operation/organizations.d.ts +54 -0
  62. package/internal/validators/operation/organizations.js +19 -4
  63. package/internal/validators/operation/organizations.js.map +1 -1
  64. package/package.json +1 -1
  65. package/workflows/containers/child/carriedDescendantRekeys.js +9 -1
  66. package/workflows/containers/child/carriedDescendantRekeys.js.map +1 -1
  67. package/workflows/containers/child/replacementPrincipalPolicyReferences.js +19 -0
  68. package/workflows/containers/child/replacementPrincipalPolicyReferences.js.map +1 -0
  69. package/workflows/organizations/commitCurrentGroupPolicyMutation.js +72 -0
  70. package/workflows/organizations/commitCurrentGroupPolicyMutation.js.map +1 -0
  71. package/workflows/organizations/createCurrentOrganizationGroup.js +85 -0
  72. package/workflows/organizations/createCurrentOrganizationGroup.js.map +1 -0
  73. package/workflows/organizations/currentGroupMetadataAuthority.js +24 -3
  74. package/workflows/organizations/currentGroupMetadataAuthority.js.map +1 -1
  75. package/workflows/organizations/currentGroupMutationReferences.js +35 -0
  76. package/workflows/organizations/currentGroupMutationReferences.js.map +1 -0
  77. package/workflows/organizations/currentGroupPolicyMutationContext.js +79 -0
  78. package/workflows/organizations/currentGroupPolicyMutationContext.js.map +1 -0
  79. package/workflows/organizations/currentOrganizationGroupNames.js +5 -1
  80. package/workflows/organizations/currentOrganizationGroupNames.js.map +1 -1
  81. package/workflows/organizations/currentOrganizationMutationAuthority.js +16 -0
  82. package/workflows/organizations/currentOrganizationMutationAuthority.js.map +1 -0
  83. package/workflows/organizations/currentOrganizationMutationRetention.js +53 -0
  84. package/workflows/organizations/currentOrganizationMutationRetention.js.map +1 -0
  85. package/workflows/organizations/currentPrincipalMutationLease.js +38 -0
  86. package/workflows/organizations/currentPrincipalMutationLease.js.map +1 -0
  87. package/workflows/organizations/deleteCurrentOrganizationGroup.js +35 -0
  88. package/workflows/organizations/deleteCurrentOrganizationGroup.js.map +1 -0
  89. package/workflows/organizations/deleteOrganizationGroup.d.ts +1 -0
  90. package/workflows/organizations/deleteOrganizationGroup.js +10 -0
  91. package/workflows/organizations/deleteOrganizationGroup.js.map +1 -1
  92. package/workflows/organizations/groupCreation.d.ts +1 -0
  93. package/workflows/organizations/groupCreation.js +8 -0
  94. package/workflows/organizations/groupCreation.js.map +1 -1
  95. package/workflows/organizations/groupMembershipName.d.ts +1 -1
  96. package/workflows/organizations/groupMembershipName.js.map +1 -1
  97. package/workflows/organizations/groupMetadataRuntime.js +14 -9
  98. package/workflows/organizations/groupMetadataRuntime.js.map +1 -1
  99. package/workflows/organizations/groupNameUniqueness.js +1 -1
  100. package/workflows/organizations/groupNameUniqueness.js.map +1 -1
  101. package/workflows/organizations/groupPolicyHistoryPage.js +31 -0
  102. package/workflows/organizations/groupPolicyHistoryPage.js.map +1 -0
  103. package/workflows/organizations/groupPolicyMutationAcknowledgement.js +1 -0
  104. package/workflows/organizations/groupPolicyMutationAcknowledgement.js.map +1 -1
  105. package/workflows/organizations/groupPolicyMutationContext.d.ts +18 -0
  106. package/workflows/organizations/groupPolicyMutationContext.js +1 -1
  107. package/workflows/organizations/groupPolicyMutationContext.js.map +1 -1
  108. package/workflows/organizations/index.d.ts +1 -0
  109. package/workflows/organizations/index.js.map +1 -1
  110. package/workflows/organizations/initialPrincipalCurrentPublication.js +83 -0
  111. package/workflows/organizations/initialPrincipalCurrentPublication.js.map +1 -0
  112. package/workflows/organizations/organizationGroupDirectory.js +6 -0
  113. package/workflows/organizations/organizationGroupDirectory.js.map +1 -1
  114. package/workflows/organizations/organizationGroupNames.js.map +1 -1
  115. package/workflows/organizations/policyHistoryTypes.d.ts +2 -0
  116. package/workflows/organizations/policyHistoryTypes.js.map +1 -1
  117. package/workflows/organizations/principalContainerRematerialization.js +12 -2
  118. package/workflows/organizations/principalContainerRematerialization.js.map +1 -1
  119. package/workflows/organizations/principalContainerRematerializationPlanning.js +1 -0
  120. package/workflows/organizations/principalContainerRematerializationPlanning.js.map +1 -1
  121. package/workflows/organizations/principalContainerRematerializationTargets.js.map +1 -1
  122. package/workflows/organizations/principalMutationJournalSession.d.ts +3 -3
  123. package/workflows/organizations/principalMutationJournalSession.js +2 -2
  124. package/workflows/organizations/principalMutationJournalSession.js.map +1 -1
  125. package/workflows/organizations/principalMutationReceipt.js +13 -12
  126. package/workflows/organizations/principalMutationReceipt.js.map +1 -1
  127. package/workflows/organizations/principalOperationReceipt.d.ts +5 -0
  128. package/workflows/organizations/principalOperationReceipt.js +36 -0
  129. package/workflows/organizations/principalOperationReceipt.js.map +1 -0
  130. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.d.ts +2 -0
  131. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js +5 -1
  132. package/workflows/organizations/retainAcknowledgedPrincipalCurrents.js.map +1 -1
  133. package/workflows/organizations/runtimeCurrentGroupMutation.js +85 -0
  134. package/workflows/organizations/runtimeCurrentGroupMutation.js.map +1 -0
  135. package/workflows/organizations/runtimeCurrentOrganizationMutation.js +48 -0
  136. package/workflows/organizations/runtimeCurrentOrganizationMutation.js.map +1 -0
  137. package/workflows/principals/loadRecoveredPrincipalHistoryPage.d.ts +11 -0
  138. package/workflows/principals/loadRecoveredPrincipalHistoryPage.js +120 -0
  139. package/workflows/principals/loadRecoveredPrincipalHistoryPage.js.map +1 -0
  140. package/workflows/principals/principalHistoryRecoveryReferences.js +8 -0
  141. package/workflows/principals/principalHistoryRecoveryReferences.js.map +1 -1
  142. package/workflows/principals/principalRecoveryDirectory.js +3 -8
  143. package/workflows/principals/principalRecoveryDirectory.js.map +1 -1
  144. package/workflows/principals/principalRecoveryLocalPreference.js +3 -2
  145. package/workflows/principals/principalRecoveryLocalPreference.js.map +1 -1
  146. package/workflows/principals/recoverCurrentOrganizationPolicy.js.map +1 -1
  147. package/workflows/principals/recoverPrincipalHistoryPage.js +30 -0
  148. package/workflows/principals/recoverPrincipalHistoryPage.js.map +1 -0
  149. package/workflows/principals/recoverPrincipalPolicyHistory.d.ts +2 -0
  150. package/workflows/principals/recoverPrincipalPolicyHistory.js +14 -2
  151. package/workflows/principals/recoverPrincipalPolicyHistory.js.map +1 -1
  152. package/workflows/principals/recoverScopedPrincipalPolicyHistory.d.ts +6 -0
  153. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js +31 -19
  154. package/workflows/principals/recoverScopedPrincipalPolicyHistory.js.map +1 -1
  155. package/workflows/principals/runtimePolicyRecovery.js +25 -4
  156. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  157. package/workflows/principals/runtimePolicyWarmer.js +2 -2
  158. package/workflows/principals/runtimePolicyWarmer.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"principalContainerRematerialization.js","sourceRoot":"","sources":["principalContainerRematerialization.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EAAE,8BAA8B,EAAE,MAAM,iDAAiD,CAAC;AAEjG,OAAO,EAAE,iCAAiC,EAAE,MAAM,sDAAsD,CAAC;AACzG,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAEL,+BAA+B,GAChC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,yDAAyD,CAAC;AAC1G,OAAO,EAAE,uBAAuB,EAAE,MAAM,6CAA6C,CAAC;AACtF,OAAO,EAAE,iCAAiC,EAAE,MAAM,4BAA4B,CAAC;AAC/E,OAAO,EAAE,mCAAmC,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EAAE,oCAAoC,EAAE,MAAM,4BAA4B,CAAC;AAClF,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAC;AAC/F,OAAO,EACL,OAAO,EAEP,UAAU,EAEV,gBAAgB,GACjB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,4BAA4B,EAC5B,oBAAoB,EAIpB,WAAW,EACX,0BAA0B,GAC3B,MAAM,8CAA8C,CAAC;AAEtD,SAAS,kBAAkB,CAAC,KAG3B;IACC,OAAO,CACL,KAAK,CAAC,YAAY,CAAC,IAAI,CACrB,CAAC,KAAK,EAAE,EAAE,CACR,KAAK,CAAC,WAAW,KAAK,OAAO,IAAI,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,OAAO,CACrE,IAAI,IAAI,CACV,CAAC;AACJ,CAAC;AAED,SAAS,uBAAuB,CAAC,KAKhC;IACC,OAAO,CACL,KAAK,CAAC,wBAAwB,CAAC,IAAI,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;gBAAE,OAAO;YAC1C,MAAM,mBAAmB,GAAG,IAAI,GAAG,EAGhC,CAAC;YACJ,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;gBACzB,MAAM,cAAc,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC;gBACjD,MAAM,KAAK,GAAG,mBAAmB,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,EAAE,CAAC;gBAC5D,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBACjB,mBAAmB,CAAC,GAAG,CAAC,cAAc,EAAE,KAAK,CAAC,CAAC;YACjD,CAAC;YACD,KAAK,MAAM,CAAC,cAAc,EAAE,iBAAiB,CAAC,IAAI,mBAAmB,EAAE,CAAC;gBACtE,IAAI,CAAC;oBACH,8BAA8B,CAAC;wBAC7B,cAAc;wBACd,OAAO,EAAE,KAAK,CAAC,OAAO;wBACtB,KAAK,EAAE,EAAE;wBACT,QAAQ,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC;qBAC7B,CAAC,CAAC;gBACL,CAAC;gBAAC,MAAM,CAAC;oBACP,oEAAoE;oBACpE,SAAS;gBACX,CAAC;gBACD,iCAAiC,CAAC;oBAChC,SAAS,EAAE,KAAK,CAAC,SAAS;oBAC1B,MAAM,EAAE,EAAE,GAAG,KAAK,CAAC,MAAM,EAAE,cAAc,EAAE;oBAC3C,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,KAAK,EAAE,iBAAiB;oBACxB,YAAY,EAAE,SAAS;oBACvB,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;iBACrD,CAAC,CAAC;YACL,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerDirectGrant,\n PrincipalContainerGrant,\n} from \"@tearleads/crypto\";\nimport type { ContainerMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { rememberVerifiedContainerHeads } from \"../../data/containers/shared/heldContainerHeads\";\nimport type { AuthoredContainerMutationHead } from \"../../data/containers/shared/mutationAcknowledgement\";\nimport { acknowledgeContainerMutationBatch } from \"../../data/containers/shared/mutationAcknowledgement\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../data/containers/shared/projection\";\nimport {\n type PrincipalPolicyCache,\n verifyContainerWriterProjection,\n} from \"../../data/keyingProjectionVerification\";\nimport { createProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification/userKeyResolver\";\nimport { rebaseOnDeepestAncestor } from \"../containers/child/carriedDescendantRekeys\";\nimport { scheduleHeldDescendantRecitations } from \"../containers/child/recite\";\nimport { buildMaterializedContainerRekeyPlan } from \"../containers/child/rekey\";\nimport { isSpeculativeContainerWriterProjection } from \"../containers/child/rekeyProjection\";\nimport { buildMaterializedContainerRevokePlan } from \"../containers/child/revoke\";\nimport { buildMaterializedContainerSharePlan } from \"../containers/child/shareMaterialization\";\nimport {\n addPlan,\n type BatchPlanning,\n carryLevel,\n type PrincipalContainerRematerializationInput,\n staleLevelsAbove,\n} from \"./principalContainerRematerializationPlanning\";\nimport {\n loadRematerializationTargets,\n loadServedProjection,\n type MaterializedPrincipalContainerMutationPlan,\n type PlannedRematerialization,\n type RematerializationTarget,\n rotatedPath,\n seededPrincipalPolicyCache,\n} from \"./principalContainerRematerializationTargets\";\n\nfunction matchingGroupGrant(input: {\n readonly directGrants: readonly ContainerDirectGrant[];\n readonly groupId: string;\n}): ContainerDirectGrant | null {\n return (\n input.directGrants.find(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n ) ?? null\n );\n}\n\nfunction referencedGroupKeyEpoch(input: {\n readonly groupId: string;\n readonly referencedPrincipalHeads: ReturnType<\n typeof readContainerState\n >[\"referencedPrincipalHeads\"];\n}): number | null {\n return (\n input.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n )?.keyEpoch ?? null\n );\n}\n\nasync function loadGrantedContainerContext(\n input: PrincipalContainerRematerializationInput,\n grantRow: PrincipalContainerGrant,\n projection: ContainerWriterProjectionResponse,\n principalPolicyCache: PrincipalPolicyCache,\n) {\n // A projection re-rooted on a rotation this batch has yet to commit must\n // not pin anything: its heads are speculative until acknowledged, and a\n // pin past the group's served head would refuse the other served paths.\n await verifyContainerWriterProjection({\n execSql: input.execSql,\n persistVerificationCheckpoints:\n !isSpeculativeContainerWriterProjection(projection),\n principalPolicyCache,\n projection,\n resolveUserKey: createProjectionUserKeyResolver({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n }),\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const state = readContainerState(\n getTargetContainerContext(projection).manifest,\n );\n const grant = matchingGroupGrant({\n directGrants: state.directGrants,\n groupId: input.groupId,\n });\n if (grant && grant.accessLevel !== grantRow.accessLevel) {\n const nextGrant = input.nextPolicy.grants.find(\n (candidate) => candidate.containerId === grantRow.containerId,\n );\n if (!nextGrant || nextGrant.accessLevel !== grantRow.accessLevel) {\n throw new Error(\n `Container ${grantRow.containerId} does not contain the expected group grant`,\n );\n }\n }\n const referencedKeyEpoch = referencedGroupKeyEpoch({\n groupId: input.groupId,\n referencedPrincipalHeads: state.referencedPrincipalHeads,\n });\n if (grant && referencedKeyEpoch === null) {\n throw new Error(\n `Container ${grantRow.containerId} is missing its group reference`,\n );\n }\n return { grant, projection, referencedKeyEpoch };\n}\n\nexport async function buildPrincipalContainerRematerializationBatch(\n input: PrincipalContainerRematerializationInput,\n): Promise<ContainerMutationRequest[]> {\n return (\n await buildPrincipalContainerRematerializationPlans(input)\n ).entries.map((entry) => entry.planned.plan.request);\n}\n\nexport interface PreparedPrincipalContainerRematerializationBatch {\n readonly retiredContainerIds: readonly string[];\n readonly acknowledge: (\n responses: readonly ContainerMutationResponse[],\n stillCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n /**\n * Re-sign the batch with the descendant rekeys the server named for its\n * rotations woven in, parent-first, each against the path the batch will\n * leave behind. A named container the batch already rotates is re-planned\n * under what is carried above it, so no container rotates twice. Returns the\n * whole request list, which replaces `requests`; `acknowledge` then expects\n * the responses in that order.\n */\n readonly carry: (\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>;\n readonly plans: readonly MaterializedPrincipalContainerMutationPlan[];\n readonly requests: readonly ContainerMutationRequest[];\n}\n\nfunction authoredMutationHead(\n planned: MaterializedPrincipalContainerMutationPlan,\n): AuthoredContainerMutationHead {\n return planned.plan;\n}\n\nasync function buildPrincipalContainerRematerializationPlan(input: {\n readonly grantRow: PrincipalContainerGrant;\n /** Keys the batch minted above this container; see `BatchPlanning`. */\n readonly knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n /** Holds the policy this batch commits, which rebased paths already cite. */\n readonly principalPolicyCache: PrincipalPolicyCache;\n /** The served projection, re-rooted on any rotation planned above it. */\n readonly projection: ContainerWriterProjectionResponse;\n readonly rematerialization: PrincipalContainerRematerializationInput;\n readonly resolveProjectionUserKey: ReturnType<\n typeof createProjectionUserKeyResolver\n >;\n}): Promise<MaterializedPrincipalContainerMutationPlan> {\n const { grantRow, rematerialization } = input;\n const { grant, projection, referencedKeyEpoch } =\n await loadGrantedContainerContext(\n rematerialization,\n grantRow,\n input.projection,\n input.principalPolicyCache,\n );\n const nextGrant = rematerialization.nextPolicy.grants.find(\n (candidate) => candidate.containerId === grantRow.containerId,\n );\n const author = {\n ...rematerialization.author,\n organizationId: projection.organizationId,\n };\n const sharedInput = {\n author,\n execSql: rematerialization.execSql,\n knownContainerKeks: input.knownContainerKeks,\n // Planning against a path this batch has yet to commit pins nothing; the\n // acknowledgement advances every head at once. The rekey planner applies\n // this rule itself; revoke and grant planning take it from here.\n persistVerificationCheckpoints:\n !isSpeculativeContainerWriterProjection(projection),\n previousProjection: projection,\n principalPolicyCache: input.principalPolicyCache,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: rematerialization.stillCurrent,\n targetSecretKey: rematerialization.targetSecretKey,\n warmReferencedPrincipalPolicies:\n rematerialization.warmReferencedPrincipalPolicies,\n };\n if (grantRow.containerId === rematerialization.revokedContainerId) {\n if (!grant) {\n throw new Error(\n `Container ${grantRow.containerId} does not contain the revoked group grant`,\n );\n }\n return buildMaterializedContainerRevokePlan({\n ...sharedInput,\n replacementPrincipalPolicy: rematerialization.nextPolicy,\n revokedSubject: {\n subjectId: rematerialization.groupId,\n subjectType: \"group\",\n },\n });\n }\n if (!grant || grant.accessLevel !== nextGrant?.accessLevel) {\n if (!nextGrant) {\n throw new Error(\n `Container ${grantRow.containerId} is absent from the next group grant set`,\n );\n }\n return buildMaterializedContainerSharePlan({\n ...sharedInput,\n accessLevel: nextGrant.accessLevel,\n recipient: {\n principalPolicy: rematerialization.nextPolicy,\n subjectId: rematerialization.groupId,\n subjectType: \"group\",\n },\n });\n }\n if (referencedKeyEpoch === rematerialization.nextPolicy.keyEpoch) {\n return buildMaterializedContainerSharePlan({\n ...sharedInput,\n accessLevel: grant.accessLevel,\n recipient: {\n principalPolicy: rematerialization.nextPolicy,\n subjectId: rematerialization.groupId,\n subjectType: \"group\",\n },\n });\n }\n return buildMaterializedContainerRekeyPlan({\n ...sharedInput,\n replacementPrincipalPolicy: rematerialization.nextPolicy,\n });\n}\n\n/**\n * Plan one target against the paths already planned above it. A grant's\n * rematerialization extends the served head; a rotation's, and every carried\n * rekey, extends the epoch the batch mints above it.\n */\nasync function planRematerializationTarget(\n batch: BatchPlanning,\n target: RematerializationTarget,\n): Promise<void> {\n const { rematerialization } = batch;\n let rebased = rebaseOnDeepestAncestor(target.projection, batch.rotatedAbove);\n const stale = rebased\n ? staleLevelsAbove(\n rebased.projection,\n rebased.ancestor.containerKeks.at(-1)?.containerId ?? \"\",\n )\n : [];\n for (const containerId of stale) {\n await carryLevel(\n batch,\n await loadServedProjection(rematerialization.apiClient, containerId),\n );\n }\n if (!target.grantRow) {\n await carryLevel(batch, target.projection);\n return;\n }\n // Each level carried above re-roots the target one step deeper.\n if (stale.length > 0) {\n rebased = rebaseOnDeepestAncestor(target.projection, batch.rotatedAbove);\n }\n const previousProjection = rebased?.projection ?? target.projection;\n const planned = await buildPrincipalContainerRematerializationPlan({\n grantRow: target.grantRow,\n knownContainerKeks: batch.knownContainerKeks,\n principalPolicyCache: batch.principalPolicyCache,\n projection: previousProjection,\n rematerialization,\n resolveProjectionUserKey: batch.resolveProjectionUserKey,\n });\n addPlan(batch, {\n carried: false,\n planned,\n rotated: await rotatedPath({ planned, previousProjection }),\n });\n}\n\n/**\n * Sign the batch parent-first. `carriedContainerIds` are the descendant rekeys\n * a refused attempt was told to carry; woven in by depth, each sits under the\n * rotation it rides, and a named container the batch rematerializes anyway is\n * re-planned there rather than rotated twice.\n */\nasync function buildPrincipalContainerRematerializationPlans(\n input: PrincipalContainerRematerializationInput,\n carriedContainerIds: readonly string[] = [],\n): Promise<{\n entries: PlannedRematerialization[];\n retiredContainerIds: readonly string[];\n}> {\n if (\n input.revokedContainerId &&\n !input.grants.some(\n (grant) => grant.containerId === input.revokedContainerId,\n )\n ) {\n throw new Error(\"Revoked container is not granted to the group\");\n }\n const { targets, retiredContainerIds } = await loadRematerializationTargets({\n apiClient: input.apiClient,\n carriedContainerIds,\n grants: input.grants,\n });\n const batch: BatchPlanning = {\n knownContainerKeks: new Map(),\n plans: [],\n // A rotation planned above cites the group at the head this batch commits,\n // which no store holds yet; the cache is what lets a rebased path verify.\n principalPolicyCache: seededPrincipalPolicyCache(input.nextPolicy),\n rematerialization: input,\n resolveProjectionUserKey: createProjectionUserKeyResolver({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n }),\n rotatedAbove: [],\n };\n for (const target of targets) {\n await planRematerializationTarget(batch, target);\n }\n return { entries: batch.plans, retiredContainerIds };\n}\n\n/**\n * The server names a level it found pinned to a retired epoch. A batch answers\n * with a rotation of it: a carried rekey, or its own rematerialization when\n * that is a rekey or revoke. A rematerialized grant rotates nothing, so a\n * batch that both grants a container and must re-key it cannot be signed;\n * no policy change the SDK builds combines the two.\n */\nfunction assertNamedContainersRotated(\n plans: readonly PlannedRematerialization[],\n requiredContainerIds: readonly string[],\n): void {\n const rotatedIds = new Set(\n plans.flatMap((entry) =>\n entry.rotated ? [entry.planned.plan.containerId] : [],\n ),\n );\n const unrotated = requiredContainerIds\n .slice(0, MAX_ROTATION_CONTAINER_REKEYS)\n .find((containerId) => !rotatedIds.has(containerId));\n if (unrotated !== undefined) {\n throw new Error(\n `Container ${unrotated} needs a rekey this policy change only grants`,\n );\n }\n}\n\nexport async function preparePrincipalContainerRematerializationBatch(\n input: PrincipalContainerRematerializationInput,\n): Promise<PreparedPrincipalContainerRematerializationBatch> {\n let { entries, retiredContainerIds } =\n await buildPrincipalContainerRematerializationPlans(input);\n const requests = () => entries.map((entry) => entry.planned.plan.request);\n return {\n get retiredContainerIds() {\n return retiredContainerIds;\n },\n get plans() {\n return entries.map((entry) => entry.planned);\n },\n get requests() {\n return requests();\n },\n carry: async (requiredContainerIds) => {\n // The refused attempt rolled back whole, so every served head still\n // stands; the batch is signed again from them with the named levels in.\n const replanned = await buildPrincipalContainerRematerializationPlans(\n input,\n requiredContainerIds,\n );\n assertNamedContainersRotated(replanned.entries, requiredContainerIds);\n entries = replanned.entries;\n retiredContainerIds = replanned.retiredContainerIds;\n return requests();\n },\n acknowledge: async (responses, stillCurrent) => {\n const isCurrent = () =>\n input.stillCurrent?.() !== false && stillCurrent?.() !== false;\n const heads = entries.map((entry) => authoredMutationHead(entry.planned));\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.execSql,\n plans: heads,\n responses,\n stillCurrent: isCurrent,\n });\n if (!acknowledged || !isCurrent()) return;\n const plansByOrganization = new Map<\n string,\n AuthoredContainerMutationHead[]\n >();\n for (const head of heads) {\n const organizationId = head.state.organizationId;\n const group = plansByOrganization.get(organizationId) ?? [];\n group.push(head);\n plansByOrganization.set(organizationId, group);\n }\n for (const [organizationId, organizationPlans] of plansByOrganization) {\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql,\n heads: [],\n policies: [input.nextPolicy],\n });\n } catch {\n // Cache failure must not invalidate the durably acknowledged batch.\n continue;\n }\n scheduleHeldDescendantRecitations({\n apiClient: input.apiClient,\n author: { ...input.author, organizationId },\n execSql: input.execSql,\n plans: organizationPlans,\n stillCurrent: isCurrent,\n reportSecurityIncident: input.reportSecurityIncident,\n });\n }\n },\n };\n}\n"]}
1
+ {"version":3,"file":"principalContainerRematerialization.js","sourceRoot":"","sources":["principalContainerRematerialization.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EAAE,8BAA8B,EAAE,MAAM,iDAAiD,CAAC;AAEjG,OAAO,EAAE,iCAAiC,EAAE,MAAM,sDAAsD,CAAC;AACzG,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAEL,+BAA+B,GAChC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,+BAA+B,EAAE,MAAM,yDAAyD,CAAC;AAC1G,OAAO,EAAE,uBAAuB,EAAE,MAAM,6CAA6C,CAAC;AACtF,OAAO,EAAE,iCAAiC,EAAE,MAAM,4BAA4B,CAAC;AAC/E,OAAO,EAAE,mCAAmC,EAAE,MAAM,2BAA2B,CAAC;AAChF,OAAO,EAAE,sCAAsC,EAAE,MAAM,qCAAqC,CAAC;AAC7F,OAAO,EAAE,0CAA0C,EAAE,MAAM,0DAA0D,CAAC;AACtH,OAAO,EAAE,oCAAoC,EAAE,MAAM,4BAA4B,CAAC;AAClF,OAAO,EAAE,mCAAmC,EAAE,MAAM,0CAA0C,CAAC;AAC/F,OAAO,EACL,OAAO,EAEP,UAAU,EAEV,gBAAgB,GACjB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,4BA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AO;wBACtB,KAAK,EAAE,EAAE;wBACT,QAAQ,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC;qBAC7B,CAAC,CAAC;gBACL,CAAC;gBAAC,MAAM,CAAC;oBACP,oEAAoE;oBACpE,SAAS;gBACX,CAAC;gBACD,iCAAiC,CAAC;oBAChC,SAAS,EAAE,KAAK,CAAC,SAAS;oBAC1B,MAAM,EAAE,EAAE,GAAG,KAAK,CAAC,MAAM,EAAE,cAAc,EAAE;oBAC3C,OAAO,EAAE,KAAK,CAAC,OAAO;oBACtB,KAAK,EAAE,iBAAiB;oBACxB,YAAY,EAAE,KAAK,CAAC,sBAAsB,IAAI,SAAS;oBACvD,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;iBACrD,CAAC,CAAC;YACL,CAAC;QACH,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n ContainerDirectGrant,\n PrincipalContainerGrant,\n} from \"@tearleads/crypto\";\nimport type { ContainerMutationRequest } from \"@tearleads/validators/request\";\nimport type {\n ContainerMutationResponse,\n ContainerWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { rememberVerifiedContainerHeads } from \"../../data/containers/shared/heldContainerHeads\";\nimport type { AuthoredContainerMutationHead } from \"../../data/containers/shared/mutationAcknowledgement\";\nimport { acknowledgeContainerMutationBatch } from \"../../data/containers/shared/mutationAcknowledgement\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../data/containers/shared/projection\";\nimport {\n type PrincipalPolicyCache,\n verifyContainerWriterProjection,\n} from \"../../data/keyingProjectionVerification\";\nimport { createProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification/userKeyResolver\";\nimport { rebaseOnDeepestAncestor } from \"../containers/child/carriedDescendantRekeys\";\nimport { scheduleHeldDescendantRecitations } from \"../containers/child/recite\";\nimport { buildMaterializedContainerRekeyPlan } from \"../containers/child/rekey\";\nimport { isSpeculativeContainerWriterProjection } from \"../containers/child/rekeyProjection\";\nimport { selectReplacementPrincipalPolicyReferences } from \"../containers/child/replacementPrincipalPolicyReferences\";\nimport { buildMaterializedContainerRevokePlan } from \"../containers/child/revoke\";\nimport { buildMaterializedContainerSharePlan } from \"../containers/child/shareMaterialization\";\nimport {\n addPlan,\n type BatchPlanning,\n carryLevel,\n type PrincipalContainerRematerializationInput,\n staleLevelsAbove,\n} from \"./principalContainerRematerializationPlanning\";\nimport {\n loadRematerializationTargets,\n loadServedProjection,\n type MaterializedPrincipalContainerMutationPlan,\n type PlannedRematerialization,\n type RematerializationTarget,\n rotatedPath,\n seededPrincipalPolicyCache,\n} from \"./principalContainerRematerializationTargets\";\n\nfunction matchingGroupGrant(input: {\n readonly directGrants: readonly ContainerDirectGrant[];\n readonly groupId: string;\n}): ContainerDirectGrant | null {\n return (\n input.directGrants.find(\n (grant) =>\n grant.subjectType === \"group\" && grant.subjectId === input.groupId,\n ) ?? null\n );\n}\n\nfunction referencedGroupKeyEpoch(input: {\n readonly groupId: string;\n readonly referencedPrincipalHeads: ReturnType<\n typeof readContainerState\n >[\"referencedPrincipalHeads\"];\n}): number | null {\n return (\n input.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.groupId,\n )?.keyEpoch ?? null\n );\n}\n\nasync function loadGrantedContainerContext(\n input: PrincipalContainerRematerializationInput,\n grantRow: PrincipalContainerGrant,\n projection: ContainerWriterProjectionResponse,\n principalPolicyCache: PrincipalPolicyCache,\n) {\n // A projection re-rooted on a rotation this batch has yet to commit must\n // not pin anything: its heads are speculative until acknowledged, and a\n // pin past the group's served head would refuse the other served paths.\n await verifyContainerWriterProjection({\n execSql: input.execSql,\n persistVerificationCheckpoints:\n !isSpeculativeContainerWriterProjection(projection),\n principalPolicyCache,\n projection,\n resolveUserKey: createProjectionUserKeyResolver({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n }),\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const state = readContainerState(\n getTargetContainerContext(projection).manifest,\n );\n const grant = matchingGroupGrant({\n directGrants: state.directGrants,\n groupId: input.groupId,\n });\n if (grant && grant.accessLevel !== grantRow.accessLevel) {\n const nextGrant = input.nextPolicy.grants.find(\n (candidate) => candidate.containerId === grantRow.containerId,\n );\n if (!nextGrant || nextGrant.accessLevel !== grantRow.accessLevel) {\n throw new Error(\n `Container ${grantRow.containerId} does not contain the expected group grant`,\n );\n }\n }\n const referencedKeyEpoch = referencedGroupKeyEpoch({\n groupId: input.groupId,\n referencedPrincipalHeads: state.referencedPrincipalHeads,\n });\n if (grant && referencedKeyEpoch === null) {\n throw new Error(\n `Container ${grantRow.containerId} is missing its group reference`,\n );\n }\n return { grant, projection, referencedKeyEpoch };\n}\n\nexport async function buildPrincipalContainerRematerializationBatch(\n input: PrincipalContainerRematerializationInput,\n): Promise<ContainerMutationRequest[]> {\n return (\n await buildPrincipalContainerRematerializationPlans(input)\n ).entries.map((entry) => entry.planned.plan.request);\n}\n\nexport interface PreparedPrincipalContainerRematerializationBatch {\n readonly retiredContainerIds: readonly string[];\n readonly acknowledge: (\n responses: readonly ContainerMutationResponse[],\n stillCurrent?: (() => boolean) | undefined,\n ) => Promise<void>;\n /**\n * Re-sign the batch with the descendant rekeys the server named for its\n * rotations woven in, parent-first, each against the path the batch will\n * leave behind. A named container the batch already rotates is re-planned\n * under what is carried above it, so no container rotates twice. Returns the\n * whole request list, which replaces `requests`; `acknowledge` then expects\n * the responses in that order.\n */\n readonly carry: (\n requiredContainerIds: readonly string[],\n ) => Promise<readonly ContainerMutationRequest[]>;\n readonly plans: readonly MaterializedPrincipalContainerMutationPlan[];\n readonly requests: readonly ContainerMutationRequest[];\n}\n\nfunction authoredMutationHead(\n planned: MaterializedPrincipalContainerMutationPlan,\n): AuthoredContainerMutationHead {\n return planned.plan;\n}\n\nasync function buildPrincipalContainerRematerializationPlan(input: {\n readonly grantRow: PrincipalContainerGrant;\n /** Keys the batch minted above this container; see `BatchPlanning`. */\n readonly knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n /** Holds the policy this batch commits, which rebased paths already cite. */\n readonly principalPolicyCache: PrincipalPolicyCache;\n /** The served projection, re-rooted on any rotation planned above it. */\n readonly projection: ContainerWriterProjectionResponse;\n readonly rematerialization: PrincipalContainerRematerializationInput;\n readonly resolveProjectionUserKey: ReturnType<\n typeof createProjectionUserKeyResolver\n >;\n}): Promise<MaterializedPrincipalContainerMutationPlan> {\n const { grantRow } = input;\n const rematerialization = {\n ...input.rematerialization,\n nextPolicy: await selectReplacementPrincipalPolicyReferences({\n policy: input.rematerialization.nextPolicy,\n projection: input.projection,\n principalPolicyCache: input.principalPolicyCache,\n resolveAuthoredPolicyReferences:\n input.rematerialization.resolveAuthoredPolicyReferences,\n }),\n };\n const { grant, projection, referencedKeyEpoch } =\n await loadGrantedContainerContext(\n rematerialization,\n grantRow,\n input.projection,\n input.principalPolicyCache,\n );\n const nextGrant = rematerialization.nextPolicy.grants.find(\n (candidate) => candidate.containerId === grantRow.containerId,\n );\n const author = {\n ...rematerialization.author,\n organizationId: projection.organizationId,\n };\n const sharedInput = {\n author,\n execSql: rematerialization.execSql,\n knownContainerKeks: input.knownContainerKeks,\n // Planning against a path this batch has yet to commit pins nothing; the\n // acknowledgement advances every head at once. The rekey planner applies\n // this rule itself; revoke and grant planning take it from here.\n persistVerificationCheckpoints:\n !isSpeculativeContainerWriterProjection(projection),\n previousProjection: projection,\n principalPolicyCache: input.principalPolicyCache,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: rematerialization.stillCurrent,\n targetSecretKey: rematerialization.targetSecretKey,\n warmReferencedPrincipalPolicies:\n rematerialization.warmReferencedPrincipalPolicies,\n };\n if (grantRow.containerId === rematerialization.revokedContainerId) {\n if (!grant) {\n throw new Error(\n `Container ${grantRow.containerId} does not contain the revoked group grant`,\n );\n }\n return buildMaterializedContainerRevokePlan({\n ...sharedInput,\n replacementPrincipalPolicy: rematerialization.nextPolicy,\n revokedSubject: {\n subjectId: rematerialization.groupId,\n subjectType: \"group\",\n },\n });\n }\n if (!grant || grant.accessLevel !== nextGrant?.accessLevel) {\n if (!nextGrant) {\n throw new Error(\n `Container ${grantRow.containerId} is absent from the next group grant set`,\n );\n }\n return buildMaterializedContainerSharePlan({\n ...sharedInput,\n accessLevel: nextGrant.accessLevel,\n recipient: {\n principalPolicy: rematerialization.nextPolicy,\n subjectId: rematerialization.groupId,\n subjectType: \"group\",\n },\n });\n }\n if (referencedKeyEpoch === rematerialization.nextPolicy.keyEpoch) {\n return buildMaterializedContainerSharePlan({\n ...sharedInput,\n accessLevel: grant.accessLevel,\n recipient: {\n principalPolicy: rematerialization.nextPolicy,\n subjectId: rematerialization.groupId,\n subjectType: \"group\",\n },\n });\n }\n return buildMaterializedContainerRekeyPlan({\n ...sharedInput,\n replacementPrincipalPolicy: rematerialization.nextPolicy,\n });\n}\n\n/**\n * Plan one target against the paths already planned above it. A grant's\n * rematerialization extends the served head; a rotation's, and every carried\n * rekey, extends the epoch the batch mints above it.\n */\nasync function planRematerializationTarget(\n batch: BatchPlanning,\n target: RematerializationTarget,\n): Promise<void> {\n const { rematerialization } = batch;\n let rebased = rebaseOnDeepestAncestor(target.projection, batch.rotatedAbove);\n const stale = rebased\n ? staleLevelsAbove(\n rebased.projection,\n rebased.ancestor.containerKeks.at(-1)?.containerId ?? \"\",\n )\n : [];\n for (const containerId of stale) {\n await carryLevel(\n batch,\n await loadServedProjection(rematerialization.apiClient, containerId),\n );\n }\n if (!target.grantRow) {\n await carryLevel(batch, target.projection);\n return;\n }\n // Each level carried above re-roots the target one step deeper.\n if (stale.length > 0) {\n rebased = rebaseOnDeepestAncestor(target.projection, batch.rotatedAbove);\n }\n const previousProjection = rebased?.projection ?? target.projection;\n const planned = await buildPrincipalContainerRematerializationPlan({\n grantRow: target.grantRow,\n knownContainerKeks: batch.knownContainerKeks,\n principalPolicyCache: batch.principalPolicyCache,\n projection: previousProjection,\n rematerialization,\n resolveProjectionUserKey: batch.resolveProjectionUserKey,\n });\n addPlan(batch, {\n carried: false,\n planned,\n rotated: await rotatedPath({ planned, previousProjection }),\n });\n}\n\n/**\n * Sign the batch parent-first. `carriedContainerIds` are the descendant rekeys\n * a refused attempt was told to carry; woven in by depth, each sits under the\n * rotation it rides, and a named container the batch rematerializes anyway is\n * re-planned there rather than rotated twice.\n */\nasync function buildPrincipalContainerRematerializationPlans(\n input: PrincipalContainerRematerializationInput,\n carriedContainerIds: readonly string[] = [],\n): Promise<{\n entries: PlannedRematerialization[];\n retiredContainerIds: readonly string[];\n}> {\n if (\n input.revokedContainerId &&\n !input.grants.some(\n (grant) => grant.containerId === input.revokedContainerId,\n )\n ) {\n throw new Error(\"Revoked container is not granted to the group\");\n }\n const { targets, retiredContainerIds } = await loadRematerializationTargets({\n apiClient: input.apiClient,\n carriedContainerIds,\n grants: input.grants,\n });\n const batch: BatchPlanning = {\n knownContainerKeks: new Map(),\n plans: [],\n // A rotation planned above cites the group at the head this batch commits,\n // which no store holds yet; the cache is what lets a rebased path verify.\n principalPolicyCache: seededPrincipalPolicyCache(input.nextPolicy),\n rematerialization: input,\n resolveProjectionUserKey: createProjectionUserKeyResolver({\n resolveTrustedUserIdentity: input.resolveTrustedUserIdentity,\n }),\n rotatedAbove: [],\n };\n for (const target of targets) {\n await planRematerializationTarget(batch, target);\n }\n return { entries: batch.plans, retiredContainerIds };\n}\n\n/**\n * The server names a level it found pinned to a retired epoch. A batch answers\n * with a rotation of it: a carried rekey, or its own rematerialization when\n * that is a rekey or revoke. A rematerialized grant rotates nothing, so a\n * batch that both grants a container and must re-key it cannot be signed;\n * no policy change the SDK builds combines the two.\n */\nfunction assertNamedContainersRotated(\n plans: readonly PlannedRematerialization[],\n requiredContainerIds: readonly string[],\n): void {\n const rotatedIds = new Set(\n plans.flatMap((entry) =>\n entry.rotated ? [entry.planned.plan.containerId] : [],\n ),\n );\n const unrotated = requiredContainerIds\n .slice(0, MAX_ROTATION_CONTAINER_REKEYS)\n .find((containerId) => !rotatedIds.has(containerId));\n if (unrotated !== undefined) {\n throw new Error(\n `Container ${unrotated} needs a rekey this policy change only grants`,\n );\n }\n}\n\nexport async function preparePrincipalContainerRematerializationBatch(\n input: PrincipalContainerRematerializationInput,\n): Promise<PreparedPrincipalContainerRematerializationBatch> {\n let { entries, retiredContainerIds } =\n await buildPrincipalContainerRematerializationPlans(input);\n const requests = () => entries.map((entry) => entry.planned.plan.request);\n return {\n get retiredContainerIds() {\n return retiredContainerIds;\n },\n get plans() {\n return entries.map((entry) => entry.planned);\n },\n get requests() {\n return requests();\n },\n carry: async (requiredContainerIds) => {\n // The refused attempt rolled back whole, so every served head still\n // stands; the batch is signed again from them with the named levels in.\n const replanned = await buildPrincipalContainerRematerializationPlans(\n input,\n requiredContainerIds,\n );\n assertNamedContainersRotated(replanned.entries, requiredContainerIds);\n entries = replanned.entries;\n retiredContainerIds = replanned.retiredContainerIds;\n return requests();\n },\n acknowledge: async (responses, stillCurrent) => {\n const isCurrent = () =>\n input.stillCurrent?.() !== false && stillCurrent?.() !== false;\n const heads = entries.map((entry) => authoredMutationHead(entry.planned));\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.execSql,\n plans: heads,\n responses,\n stillCurrent: isCurrent,\n });\n if (!acknowledged || !isCurrent()) return;\n const plansByOrganization = new Map<\n string,\n AuthoredContainerMutationHead[]\n >();\n for (const head of heads) {\n const organizationId = head.state.organizationId;\n const group = plansByOrganization.get(organizationId) ?? [];\n group.push(head);\n plansByOrganization.set(organizationId, group);\n }\n for (const [organizationId, organizationPlans] of plansByOrganization) {\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql,\n heads: [],\n policies: [input.nextPolicy],\n });\n } catch {\n // Cache failure must not invalidate the durably acknowledged batch.\n continue;\n }\n scheduleHeldDescendantRecitations({\n apiClient: input.apiClient,\n author: { ...input.author, organizationId },\n execSql: input.execSql,\n plans: organizationPlans,\n stillCurrent: input.recitationStillCurrent ?? isCurrent,\n reportSecurityIncident: input.reportSecurityIncident,\n });\n }\n },\n };\n}\n"]}
@@ -27,6 +27,7 @@ export async function carryLevel(batch, served) {
27
27
  // Its path cites the policy this batch commits, so like every
28
28
  // rematerialized rotation it must cite the successor.
29
29
  replacementPrincipalPolicy: rematerialization.nextPolicy,
30
+ resolveAuthoredPolicyReferences: rematerialization.resolveAuthoredPolicyReferences,
30
31
  resolveProjectionUserKey: batch.resolveProjectionUserKey,
31
32
  rotated: batch.rotatedAbove,
32
33
  served,
@@ -1 +1 @@
1
- {"version":3,"file":"principalContainerRematerializationPlanning.js","sourceRoot":"","sources":["principalContainerRematerializationPlanning.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAW3E,OAAO,EACL,0BAA0B,GAE3B,MAAM,6CAA6C,CAAC;AA8CrD,uEAAuE;AACvE,SAAS,YAAY,CAAC,KAAoB;IACxC,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC;AAC7D,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,KAAoB,EACpB,MAAyC;IAEzC,MAAM,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACpC,IAAI,YAAY,CAAC,KAAK,CAAC,IAAI,6BAA6B,EAAE,CAAC;QACzD,MAAM,IAAI,KAAK,CACb,uCAAuC,6BAA6B,oBAAoB,CACzF,CAAC;IACJ,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,0BAA0B,CAAC;QAC/C,SAAS,EAAE,iBAAiB,CAAC,SAAS;QACtC,MAAM,EAAE,iBAAiB,CAAC,MAAM;QAChC,OAAO,EAAE,iBAAiB,CAAC,OAAO;QAClC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,oBAAoB,EAAE,K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;IAC5B,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC;IACzC,MAAM,UAAU,GAAG,OAAO,CAAC,SAAS,CAClC,CAAC,GAAG,EAAE,KAAK,EAAE,EAAE,CACb,KAAK,GAAG,CAAC;QACT,GAAG,CAAC,yBAAyB,KAAK,OAAO,CAAC,KAAK,GAAG,CAAC,CAAC,EAAE,mBAAmB,CAC5E,CAAC;IACF,OAAO,UAAU,GAAG,CAAC;QACnB,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type {\n PrincipalContainerGrant,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport type { ContainerReciteApi } from \"../../data/containers/shared/reciteApi\";\nimport type { ContainerMutationAuthor } from \"../../data/containers/shared/types\";\nimport type {\n PrincipalPolicyCache,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification\";\nimport type { createProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport {\n planCarriedDescendantRekey,\n type SpeculativePath,\n} from \"../containers/child/carriedDescendantRekeys\";\nimport type { PlannedRematerialization } from \"./principalContainerRematerializationTargets\";\n\nexport interface RematerializationApi\n extends ContainerReciteApi,\n Pick<ApiClient, \"getContainerWriterProjectionResult\"> {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport interface PrincipalContainerRematerializationInput {\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly apiClient: RematerializationApi;\n readonly author: ContainerMutationAuthor;\n readonly execSql: ExecSql;\n readonly grants: readonly PrincipalContainerGrant[];\n readonly groupId: string;\n readonly nextPolicy: VerifiedPrincipalPolicy;\n readonly revokedContainerId?: string | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly targetSecretKey: Uint8Array;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/** What the batch has signed so far, in the order it will be submitted. */\nexport interface BatchPlanning {\n /**\n * Keys the batch minted, by epoch id. A rotation wraps its successor to the\n * group at the head this batch commits, which no store can open yet; a\n * level planned beneath it opens that epoch with the key minted here, and\n * its keyring then opens the retired epoch the level below is pinned to.\n */\n readonly knownContainerKeks: Map<string, Uint8Array>;\n readonly plans: PlannedRematerialization[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly rematerialization: PrincipalContainerRematerializationInput;\n readonly resolveProjectionUserKey: ReturnType<\n typeof createProjectionUserKeyResolver\n >;\n readonly rotatedAbove: SpeculativePath[];\n}\n\n/** How many rekeys the batch carries beyond its rematerializations. */\nfunction carriedCount(batch: BatchPlanning): number {\n return batch.plans.filter((entry) => entry.carried).length;\n}\n\n/**\n * Sign a rekey of `served` under the batch's rotations above it, and add it.\n * The server accepts at most `MAX_ROTATION_CONTAINER_REKEYS` carried entries;\n * past that a rematerialization below them could not be signed on a current\n * path, so the batch is refused here, before signing what the server would\n * refuse anyway, and the policy change has to wait for a lazy repair of the\n * tree. Groups granted that far apart on one chain are not a shape the SDK\n * creates.\n */\nexport async function carryLevel(\n batch: BatchPlanning,\n served: ContainerWriterProjectionResponse,\n): Promise<void> {\n const { rematerialization } = batch;\n if (carriedCount(batch) >= MAX_ROTATION_CONTAINER_REKEYS) {\n throw new Error(\n `Policy change would carry more than ${MAX_ROTATION_CONTAINER_REKEYS} descendant rekeys`,\n );\n }\n const planned = await planCarriedDescendantRekey({\n apiClient: rematerialization.apiClient,\n author: rematerialization.author,\n execSql: rematerialization.execSql,\n knownContainerKeks: batch.knownContainerKeks,\n principalPolicyCache: batch.principalPolicyCache,\n // Its path cites the policy this batch commits, so like every\n // rematerialized rotation it must cite the successor.\n replacementPrincipalPolicy: rematerialization.nextPolicy,\n resolveProjectionUserKey: batch.resolveProjectionUserKey,\n rotated: batch.rotatedAbove,\n served,\n stillCurrent: rematerialization.stillCurrent,\n targetSecretKey: rematerialization.targetSecretKey,\n warmReferencedPrincipalPolicies:\n rematerialization.warmReferencedPrincipalPolicies,\n });\n addPlan(batch, { carried: true, planned, rotated: planned.writerProjection });\n}\n\nexport function addPlan(\n batch: BatchPlanning,\n entry: PlannedRematerialization,\n): void {\n batch.plans.push(entry);\n if (!entry.rotated) return;\n batch.rotatedAbove.push(entry.rotated);\n const minted = entry.rotated.containerKeks.at(-1)?.containerKeyEpochId;\n if (minted) batch.knownContainerKeks.set(minted, entry.planned.containerKey);\n}\n\n/**\n * Levels of a re-rooted path pinned to an epoch the batch retires above them:\n * those strictly between the rotated ancestor the path was re-rooted on and\n * the target, parent-first, from the first stale one down. A rotation planned\n * above a target strands every level between the two, and each must be\n * re-keyed under the one above before the target can be signed. The batch\n * carries them without waiting to be told: they are proper ancestors of a\n * granted container, so the server would name them, and a refusal per level\n * is a round trip each. Anything stale above the rotated ancestor is not this\n * batch's doing and is left alone. `carryLevel` holds the count to the cap.\n */\nexport function staleLevelsAbove(\n projection: ContainerWriterProjectionResponse,\n rotatedAncestorId: string,\n): string[] {\n const keks = projection.containerKeks;\n const ancestor = keks.findIndex(\n (kek) => kek.containerId === rotatedAncestorId,\n );\n if (ancestor < 0) return [];\n const between = keks.slice(ancestor, -1);\n const firstStale = between.findIndex(\n (kek, index) =>\n index > 0 &&\n kek.parentContainerKeyEpochId !== between[index - 1]?.containerKeyEpochId,\n );\n return firstStale < 0\n ? []\n : between.slice(firstStale).map((kek) => kek.containerId);\n}\n"]}
1
+ {"version":3,"file":"principalContainerRematerializationPlanning.js","sourceRoot":"","sources":["principalContainerRematerializationPlanning.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAa3E,OAAO,EACL,0BAA0B,GAE3B,MAAM,6CAA6C,CAAC;AAmDrD,uEAAuE;AACvE,SAAS,YAAY,CAAC,KAAoB;IACxC,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC;AAC7D,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAC9B,KAAoB,EACpB,MAAyC;IAEzC,MAAM,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC;IACpC,IAAI,YAAY,CAAC,KAAK,CAAC,IAAI,6BAA6B,EAAE,CAAC;QACzD,MAAM,IAAI,KAAK,CACb,uCAAuC,6BAA6B,oBAAoB,CACzF,CAAC;IACJ,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,0BAA0B,CAAC;QAC/C,SAAS,EAAE,iBAAiB,CAAC,SAAS;QACtC,MAAM,EAAE,iBAAiB,CAAC,MAAM;QAChC,OAAO,EAAE,iBAAiB,CAAC,OAAO;QAClC,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,8DAA8D;QAC9D,sDAAsD;QACtD,0BAA0B,EAAE,iBAAiB,CAAC,UAAU;QACxD,+BAA+B,EAC7B,iBAAiB,CAAC,+BAA+B;QACnD,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,OAAO,EAAE,KAAK,CAAC,YAAY;QAC3B,MAAM;QACN,YAAY,EAAE,iBAAiB,CAAC,YAAY;QAC5C,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,OAAO,CAAC,KAAK,GAAG,CAAC,CAAC,EAAE,mBAAmB,CAC5E,CAAC;IACF,OAAO,UAAU,GAAG,CAAC;QACnB,CAAC,CAAC,EAAE;QACJ,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;AAC9D,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { PrincipalContainerGrant } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport type { ContainerReciteApi } from \"../../data/containers/shared/reciteApi\";\nimport type { ContainerMutationAuthor } from \"../../data/containers/shared/types\";\nimport type {\n PrincipalPolicyCache,\n ReferencedPrincipalPolicyWarmer,\n} from \"../../data/keyingProjectionVerification\";\nimport type { createProjectionUserKeyResolver } from \"../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { CurrentPolicyReferenceResolver } from \"../../data/principals/currentPolicyReferenceResolver\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../data/principals/principalPolicyEvidence\";\nimport type { SecurityIncidentReporter } from \"../../data/securityIncidents\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../data/trustedUserIdentity\";\nimport {\n planCarriedDescendantRekey,\n type SpeculativePath,\n} from \"../containers/child/carriedDescendantRekeys\";\nimport type { PlannedRematerialization } from \"./principalContainerRematerializationTargets\";\n\nexport interface RematerializationApi\n extends ContainerReciteApi,\n Pick<ApiClient, \"getContainerWriterProjectionResult\"> {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\nexport interface PrincipalContainerRematerializationInput {\n readonly reportSecurityIncident: SecurityIncidentReporter;\n readonly apiClient: RematerializationApi;\n readonly author: ContainerMutationAuthor;\n readonly execSql: ExecSql;\n readonly grants: readonly PrincipalContainerGrant[];\n readonly groupId: string;\n readonly nextPolicy: PrincipalPolicyCurrentEvidence;\n readonly resolveAuthoredPolicyReferences?:\n | CurrentPolicyReferenceResolver\n | undefined;\n readonly revokedContainerId?: string | undefined;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n /** Session lifetime for best-effort work after durable acknowledgement. */\n readonly recitationStillCurrent?: (() => boolean) | undefined;\n readonly targetSecretKey: Uint8Array;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\n/** What the batch has signed so far, in the order it will be submitted. */\nexport interface BatchPlanning {\n /**\n * Keys the batch minted, by epoch id. A rotation wraps its successor to the\n * group at the head this batch commits, which no store can open yet; a\n * level planned beneath it opens that epoch with the key minted here, and\n * its keyring then opens the retired epoch the level below is pinned to.\n */\n readonly knownContainerKeks: Map<string, Uint8Array>;\n readonly plans: PlannedRematerialization[];\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly rematerialization: PrincipalContainerRematerializationInput;\n readonly resolveProjectionUserKey: ReturnType<\n typeof createProjectionUserKeyResolver\n >;\n readonly rotatedAbove: SpeculativePath[];\n}\n\n/** How many rekeys the batch carries beyond its rematerializations. */\nfunction carriedCount(batch: BatchPlanning): number {\n return batch.plans.filter((entry) => entry.carried).length;\n}\n\n/**\n * Sign a rekey of `served` under the batch's rotations above it, and add it.\n * The server accepts at most `MAX_ROTATION_CONTAINER_REKEYS` carried entries;\n * past that a rematerialization below them could not be signed on a current\n * path, so the batch is refused here, before signing what the server would\n * refuse anyway, and the policy change has to wait for a lazy repair of the\n * tree. Groups granted that far apart on one chain are not a shape the SDK\n * creates.\n */\nexport async function carryLevel(\n batch: BatchPlanning,\n served: ContainerWriterProjectionResponse,\n): Promise<void> {\n const { rematerialization } = batch;\n if (carriedCount(batch) >= MAX_ROTATION_CONTAINER_REKEYS) {\n throw new Error(\n `Policy change would carry more than ${MAX_ROTATION_CONTAINER_REKEYS} descendant rekeys`,\n );\n }\n const planned = await planCarriedDescendantRekey({\n apiClient: rematerialization.apiClient,\n author: rematerialization.author,\n execSql: rematerialization.execSql,\n knownContainerKeks: batch.knownContainerKeks,\n principalPolicyCache: batch.principalPolicyCache,\n // Its path cites the policy this batch commits, so like every\n // rematerialized rotation it must cite the successor.\n replacementPrincipalPolicy: rematerialization.nextPolicy,\n resolveAuthoredPolicyReferences:\n rematerialization.resolveAuthoredPolicyReferences,\n resolveProjectionUserKey: batch.resolveProjectionUserKey,\n rotated: batch.rotatedAbove,\n served,\n stillCurrent: rematerialization.stillCurrent,\n targetSecretKey: rematerialization.targetSecretKey,\n warmReferencedPrincipalPolicies:\n rematerialization.warmReferencedPrincipalPolicies,\n });\n addPlan(batch, { carried: true, planned, rotated: planned.writerProjection });\n}\n\nexport function addPlan(\n batch: BatchPlanning,\n entry: PlannedRematerialization,\n): void {\n batch.plans.push(entry);\n if (!entry.rotated) return;\n batch.rotatedAbove.push(entry.rotated);\n const minted = entry.rotated.containerKeks.at(-1)?.containerKeyEpochId;\n if (minted) batch.knownContainerKeks.set(minted, entry.planned.containerKey);\n}\n\n/**\n * Levels of a re-rooted path pinned to an epoch the batch retires above them:\n * those strictly between the rotated ancestor the path was re-rooted on and\n * the target, parent-first, from the first stale one down. A rotation planned\n * above a target strands every level between the two, and each must be\n * re-keyed under the one above before the target can be signed. The batch\n * carries them without waiting to be told: they are proper ancestors of a\n * granted container, so the server would name them, and a refusal per level\n * is a round trip each. Anything stale above the rotated ancestor is not this\n * batch's doing and is left alone. `carryLevel` holds the count to the cap.\n */\nexport function staleLevelsAbove(\n projection: ContainerWriterProjectionResponse,\n rotatedAncestorId: string,\n): string[] {\n const keks = projection.containerKeks;\n const ancestor = keks.findIndex(\n (kek) => kek.containerId === rotatedAncestorId,\n );\n if (ancestor < 0) return [];\n const between = keks.slice(ancestor, -1);\n const firstStale = between.findIndex(\n (kek, index) =>\n index > 0 &&\n kek.parentContainerKeyEpochId !== between[index - 1]?.containerKeyEpochId,\n );\n return firstStale < 0\n ? []\n : between.slice(firstStale).map((kek) => kek.containerId);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"principalContainerRematerializationTargets.js","sourceRoot":"","sources":["principalContainerRematerializationTargets.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,+CAA+C,CAAC;AAO3F,OAAO,EAAE,4BAA4B,EAAE,MAAM,8DAA8D,CAAC;AAE5G,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AAwBhG;;;;;;GAMG;AACH,MAAM,UAAU,kCAAkC,CAOhD,KAAmB;IACnB,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CACpB,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACd,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM;QAC1D,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,aAAa,CAAC,KAAK,CAAC,UAAU,CAAC,WAAW,CAAC,CAC1E,CAAC;AACJ,CAAC;AAQD,oEAAoE;AACpE,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,SAAwB,EACxB,WAAmB;IAEnB,MAAM,UAAU,GAAG,MAAM,SAAS,CAAC,4BAA4B,CAAC,WAAW,CAAC,CAAC;IAC7E,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,MAAM,IAAI,KAAK,CACb,aAAa,WAAW,+CAA+C,CACxE,CAAC;IACJ,CAAC;IACD,IAAI,UAAU,CAAC,WAAW,KAAK,WAAW,EAAE,CAAC;QAC3C,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;IACnE,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC;AAED;;;;;GAK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;YAChB,MAAM,IAAI,KAAK,CACb,aAAa,WAAW,kDAAkD,MAAM,CAAC,OAAO,EAAE,CAC3F,CAAC;QACJ,CAAC;QACD,IAAI,MAAM,CAAC,IAAI,CAAC,WAAW,KAAK,WAAW;YACzC,MAAM,IAAI,KAAK,CAAC,+CAA+C,CAAC,CAAC;QACnE,OAAO,CAAC,IAAI,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC;IACtD,CAAC;IACD,OAAO;QACL,OAAO,EAAE,kCAAkC,CAAC,OAAO,CAAC;QACpD,mBAAmB;KACpB,CAAC;AACJ,CAAC;AAED,gFAAgF;AAChF,MAAM,UAAU,0BAA0B,CACxC,UAAmC;IAEnC,OAAO,IAAI,GAAG,CAAC;QACb;YACE,4BAA4B,CAAC;gBAC3B,QAAQ,EAAE,UAAU,CAAC,QAAQ;gBAC7B,cAAc,EAAE,UAAU,CAAC,KAAK,CAAC,cAAc;gBAC/C,WAAW,EAAE,UAAU,CAAC,WAAW;gBACnC,aAAa,EAAE,UAAU,CAAC,aAAa;gBACvC,SAAS,EAAE,UAAU,CAAC,SAAS;gBAC/B,OAAO,EAAE,UAAU,CAAC,OAAO;aAC5B,CAAC;YACF,UAAU;SACX;KACF,CAAC,CAAC;AACL,CAAC;AAED,kEAAkE;AAClE,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,KAGjC;IACC,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC;IAC/B,IAAI,CAAC,CAAC,SAAS,IAAI,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,OAAO,yCAAyC,CAAC;QAC/C,IAAI;QACJ,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC7C,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type {\n PrincipalContainerGrant,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { isContainerNotFoundFailure } from \"../../data/containers/shared/mutationFailures\";\nimport type {\n MaterializedContainerRekeyPlan,\n MaterializedContainerRevokePlan,\n MaterializedContainerSharePlan,\n} from \"../../data/containers/shared/types\";\nimport type { PrincipalPolicyCache } from \"../../data/keyingProjectionVerification\";\nimport { referencedPrincipalPolicyKey } from \"../../data/keyingProjectionVerification/principalPolicyCache\";\nimport type { SpeculativePath } from \"../containers/child/carriedDescendantRekeys\";\nimport { containerWriterProjectionFromRotationPlan } from \"../containers/child/rekeyProjection\";\n\nexport type MaterializedPrincipalContainerMutationPlan =\n | MaterializedContainerRekeyPlan\n | MaterializedContainerRevokePlan\n | MaterializedContainerSharePlan;\n\n/** A plan with its container's path once accepted; null for a grant, which rotates nothing. */\nexport interface PlannedRematerialization {\n /** A descendant rekey carried for a rotation above, not a rematerialization. */\n readonly carried: boolean;\n readonly planned: MaterializedPrincipalContainerMutationPlan;\n readonly rotated: SpeculativePath | null;\n}\n\n/**\n * One container a batch signs for: a group grant it rematerializes, or a\n * descendant rekey it carries for a rotation above (`grantRow` null).\n */\nexport interface RematerializationTarget {\n readonly grantRow: PrincipalContainerGrant | null;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\n/**\n * Order a batch parent-first, by served depth. A group granted on a container\n * and on one of its descendants rotates both, and the lower rotation must be\n * signed against the epoch the upper one mints in this same batch, or it\n * extends a head the batch itself retires. A carried rekey sits below the\n * rotation it rides for the same reason. Ties keep id order for stability.\n */\nexport function orderRematerializationsParentFirst<\n T extends {\n readonly projection: {\n readonly containerId: string;\n readonly path: readonly unknown[];\n };\n },\n>(batch: readonly T[]): T[] {\n return [...batch].sort(\n (left, right) =>\n left.projection.path.length - right.projection.path.length ||\n left.projection.containerId.localeCompare(right.projection.containerId),\n );\n}\n\ninterface ProjectionApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\n/** The served projection of a container the batch will sign for. */\nexport async function loadServedProjection(\n apiClient: ProjectionApi,\n containerId: string,\n): Promise<ContainerWriterProjectionResponse> {\n const projection = await apiClient.getContainerWriterProjection(containerId);\n if (!projection) {\n throw new Error(\n `Container ${containerId} could not be prepared for principal rotation`,\n );\n }\n if (projection.containerId !== containerId) {\n throw new Error(\"Served projection describes another container\");\n }\n return projection;\n}\n\n/**\n * Fetch what the batch signs for, parent-first. A named descendant the batch\n * already rematerializes is not fetched twice: its own rotation is re-planned\n * under whatever the batch carries above it. Names are a hint from the server,\n * never an authority; each is verified where it is planned.\n */\nexport async function loadRematerializationTargets(input: {\n readonly apiClient: Pick<ApiClient, \"getContainerWriterProjectionResult\">;\n readonly carriedContainerIds: readonly string[];\n readonly grants: readonly PrincipalContainerGrant[];\n}): Promise<{\n targets: RematerializationTarget[];\n retiredContainerIds: string[];\n}> {\n const grantByContainerId = new Map(\n input.grants.map((grant) => [grant.containerId, grant] as const),\n );\n const carried = [...new Set(input.carriedContainerIds)]\n .filter((containerId) => !grantByContainerId.has(containerId))\n .slice(0, MAX_ROTATION_CONTAINER_REKEYS);\n const targets: RematerializationTarget[] = [];\n const retiredContainerIds: string[] = [];\n for (const containerId of [...grantByContainerId.keys(), ...carried].sort(\n (left, right) => left.localeCompare(right),\n )) {\n const grantRow = grantByContainerId.get(containerId) ?? null;\n const result = await input.apiClient.getContainerWriterProjectionResult(\n containerId,\n { reportErrors: false },\n );\n if (!result.ok) {\n // This is only a planning hint. Keep the signed grant intact; the API\n // independently requires every live grant under the organization lock.\n if (\n grantRow &&\n result.kind === \"http\" &&\n isContainerNotFoundFailure(result)\n ) {\n retiredContainerIds.push(containerId);\n continue;\n }\n result.report();\n throw new Error(\n `Container ${containerId} could not be prepared for principal rotation: ${result.message}`,\n );\n }\n if (result.data.containerId !== containerId)\n throw new Error(\"Served projection describes another container\");\n targets.push({ grantRow, projection: result.data });\n }\n return {\n targets: orderRematerializationsParentFirst(targets),\n retiredContainerIds,\n };\n}\n\n/** An in-memory cache holding only the policy this batch is about to commit. */\nexport function seededPrincipalPolicyCache(\n nextPolicy: VerifiedPrincipalPolicy,\n): PrincipalPolicyCache {\n return new Map([\n [\n referencedPrincipalPolicyKey({\n keyEpoch: nextPolicy.keyEpoch,\n keyFingerprint: nextPolicy.state.keyFingerprint,\n principalId: nextPolicy.principalId,\n principalType: nextPolicy.principalType,\n stateHash: nextPolicy.stateHash,\n version: nextPolicy.version,\n }),\n nextPolicy,\n ],\n ]);\n}\n\n/** A rematerialization's path once accepted; null for a grant. */\nexport async function rotatedPath(input: {\n readonly planned: MaterializedPrincipalContainerMutationPlan;\n readonly previousProjection: ContainerWriterProjectionResponse;\n}): Promise<SpeculativePath | null> {\n const { plan } = input.planned;\n if (!(\"keyring\" in plan)) return null;\n return containerWriterProjectionFromRotationPlan({\n plan,\n previousProjection: input.previousProjection,\n });\n}\n"]}
1
+ {"version":3,"file":"principalContainerRematerializationTargets.js","sourceRoot":"","sources":["principalContainerRematerializationTargets.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAC3E,OAAO,EAAE,0BAA0B,EAAE,MAAM,+CAA+C,CAAC;AAO3F,OAAO,EAAE,4BAA4B,EAAE,MAAM,8DAA8D,CAAC;AAG5G,OAAO,EAAE,yCAAyC,EAAE,MAAM,qCAAqC,CAAC;AAwBhG;;;;;;GAMG;AACH,MAAM,UAAU,kCAAkC,CAOhD,KAAmB;IACnB,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CACpB,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CACd,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM;QAC1D,IAAI,CAAC,UAAU,CAAC,WAAW,CAAC,aAAa,CAAC,KAAK,CAAC,UAAU,CAAC,WAAW,CAAC,CAC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;SACX;KACF,CAAC,CAAC;AACL,CAAC;AAED,kEAAkE;AAClE,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,KAGjC;IACC,MAAM,EAAE,IAAI,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC;IAC/B,IAAI,CAAC,CAAC,SAAS,IAAI,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,OAAO,yCAAyC,CAAC;QAC/C,IAAI;QACJ,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;KAC7C,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ApiClient } from \"@tearleads/api-client\";\nimport type { PrincipalContainerGrant } from \"@tearleads/crypto\";\nimport type { ContainerWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_ROTATION_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { isContainerNotFoundFailure } from \"../../data/containers/shared/mutationFailures\";\nimport type {\n MaterializedContainerRekeyPlan,\n MaterializedContainerRevokePlan,\n MaterializedContainerSharePlan,\n} from \"../../data/containers/shared/types\";\nimport type { PrincipalPolicyCache } from \"../../data/keyingProjectionVerification\";\nimport { referencedPrincipalPolicyKey } from \"../../data/keyingProjectionVerification/principalPolicyCache\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../data/principals/principalPolicyEvidence\";\nimport type { SpeculativePath } from \"../containers/child/carriedDescendantRekeys\";\nimport { containerWriterProjectionFromRotationPlan } from \"../containers/child/rekeyProjection\";\n\nexport type MaterializedPrincipalContainerMutationPlan =\n | MaterializedContainerRekeyPlan\n | MaterializedContainerRevokePlan\n | MaterializedContainerSharePlan;\n\n/** A plan with its container's path once accepted; null for a grant, which rotates nothing. */\nexport interface PlannedRematerialization {\n /** A descendant rekey carried for a rotation above, not a rematerialization. */\n readonly carried: boolean;\n readonly planned: MaterializedPrincipalContainerMutationPlan;\n readonly rotated: SpeculativePath | null;\n}\n\n/**\n * One container a batch signs for: a group grant it rematerializes, or a\n * descendant rekey it carries for a rotation above (`grantRow` null).\n */\nexport interface RematerializationTarget {\n readonly grantRow: PrincipalContainerGrant | null;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\n/**\n * Order a batch parent-first, by served depth. A group granted on a container\n * and on one of its descendants rotates both, and the lower rotation must be\n * signed against the epoch the upper one mints in this same batch, or it\n * extends a head the batch itself retires. A carried rekey sits below the\n * rotation it rides for the same reason. Ties keep id order for stability.\n */\nexport function orderRematerializationsParentFirst<\n T extends {\n readonly projection: {\n readonly containerId: string;\n readonly path: readonly unknown[];\n };\n },\n>(batch: readonly T[]): T[] {\n return [...batch].sort(\n (left, right) =>\n left.projection.path.length - right.projection.path.length ||\n left.projection.containerId.localeCompare(right.projection.containerId),\n );\n}\n\ninterface ProjectionApi {\n getContainerWriterProjection(\n containerId: string,\n ): Promise<ContainerWriterProjectionResponse | null>;\n}\n\n/** The served projection of a container the batch will sign for. */\nexport async function loadServedProjection(\n apiClient: ProjectionApi,\n containerId: string,\n): Promise<ContainerWriterProjectionResponse> {\n const projection = await apiClient.getContainerWriterProjection(containerId);\n if (!projection) {\n throw new Error(\n `Container ${containerId} could not be prepared for principal rotation`,\n );\n }\n if (projection.containerId !== containerId) {\n throw new Error(\"Served projection describes another container\");\n }\n return projection;\n}\n\n/**\n * Fetch what the batch signs for, parent-first. A named descendant the batch\n * already rematerializes is not fetched twice: its own rotation is re-planned\n * under whatever the batch carries above it. Names are a hint from the server,\n * never an authority; each is verified where it is planned.\n */\nexport async function loadRematerializationTargets(input: {\n readonly apiClient: Pick<ApiClient, \"getContainerWriterProjectionResult\">;\n readonly carriedContainerIds: readonly string[];\n readonly grants: readonly PrincipalContainerGrant[];\n}): Promise<{\n targets: RematerializationTarget[];\n retiredContainerIds: string[];\n}> {\n const grantByContainerId = new Map(\n input.grants.map((grant) => [grant.containerId, grant] as const),\n );\n const carried = [...new Set(input.carriedContainerIds)]\n .filter((containerId) => !grantByContainerId.has(containerId))\n .slice(0, MAX_ROTATION_CONTAINER_REKEYS);\n const targets: RematerializationTarget[] = [];\n const retiredContainerIds: string[] = [];\n for (const containerId of [...grantByContainerId.keys(), ...carried].sort(\n (left, right) => left.localeCompare(right),\n )) {\n const grantRow = grantByContainerId.get(containerId) ?? null;\n const result = await input.apiClient.getContainerWriterProjectionResult(\n containerId,\n { reportErrors: false },\n );\n if (!result.ok) {\n // This is only a planning hint. Keep the signed grant intact; the API\n // independently requires every live grant under the organization lock.\n if (\n grantRow &&\n result.kind === \"http\" &&\n isContainerNotFoundFailure(result)\n ) {\n retiredContainerIds.push(containerId);\n continue;\n }\n result.report();\n throw new Error(\n `Container ${containerId} could not be prepared for principal rotation: ${result.message}`,\n );\n }\n if (result.data.containerId !== containerId)\n throw new Error(\"Served projection describes another container\");\n targets.push({ grantRow, projection: result.data });\n }\n return {\n targets: orderRematerializationsParentFirst(targets),\n retiredContainerIds,\n };\n}\n\n/** An in-memory cache holding only the policy this batch is about to commit. */\nexport function seededPrincipalPolicyCache(\n nextPolicy: PrincipalPolicyCurrentEvidence,\n): PrincipalPolicyCache {\n return new Map([\n [\n referencedPrincipalPolicyKey({\n keyEpoch: nextPolicy.keyEpoch,\n keyFingerprint: nextPolicy.state.keyFingerprint,\n principalId: nextPolicy.principalId,\n principalType: nextPolicy.principalType,\n stateHash: nextPolicy.stateHash,\n version: nextPolicy.version,\n }),\n nextPolicy,\n ],\n ]);\n}\n\n/** A rematerialization's path once accepted; null for a grant. */\nexport async function rotatedPath(input: {\n readonly planned: MaterializedPrincipalContainerMutationPlan;\n readonly previousProjection: ContainerWriterProjectionResponse;\n}): Promise<SpeculativePath | null> {\n const { plan } = input.planned;\n if (!(\"keyring\" in plan)) return null;\n return containerWriterProjectionFromRotationPlan({\n plan,\n previousProjection: input.previousProjection,\n });\n}\n"]}
@@ -1,9 +1,9 @@
1
1
  import type { RequestResult } from "../../internal/api-client/index.js";
2
2
  import type { SigningKeyPair } from "../../internal/crypto/index.js";
3
- import type { CommitOrganizationGroupPolicyResponse } from "../../internal/validators/response/index.js";
4
3
  import { type AuthoredPrincipalMutation, type PrincipalMutationJournalScope } from "../../data/principals/principalMutationJournal.js";
5
4
  import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
6
- type MutationResult = RequestResult<CommitOrganizationGroupPolicyResponse>;
5
+ import { type PrincipalMutationResponse } from "./principalOperationReceipt.js";
6
+ type MutationResult = RequestResult<PrincipalMutationResponse>;
7
7
  export interface PrincipalMutationJournalContext {
8
8
  readonly execSql: ExecSql;
9
9
  readonly scope: PrincipalMutationJournalScope;
@@ -21,6 +21,6 @@ export declare function submitJournaledPrincipalMutation(input: PrincipalMutatio
21
21
  /** Retry only authenticated saved bytes, never an application mutation callback. */
22
22
  export declare function recoverJournaledPrincipalMutation(input: PrincipalMutationJournalContext): Promise<{
23
23
  readonly mutation: AuthoredPrincipalMutation;
24
- readonly response: CommitOrganizationGroupPolicyResponse;
24
+ readonly response: PrincipalMutationResponse;
25
25
  } | null>;
26
26
  export {};
@@ -2,7 +2,7 @@ import { assertProjectionVerificationCurrent } from "../../data/keyingProjection
2
2
  import { claimPrincipalMutationJournal, clearPrincipalMutationJournal, loadPrincipalMutationJournal, } from "../../data/persistence/principalMutationJournalPersistence.js";
3
3
  import { openPrincipalMutation, principalMutationJournalScopeId, sealPrincipalMutation, } from "../../data/principals/principalMutationJournal.js";
4
4
  import { runPrincipalMutationJournalOperation } from "./principalMutationJournalLane.js";
5
- import { assertAuthoredPrincipalMutationReceipt } from "./principalMutationReceipt.js";
5
+ import { assertAuthoredPrincipalOperationReceipt, } from "./principalOperationReceipt.js";
6
6
  export class PrincipalMutationOutcomeUnknownError extends Error {
7
7
  constructor(options) {
8
8
  super("A saved policy request may have committed; resolve its outcome or explicitly abandon its retry before another mutation", options);
@@ -40,7 +40,7 @@ async function submitSavedMutation(input, row, recovering) {
40
40
  }
41
41
  assertProjectionVerificationCurrent(input.stillCurrent);
42
42
  if (result.ok) {
43
- await assertAuthoredPrincipalMutationReceipt(mutation.request, result.data);
43
+ await assertAuthoredPrincipalOperationReceipt(mutation, result.data);
44
44
  }
45
45
  else if (recovering || !knownInitialRefusal(result)) {
46
46
  // A refusal today (including loss of admin access) cannot establish whether
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationJournalSession.js","sourceRoot":"","sources":["principalMutationJournalSession.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,EAC7B,4BAA4B,GAE7B,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAEL,qBAAqB,EAErB,+BAA+B,EAC/B,qBAAqB,GACtB,MAAM,gDAAgD,CAAC;AAExD,OAAO,EAAE,oCAAoC,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAE,sCAAsC,EAAE,MAAM,4BAA4B,CAAC;AAcpF,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D,YAAY,OAAsB;QAChC,KAAK,CACH,wHAAwH,EACxH,OAAO,CACR,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;AAED,SAAS,mBAAmB,CAAC,MAAsB;IACjD,IAAI,MAAM,CAAC,EAAE;QAAE,OAAO,KAAK,CAAC;IAC5B,8EAA8E;IAC9E,IAAI,MAAM,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO,IAAI,CAAC;IAC7C,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC;IACzC,OAAO,CACL,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,CAAC;QACtD,CAAC,MAAM,CAAC,MAAM,KAAK,GAAG;YACpB,MAAM,CAAC,IAAI,KAAK,2CAA2C,CAAC,CAC/D,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,KAAsC,EACtC,GAAgC,EAChC,UAAmB;IAEnB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C,KAAK,EACX,KAAK,IAAI,EAAE;QACT,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,GAAG,GAAG,MAAM,qBAAqB,CAAC,KAAK,CAAC,CAAC;QAC/C,MAAM,6BAA6B,CAAC;YAClC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,GAAG;YACH,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC;QACH,OAAO,CAAC,MAAM,mBAAmB,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC;IAC/D,CAAC,CACF,CAAC;AACJ,CAAC;AAED,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,KAAsC;IAKtC,OAAO,oCAAoC,CACzC,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,KAAK,EACX,KAAK,IAAI,EAAE;QACT,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,GAAG,GAAG,MAAM,4BAA4B,CAC5C,KAAK,CAAC,OAAO,EACb,MAAM,+BAA+B,CAAC,KAAK,CAAC,KAAK,CAAC,CACnD,CAAC;QACF,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,IAAI,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC;QACtB,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,mBAAmB,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QACzE,IAAI,CAAC,MAAM,CAAC,EAAE;YAAE,MAAM,IAAI,oCAAoC,EAAE,CAAC;QACjE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC;IAC7C,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n claimPrincipalMutationJournal,\n clearPrincipalMutationJournal,\n loadPrincipalMutationJournal,\n type PrincipalMutationJournalRow,\n} from \"../../data/persistence/principalMutationJournalPersistence\";\nimport {\n type AuthoredPrincipalMutation,\n openPrincipalMutation,\n type PrincipalMutationJournalScope,\n principalMutationJournalScopeId,\n sealPrincipalMutation,\n} from \"../../data/principals/principalMutationJournal\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { runPrincipalMutationJournalOperation } from \"./principalMutationJournalLane\";\nimport { assertAuthoredPrincipalMutationReceipt } from \"./principalMutationReceipt\";\n\ntype MutationResult = RequestResult<CommitOrganizationGroupPolicyResponse>;\n\nexport interface PrincipalMutationJournalContext {\n readonly execSql: ExecSql;\n readonly scope: PrincipalMutationJournalScope;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent: () => boolean;\n readonly submit: (\n mutation: AuthoredPrincipalMutation,\n ) => Promise<MutationResult>;\n}\n\nexport class PrincipalMutationOutcomeUnknownError extends Error {\n constructor(options?: ErrorOptions) {\n super(\n \"A saved policy request may have committed; resolve its outcome or explicitly abandon its retry before another mutation\",\n options,\n );\n this.name = \"PrincipalMutationOutcomeUnknownError\";\n }\n}\n\nfunction knownInitialRefusal(result: MutationResult): boolean {\n if (result.ok) return false;\n // ApiClient separates pre-dispatch cancellation from an uncertain sent write.\n if (result.kind === \"cancelled\") return true;\n if (result.kind !== \"http\") return false;\n return (\n [400, 401, 402, 403, 409].includes(result.status ?? 0) ||\n (result.status === 503 &&\n result.code === \"principal_history_preparation_unavailable\")\n );\n}\n\nasync function submitSavedMutation(\n input: PrincipalMutationJournalContext,\n row: PrincipalMutationJournalRow,\n recovering: boolean,\n): Promise<{ mutation: AuthoredPrincipalMutation; result: MutationResult }> {\n const mutation = await openPrincipalMutation({\n scope: input.scope,\n row,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Keep the authenticated copy for acknowledgement checks even if a transport\n // mutates its argument while preparing or retrying the HTTP request.\n let result: MutationResult;\n try {\n result = await input.submit(structuredClone(mutation));\n } catch (cause) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n throw new PrincipalMutationOutcomeUnknownError({ cause });\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (result.ok) {\n await assertAuthoredPrincipalMutationReceipt(mutation.request, result.data);\n } else if (recovering || !knownInitialRefusal(result)) {\n // A refusal today (including loss of admin access) cannot establish whether\n // an earlier disconnected attempt committed. Preserve the original intent.\n throw new PrincipalMutationOutcomeUnknownError();\n }\n await clearPrincipalMutationJournal({\n execSql: input.execSql,\n row,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { mutation, result };\n}\n\n/** No HTTP begins until the exact authored request is durably claimed. */\nexport async function submitJournaledPrincipalMutation(\n input: PrincipalMutationJournalContext & {\n readonly mutation: AuthoredPrincipalMutation;\n },\n): Promise<MutationResult> {\n return runPrincipalMutationJournalOperation(\n input.execSql,\n input.scope,\n async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await sealPrincipalMutation(input);\n await claimPrincipalMutationJournal({\n execSql: input.execSql,\n row,\n stillCurrent: input.stillCurrent,\n });\n return (await submitSavedMutation(input, row, false)).result;\n },\n );\n}\n\n/** Retry only authenticated saved bytes, never an application mutation callback. */\nexport async function recoverJournaledPrincipalMutation(\n input: PrincipalMutationJournalContext,\n): Promise<{\n readonly mutation: AuthoredPrincipalMutation;\n readonly response: CommitOrganizationGroupPolicyResponse;\n} | null> {\n return runPrincipalMutationJournalOperation(\n input.execSql,\n input.scope,\n async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await loadPrincipalMutationJournal(\n input.execSql,\n await principalMutationJournalScopeId(input.scope),\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!row) return null;\n const { mutation, result } = await submitSavedMutation(input, row, true);\n if (!result.ok) throw new PrincipalMutationOutcomeUnknownError();\n return { mutation, response: result.data };\n },\n );\n}\n"]}
1
+ {"version":3,"file":"principalMutationJournalSession.js","sourceRoot":"","sources":["principalMutationJournalSession.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EACL,6BAA6B,EAC7B,6BAA6B,EAC7B,4BAA4B,GAE7B,MAAM,4DAA4D,CAAC;AACpE,OAAO,EAEL,qBAAqB,EAErB,+BAA+B,EAC/B,qBAAqB,GACtB,MAAM,gDAAgD,CAAC;AAExD,OAAO,EAAE,oCAAoC,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EACL,uCAAuC,GAExC,MAAM,6BAA6B,CAAC;AAcrC,MAAM,OAAO,oCAAqC,SAAQ,KAAK;IAC7D,YAAY,OAAsB;QAChC,KAAK,CACH,wHAAwH,EACxH,OAAO,CACR,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,sCAAsC,CAAC;IACrD,CAAC;CACF;AAED,SAAS,mBAAmB,CAAC,MAAsB;IACjD,IAAI,MAAM,CAAC,EAAE;QAAE,OAAO,KAAK,CAAC;IAC5B,8EAA8E;IAC9E,IAAI,MAAM,CAAC,IAAI,KAAK,WAAW;QAAE,OAAO,IAAI,CAAC;IAC7C,IAAI,MAAM,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,KAAK,CAAC;IACzC,OAAO,CACL,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,CAAC;QACtD,CAAC,MAAM,CAAC,MAAM,KAAK,GAAG;YACpB,MAAM,CAAC,IAAI,KAAK,2CAA2C,CAAC,CAC/D,CAAC;AACJ,CAAC;AAED,KAAK,UAAU,mBAAmB,CAChC,KAAsC,EACtC,GAAgC,EAChC,UAAmB;IAEnB,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AAK,IAAI,EAAE;QACT,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,GAAG,GAAG,MAAM,qBAAqB,CAAC,KAAK,CAAC,CAAC;QAC/C,MAAM,6BAA6B,CAAC;YAClC,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,GAAG;YACH,YAAY,EAAE,KAAK,CAAC,YAAY;SACjC,CAAC,CAAC;QACH,OAAO,CAAC,MAAM,mBAAmB,CAAC,KAAK,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC;IAC/D,CAAC,CACF,CAAC;AACJ,CAAC;AAED,oFAAoF;AACpF,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,KAAsC;IAKtC,OAAO,oCAAoC,CACzC,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,KAAK,EACX,KAAK,IAAI,EAAE;QACT,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,MAAM,GAAG,GAAG,MAAM,4BAA4B,CAC5C,KAAK,CAAC,OAAO,EACb,MAAM,+BAA+B,CAAC,KAAK,CAAC,KAAK,CAAC,CACnD,CAAC;QACF,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QACxD,IAAI,CAAC,GAAG;YAAE,OAAO,IAAI,CAAC;QACtB,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,GAAG,MAAM,mBAAmB,CAAC,KAAK,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;QACzE,IAAI,CAAC,MAAM,CAAC,EAAE;YAAE,MAAM,IAAI,oCAAoC,EAAE,CAAC;QACjE,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC,IAAI,EAAE,CAAC;IAC7C,CAAC,CACF,CAAC;AACJ,CAAC","sourcesContent":["import type { RequestResult } from \"@tearleads/api-client\";\nimport type { SigningKeyPair } from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n claimPrincipalMutationJournal,\n clearPrincipalMutationJournal,\n loadPrincipalMutationJournal,\n type PrincipalMutationJournalRow,\n} from \"../../data/persistence/principalMutationJournalPersistence\";\nimport {\n type AuthoredPrincipalMutation,\n openPrincipalMutation,\n type PrincipalMutationJournalScope,\n principalMutationJournalScopeId,\n sealPrincipalMutation,\n} from \"../../data/principals/principalMutationJournal\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { runPrincipalMutationJournalOperation } from \"./principalMutationJournalLane\";\nimport {\n assertAuthoredPrincipalOperationReceipt,\n type PrincipalMutationResponse,\n} from \"./principalOperationReceipt\";\n\ntype MutationResult = RequestResult<PrincipalMutationResponse>;\n\nexport interface PrincipalMutationJournalContext {\n readonly execSql: ExecSql;\n readonly scope: PrincipalMutationJournalScope;\n readonly signingKeyPair: SigningKeyPair;\n readonly stillCurrent: () => boolean;\n readonly submit: (\n mutation: AuthoredPrincipalMutation,\n ) => Promise<MutationResult>;\n}\n\nexport class PrincipalMutationOutcomeUnknownError extends Error {\n constructor(options?: ErrorOptions) {\n super(\n \"A saved policy request may have committed; resolve its outcome or explicitly abandon its retry before another mutation\",\n options,\n );\n this.name = \"PrincipalMutationOutcomeUnknownError\";\n }\n}\n\nfunction knownInitialRefusal(result: MutationResult): boolean {\n if (result.ok) return false;\n // ApiClient separates pre-dispatch cancellation from an uncertain sent write.\n if (result.kind === \"cancelled\") return true;\n if (result.kind !== \"http\") return false;\n return (\n [400, 401, 402, 403, 409].includes(result.status ?? 0) ||\n (result.status === 503 &&\n result.code === \"principal_history_preparation_unavailable\")\n );\n}\n\nasync function submitSavedMutation(\n input: PrincipalMutationJournalContext,\n row: PrincipalMutationJournalRow,\n recovering: boolean,\n): Promise<{ mutation: AuthoredPrincipalMutation; result: MutationResult }> {\n const mutation = await openPrincipalMutation({\n scope: input.scope,\n row,\n signingPublicKey: input.signingKeyPair.signingPublicKey,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n // Keep the authenticated copy for acknowledgement checks even if a transport\n // mutates its argument while preparing or retrying the HTTP request.\n let result: MutationResult;\n try {\n result = await input.submit(structuredClone(mutation));\n } catch (cause) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n throw new PrincipalMutationOutcomeUnknownError({ cause });\n }\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (result.ok) {\n await assertAuthoredPrincipalOperationReceipt(mutation, result.data);\n } else if (recovering || !knownInitialRefusal(result)) {\n // A refusal today (including loss of admin access) cannot establish whether\n // an earlier disconnected attempt committed. Preserve the original intent.\n throw new PrincipalMutationOutcomeUnknownError();\n }\n await clearPrincipalMutationJournal({\n execSql: input.execSql,\n row,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n return { mutation, result };\n}\n\n/** No HTTP begins until the exact authored request is durably claimed. */\nexport async function submitJournaledPrincipalMutation(\n input: PrincipalMutationJournalContext & {\n readonly mutation: AuthoredPrincipalMutation;\n },\n): Promise<MutationResult> {\n return runPrincipalMutationJournalOperation(\n input.execSql,\n input.scope,\n async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await sealPrincipalMutation(input);\n await claimPrincipalMutationJournal({\n execSql: input.execSql,\n row,\n stillCurrent: input.stillCurrent,\n });\n return (await submitSavedMutation(input, row, false)).result;\n },\n );\n}\n\n/** Retry only authenticated saved bytes, never an application mutation callback. */\nexport async function recoverJournaledPrincipalMutation(\n input: PrincipalMutationJournalContext,\n): Promise<{\n readonly mutation: AuthoredPrincipalMutation;\n readonly response: PrincipalMutationResponse;\n} | null> {\n return runPrincipalMutationJournalOperation(\n input.execSql,\n input.scope,\n async () => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const row = await loadPrincipalMutationJournal(\n input.execSql,\n await principalMutationJournalScopeId(input.scope),\n );\n assertProjectionVerificationCurrent(input.stillCurrent);\n if (!row) return null;\n const { mutation, result } = await submitSavedMutation(input, row, true);\n if (!result.ok) throw new PrincipalMutationOutcomeUnknownError();\n return { mutation, response: result.data };\n },\n );\n}\n"]}
@@ -4,18 +4,19 @@ import { assertPrincipalPolicyReceiptArtifacts } from "./principalPolicyReceiptA
4
4
  /** A past commit acknowledgement is not evidence for advancing current pins. */
5
5
  export async function assertAuthoredPrincipalMutationReceipt(request, response) {
6
6
  for (const part of ["groupPolicy", "organizationPolicy"]) {
7
- const expected = request[part];
8
- const observed = response[part];
9
- const { stateHash, createdAt: _createdAt, ...state } = observed.currentState;
10
- if (stateHash !== (await computePrincipalStateHash(expected.state)) ||
11
- canonicalKeyingJsonString(state, "principal mutation receipt state") !==
12
- canonicalKeyingJsonString(expected.state, "authored principal state"))
13
- throw new Error("Principal mutation receipt state differs from the authored request");
14
- assertPrincipalPolicyReceiptArtifacts({
15
- request: expected,
16
- response: observed,
17
- expectedHead: { ...observed.currentState, stateHash },
18
- });
7
+ await assertAuthoredPrincipalPolicyReceipt(request[part], response[part]);
19
8
  }
20
9
  }
10
+ export async function assertAuthoredPrincipalPolicyReceipt(expected, observed) {
11
+ const { stateHash, createdAt: _createdAt, ...state } = observed.currentState;
12
+ if (stateHash !== (await computePrincipalStateHash(expected.state)) ||
13
+ canonicalKeyingJsonString(state, "principal mutation receipt state") !==
14
+ canonicalKeyingJsonString(expected.state, "authored principal state"))
15
+ throw new Error("Principal mutation receipt state differs from the authored request");
16
+ assertPrincipalPolicyReceiptArtifacts({
17
+ request: expected,
18
+ response: observed,
19
+ expectedHead: { ...observed.currentState, stateHash },
20
+ });
21
+ }
21
22
  //# sourceMappingURL=principalMutationReceipt.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"principalMutationReceipt.js","sourceRoot":"","sources":["principalMutationReceipt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAG9D,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAE1F,gFAAgF;AAChF,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,OAA6C,EAC7C,QAA+C;IAE/C,KAAK,MAAM,IAAI,IAAI,CAAC,aAAa,EAAE,oBAAoB,CAAU,EAAE,CAAC;QAClE,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;QAC/B,MAAM,QAAQ,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;QAChC,MAAM,EACJ,SAAS,EACT,SAAS,EAAE,UAAU,EACrB,GAAG,KAAK,EACT,GAAG,QAAQ,CAAC,YAAY,CAAC;QAC1B,IACE,SAAS,KAAK,CAAC,MAAM,yBAAyB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;YAC/D,yBAAyB,CAAC,KAAK,EAAE,kCAAkC,CAAC;gBAClE,yBAAyB,CAAC,QAAQ,CAAC,KAAK,EAAE,0BAA0B,CAAC;YAEvE,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;QACJ,qCAAqC,CAAC;YACpC,OAAO,EAAE,QAAQ;YACjB,QAAQ,EAAE,QAAQ;YAClB,YAAY,EAAE,EAAE,GAAG,QAAQ,CAAC,YAAY,EAAE,SAAS,EAAE;SACtD,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import { computePrincipalStateHash } from \"@tearleads/crypto\";\nimport type { CommitOrganizationGroupPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../data/keyingCanonicalJson\";\nimport { assertPrincipalPolicyReceiptArtifacts } from \"./principalPolicyReceiptArtifacts\";\n\n/** A past commit acknowledgement is not evidence for advancing current pins. */\nexport async function assertAuthoredPrincipalMutationReceipt(\n request: CommitOrganizationGroupPolicyRequest,\n response: CommitOrganizationGroupPolicyResponse,\n): Promise<void> {\n for (const part of [\"groupPolicy\", \"organizationPolicy\"] as const) {\n const expected = request[part];\n const observed = response[part];\n const {\n stateHash,\n createdAt: _createdAt,\n ...state\n } = observed.currentState;\n if (\n stateHash !== (await computePrincipalStateHash(expected.state)) ||\n canonicalKeyingJsonString(state, \"principal mutation receipt state\") !==\n canonicalKeyingJsonString(expected.state, \"authored principal state\")\n )\n throw new Error(\n \"Principal mutation receipt state differs from the authored request\",\n );\n assertPrincipalPolicyReceiptArtifacts({\n request: expected,\n response: observed,\n expectedHead: { ...observed.currentState, stateHash },\n });\n }\n}\n"]}
1
+ {"version":3,"file":"principalMutationReceipt.js","sourceRoot":"","sources":["principalMutationReceipt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAG9D,OAAO,EAAE,yBAAyB,EAAE,MAAM,gCAAgC,CAAC;AAC3E,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAE1F,gFAAgF;AAChF,MAAM,CAAC,KAAK,UAAU,sCAAsC,CAC1D,OAA6C,EAC7C,QAA+C;IAE/C,KAAK,MAAM,IAAI,IAAI,CAAC,aAAa,EAAE,oBAAoB,CAAU,EAAE,CAAC;QAClE,MAAM,oCAAoC,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;IAC5E,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,oCAAoC,CACxD,QAA6D,EAC7D,QAA8D;IAE9D,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,GAAG,KAAK,EAAE,GAAG,QAAQ,CAAC,YAAY,CAAC;IAC7E,IACE,SAAS,KAAK,CAAC,MAAM,yBAAyB,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;QAC/D,yBAAyB,CAAC,KAAK,EAAE,kCAAkC,CAAC;YAClE,yBAAyB,CAAC,QAAQ,CAAC,KAAK,EAAE,0BAA0B,CAAC;QAEvE,MAAM,IAAI,KAAK,CACb,oEAAoE,CACrE,CAAC;IACJ,qCAAqC,CAAC;QACpC,OAAO,EAAE,QAAQ;QACjB,QAAQ,EAAE,QAAQ;QAClB,YAAY,EAAE,EAAE,GAAG,QAAQ,CAAC,YAAY,EAAE,SAAS,EAAE;KACtD,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { computePrincipalStateHash } from \"@tearleads/crypto\";\nimport type { CommitOrganizationGroupPolicyRequest } from \"@tearleads/validators/request\";\nimport type { CommitOrganizationGroupPolicyResponse } from \"@tearleads/validators/response\";\nimport { canonicalKeyingJsonString } from \"../../data/keyingCanonicalJson\";\nimport { assertPrincipalPolicyReceiptArtifacts } from \"./principalPolicyReceiptArtifacts\";\n\n/** A past commit acknowledgement is not evidence for advancing current pins. */\nexport async function assertAuthoredPrincipalMutationReceipt(\n request: CommitOrganizationGroupPolicyRequest,\n response: CommitOrganizationGroupPolicyResponse,\n): Promise<void> {\n for (const part of [\"groupPolicy\", \"organizationPolicy\"] as const) {\n await assertAuthoredPrincipalPolicyReceipt(request[part], response[part]);\n }\n}\n\nexport async function assertAuthoredPrincipalPolicyReceipt(\n expected: CommitOrganizationGroupPolicyRequest[\"groupPolicy\"],\n observed: CommitOrganizationGroupPolicyResponse[\"groupPolicy\"],\n): Promise<void> {\n const { stateHash, createdAt: _createdAt, ...state } = observed.currentState;\n if (\n stateHash !== (await computePrincipalStateHash(expected.state)) ||\n canonicalKeyingJsonString(state, \"principal mutation receipt state\") !==\n canonicalKeyingJsonString(expected.state, \"authored principal state\")\n )\n throw new Error(\n \"Principal mutation receipt state differs from the authored request\",\n );\n assertPrincipalPolicyReceiptArtifacts({\n request: expected,\n response: observed,\n expectedHead: { ...observed.currentState, stateHash },\n });\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import { type CommitOrganizationGroupPolicyResponse, type CreateOrganizationGroupResponse, type DeleteOrganizationGroupResponse, type PrincipalPolicyMutationResponse } from "../../internal/validators/response/index.js";
2
+ import type { AuthoredPrincipalMutation } from "../../data/principals/principalMutationJournal.js";
3
+ export type PrincipalMutationResponse = CommitOrganizationGroupPolicyResponse | CreateOrganizationGroupResponse | DeleteOrganizationGroupResponse | PrincipalPolicyMutationResponse;
4
+ /** Match both the operation's route and its exact authored policy artifacts. */
5
+ export declare function assertAuthoredPrincipalOperationReceipt(mutation: AuthoredPrincipalMutation, response: PrincipalMutationResponse): Promise<void>;
@@ -0,0 +1,36 @@
1
+ import { computePrincipalStateHash } from "../../internal/crypto/index.js";
2
+ import { isCommitOrganizationGroupPolicyResponse, isCreateOrganizationGroupResponse, isDeleteOrganizationGroupResponse, isPrincipalPolicyMutationResponse, } from "../../internal/validators/response/index.js";
3
+ import { acknowledgeInitialGroupPolicy } from "./groupPolicyMutationAcknowledgement.js";
4
+ import { assertAuthoredPrincipalMutationReceipt, assertAuthoredPrincipalPolicyReceipt, } from "./principalMutationReceipt.js";
5
+ /** Match both the operation's route and its exact authored policy artifacts. */
6
+ export async function assertAuthoredPrincipalOperationReceipt(mutation, response) {
7
+ switch (mutation.kind) {
8
+ case undefined:
9
+ if (!isCommitOrganizationGroupPolicyResponse(response))
10
+ break;
11
+ return assertAuthoredPrincipalMutationReceipt(mutation.request, response);
12
+ case "organization":
13
+ if (!isPrincipalPolicyMutationResponse(response))
14
+ break;
15
+ return assertAuthoredPrincipalPolicyReceipt(mutation.request, response);
16
+ case "group-create":
17
+ if (!isCreateOrganizationGroupResponse(response))
18
+ break;
19
+ await acknowledgeInitialGroupPolicy({
20
+ organizationId: mutation.request.organizationPolicy.state.principalId,
21
+ request: mutation.request,
22
+ response: response.group,
23
+ stateHash: await computePrincipalStateHash(mutation.request.initialGroupPolicy.state),
24
+ });
25
+ return assertAuthoredPrincipalPolicyReceipt(mutation.request.organizationPolicy, response.organizationPolicy);
26
+ case "group-delete":
27
+ if (!isDeleteOrganizationGroupResponse(response) ||
28
+ response.groupId !== mutation.groupId ||
29
+ response.organizationId !==
30
+ mutation.request.organizationPolicy.state.principalId)
31
+ break;
32
+ return assertAuthoredPrincipalPolicyReceipt(mutation.request.organizationPolicy, response.organizationPolicy);
33
+ }
34
+ throw new Error("Principal mutation receipt operation or target differs");
35
+ }
36
+ //# sourceMappingURL=principalOperationReceipt.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalOperationReceipt.js","sourceRoot":"","sources":["principalOperationReceipt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,yBAAyB,EAAE,MAAM,mBAAmB,CAAC;AAC9D,OAAO,EAIL,uCAAuC,EACvC,iCAAiC,EACjC,iCAAiC,EACjC,iCAAiC,GAElC,MAAM,gCAAgC,CAAC;AAExC,OAAO,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AACrF,OAAO,EACL,sCAAsC,EACtC,oCAAoC,GACrC,MAAM,4BAA4B,CAAC;AAQpC,gFAAgF;AAChF,MAAM,CAAC,KAAK,UAAU,uCAAuC,CAC3D,QAAmC,EACnC,QAAmC;IAEnC,QAAQ,QAAQ,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,SAAS;YACZ,IAAI,CAAC,uCAAuC,CAAC,QAAQ,CAAC;gBAAE,MAAM;YAC9D,OAAO,sCAAsC,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QAC5E,KAAK,cAAc;YACjB,IAAI,CAAC,iCAAiC,CAAC,QAAQ,CAAC;gBAAE,MAAM;YACxD,OAAO,oCAAoC,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;QAC1E,KAAK,cAAc;YACjB,IAAI,CAAC,iCAAiC,CAAC,QAAQ,CAAC;gBAAE,MAAM;YACxD,MAAM,6BAA6B,CAAC;gBAClC,cAAc,EAAE,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAAC,WAAW;gBACrE,OAAO,EAAE,QAAQ,CAAC,OAAO;gBACzB,QAAQ,EAAE,QAAQ,CAAC,KAAK;gBACxB,SAAS,EAAE,MAAM,yBAAyB,CACxC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAC1C;aACF,CAAC,CAAC;YACH,OAAO,oCAAoC,CACzC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,EACnC,QAAQ,CAAC,kBAAkB,CAC5B,CAAC;QACJ,KAAK,cAAc;YACjB,IACE,CAAC,iCAAiC,CAAC,QAAQ,CAAC;gBAC5C,QAAQ,CAAC,OAAO,KAAK,QAAQ,CAAC,OAAO;gBACrC,QAAQ,CAAC,cAAc;oBACrB,QAAQ,CAAC,OAAO,CAAC,kBAAkB,CAAC,KAAK,CAAC,WAAW;gBAEvD,MAAM;YACR,OAAO,oCAAoC,CACzC,QAAQ,CAAC,OAAO,CAAC,kBAAkB,EACnC,QAAQ,CAAC,kBAAkB,CAC5B,CAAC;IACN,CAAC;IACD,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import { computePrincipalStateHash } from \"@tearleads/crypto\";\nimport {\n type CommitOrganizationGroupPolicyResponse,\n type CreateOrganizationGroupResponse,\n type DeleteOrganizationGroupResponse,\n isCommitOrganizationGroupPolicyResponse,\n isCreateOrganizationGroupResponse,\n isDeleteOrganizationGroupResponse,\n isPrincipalPolicyMutationResponse,\n type PrincipalPolicyMutationResponse,\n} from \"@tearleads/validators/response\";\nimport type { AuthoredPrincipalMutation } from \"../../data/principals/principalMutationJournal\";\nimport { acknowledgeInitialGroupPolicy } from \"./groupPolicyMutationAcknowledgement\";\nimport {\n assertAuthoredPrincipalMutationReceipt,\n assertAuthoredPrincipalPolicyReceipt,\n} from \"./principalMutationReceipt\";\n\nexport type PrincipalMutationResponse =\n | CommitOrganizationGroupPolicyResponse\n | CreateOrganizationGroupResponse\n | DeleteOrganizationGroupResponse\n | PrincipalPolicyMutationResponse;\n\n/** Match both the operation's route and its exact authored policy artifacts. */\nexport async function assertAuthoredPrincipalOperationReceipt(\n mutation: AuthoredPrincipalMutation,\n response: PrincipalMutationResponse,\n): Promise<void> {\n switch (mutation.kind) {\n case undefined:\n if (!isCommitOrganizationGroupPolicyResponse(response)) break;\n return assertAuthoredPrincipalMutationReceipt(mutation.request, response);\n case \"organization\":\n if (!isPrincipalPolicyMutationResponse(response)) break;\n return assertAuthoredPrincipalPolicyReceipt(mutation.request, response);\n case \"group-create\":\n if (!isCreateOrganizationGroupResponse(response)) break;\n await acknowledgeInitialGroupPolicy({\n organizationId: mutation.request.organizationPolicy.state.principalId,\n request: mutation.request,\n response: response.group,\n stateHash: await computePrincipalStateHash(\n mutation.request.initialGroupPolicy.state,\n ),\n });\n return assertAuthoredPrincipalPolicyReceipt(\n mutation.request.organizationPolicy,\n response.organizationPolicy,\n );\n case \"group-delete\":\n if (\n !isDeleteOrganizationGroupResponse(response) ||\n response.groupId !== mutation.groupId ||\n response.organizationId !==\n mutation.request.organizationPolicy.state.principalId\n )\n break;\n return assertAuthoredPrincipalPolicyReceipt(\n mutation.request.organizationPolicy,\n response.organizationPolicy,\n );\n }\n throw new Error(\"Principal mutation receipt operation or target differs\");\n}\n"]}
@@ -6,6 +6,8 @@ import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
6
6
  import type { RecoverPrincipalPolicyHistoryOptions } from "../principals/principalHistoryRecoveryTypes.js";
7
7
  export type { AcknowledgedPrincipalCurrentRetirement } from "../../data/persistence/principalCurrentAcknowledgementPersistence.js";
8
8
  export interface AcknowledgedPrincipalCurrentInput {
9
+ /** Only a newly authored group at version one; never skips a predecessor. */
10
+ readonly initialGroup?: boolean | undefined;
9
11
  /** The same scoped protection and verification mode used to recover the predecessor. */
10
12
  readonly recovery: Omit<RecoverPrincipalPolicyHistoryOptions, "execSql" | "organizationId" | "stillCurrent">;
11
13
  readonly request: PutPrincipalPolicyRequest;
@@ -11,6 +11,7 @@ import { assertPrincipalHistoryVerificationMode, principalHistoryVerificationCon
11
11
  import { assertAcknowledgedDirectoryBindings } from "./acknowledgedDirectoryBindings.js";
12
12
  import { acknowledgeGroupPolicyState } from "./groupPolicyMutationAcknowledgement.js";
13
13
  import { groupPolicyMutationHead } from "./groupPolicyMutationHead.js";
14
+ import { prepareInitialGroupCurrentPublication } from "./initialPrincipalCurrentPublication.js";
14
15
  import { sealPrincipalCurrentPublication, sealPrincipalCurrentStage, } from "./principalCurrentPublicationSeal.js";
15
16
  import { assertPrincipalPolicyReceiptArtifacts } from "./principalPolicyReceiptArtifacts.js";
16
17
  async function restorePredecessor(options) {
@@ -122,6 +123,7 @@ export async function retainAcknowledgedPrincipalCurrents(input) {
122
123
  assertProjectionVerificationCurrent(stillCurrent);
123
124
  for (const entry of input.entries)
124
125
  entries.push({
126
+ initialGroup: entry.initialGroup === true,
125
127
  request: structuredClone(entry.request),
126
128
  response: structuredClone(entry.response),
127
129
  options: {
@@ -135,7 +137,9 @@ export async function retainAcknowledgedPrincipalCurrents(input) {
135
137
  });
136
138
  const publications = [];
137
139
  for (const entry of entries)
138
- publications.push(await preparePublication(entry.options, entry.request, entry.response));
140
+ publications.push(await (entry.initialGroup
141
+ ? prepareInitialGroupCurrentPublication
142
+ : preparePublication)(entry.options, entry.request, entry.response));
139
143
  assertAcknowledgedDirectoryBindings(organizationId, entries.map(({ response }) => response));
140
144
  await persistAcknowledgedPrincipalCurrents({
141
145
  execSql,
@@ -1 +1 @@
1
- {"version":3,"file":"retainAcknowledgedPrincipalCurrents.js","sourceRoot":"","sources":["retainAcknowledgedPrincipalCurrents.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,qCAAqC,EAErC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAGL,oCAAoC,GACrC,MAAM,mEAAmE,CAAC;AAC3E,OAAO,EAAE,mCAAmC,EAAE,MAAM,4DAA4D,CAAC;AACjH,OAAO,EAAE,0BAA0B,EAAE,MAAM,0DAA0D,CAAC;AACtG,OAAO,EACL,+BAA+B,EAC/B,gCAAgC,GACjC,MAAM,wDAAwD,CAAC;AAChE,OAAO,EAAE,6BAA6B,EAAE,MAAM,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AAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n persistAcknowledgedPrincipalCurrents,\n} from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { loadPrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { parsePrincipalHistoryStageCurrent } from \"../../data/principals/principalHistoryStageProtection\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../principals/policyVerification\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../principals/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../principals/principalHistoryRecoveryVerification\";\nimport { assertAcknowledgedDirectoryBindings } from \"./acknowledgedDirectoryBindings\";\nimport { acknowledgeGroupPolicyState } from \"./groupPolicyMutationAcknowledgement\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport { assertPrincipalPolicyReceiptArtifacts } from \"./principalPolicyReceiptArtifacts\";\n\nexport type { AcknowledgedPrincipalCurrentRetirement } from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function restorePredecessor(\n options: RecoverPrincipalPolicyHistoryOptions,\n) {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n const saved = await loadPrincipalHistoryPrefix(options.execSql, scopeId);\n if (!saved || saved.organizationId !== options.organizationId)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledgement requires its authenticated predecessor prefix\",\n );\n const restored = await restorePrincipalPolicyHistoryVerifier(\n {\n principalId: options.expectedHead.principalId,\n principalType: options.expectedHead.principalType,\n },\n saved.progress,\n await principalHistoryPrefixProtection(options.protection, saved),\n );\n if (!restored.ok) throw restored.error;\n const history = restored.value.finish(options.expectedHead);\n if (!history.ok) throw history.error;\n const artifacts = parsePrincipalHistoryStageCurrent({\n currentJson: saved.currentJson,\n afterVersion: saved.version - 1,\n });\n if (!artifacts)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Acknowledged predecessor artifacts are malformed\",\n );\n const previous = await verifyPrincipalPolicyCurrent({\n current: artifacts,\n history: history.value,\n });\n if (!previous.ok) throw previous.error;\n return {\n scopeId,\n saved,\n artifacts,\n verifier: restored.value,\n previous: previous.value,\n };\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const { scopeId, saved, artifacts, verifier, previous } =\n await restorePredecessor(options);\n const expectedHead = await groupPolicyMutationHead(request);\n assertPrincipalPolicyReceiptArtifacts({ expectedHead, request, response });\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { currentState: response.currentState, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(current);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(current);\n const policy = await acknowledgeGroupPolicyState({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: response.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent: current,\n });\n const entry = {\n state: response.currentState,\n projection: response.currentProjection,\n grants: response.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n response,\n );\n assertProjectionVerificationCurrent(current);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** Extend authenticated local progress and retain exact acknowledged artifacts atomically with pins. */\nexport async function retainAcknowledgedPrincipalCurrents(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: {\n request: PutPrincipalPolicyRequest;\n response: PrincipalPolicyMutationResponse;\n options: RecoverPrincipalPolicyHistoryOptions;\n }[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n for (const entry of input.entries)\n entries.push({\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const entry of entries)\n publications.push(\n await preparePublication(entry.options, entry.request, entry.response),\n );\n assertAcknowledgedDirectoryBindings(\n organizationId,\n entries.map(({ response }) => response),\n );\n await persistAcknowledgedPrincipalCurrents({\n execSql,\n organizationId,\n entries: publications,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}
1
+ {"version":3,"file":"retainAcknowledgedPrincipalCurrents.js","sourceRoot":"","sources":["retainAcknowledgedPrincipalCurrents.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,qCAAqC,EAErC,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAGL,oCAAoC,GACrC,MAAM,mEAAmE,CAAC;AAC3E,OAAO,EAAE,mCAAmC,EAAE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W;YACX,YAAY,EAAE,GAAG,EAAE,CACjB,YAAY,EAAE;gBACd,OAAO,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC;SAC3D,CAAC,CAAC;QACH,OAAO,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC;IAClD,CAAC;YAAS,CAAC;QACT,KAAK,MAAM,KAAK,IAAI,OAAO;YAAE,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IACzE,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n restorePrincipalPolicyHistoryVerifier,\n type VerifiedPrincipalPolicyCurrent,\n verifyPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport type { PutPrincipalPolicyRequest } from \"@tearleads/validators/request\";\nimport type { PrincipalPolicyMutationResponse } from \"@tearleads/validators/response\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport {\n type AcknowledgedPrincipalCurrentPublication,\n type AcknowledgedPrincipalCurrentRetirement,\n persistAcknowledgedPrincipalCurrents,\n} from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\nimport { preparePrincipalHistoryEvidencePage } from \"../../data/persistence/principalHistoryEvidencePersistence\";\nimport { loadPrincipalHistoryPrefix } from \"../../data/persistence/principalHistoryPrefixPersistence\";\nimport {\n principalHistoryEvidenceScopeId,\n principalHistoryPrefixProtection,\n} from \"../../data/principals/principalHistoryPrefixProtection\";\nimport { ownPrincipalHistoryProtection } from \"../../data/principals/principalHistoryProtection\";\nimport { parsePrincipalHistoryStageCurrent } from \"../../data/principals/principalHistoryStageProtection\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport { collectPrincipalPolicySignerPublicKeys } from \"../principals/policyVerification\";\nimport type { RecoverPrincipalPolicyHistoryOptions } from \"../principals/principalHistoryRecoveryTypes\";\nimport {\n assertPrincipalHistoryVerificationMode,\n principalHistoryVerificationContext,\n} from \"../principals/principalHistoryRecoveryVerification\";\nimport { assertAcknowledgedDirectoryBindings } from \"./acknowledgedDirectoryBindings\";\nimport { acknowledgeGroupPolicyState } from \"./groupPolicyMutationAcknowledgement\";\nimport { groupPolicyMutationHead } from \"./groupPolicyMutationHead\";\nimport { prepareInitialGroupCurrentPublication } from \"./initialPrincipalCurrentPublication\";\nimport {\n sealPrincipalCurrentPublication,\n sealPrincipalCurrentStage,\n} from \"./principalCurrentPublicationSeal\";\nimport { assertPrincipalPolicyReceiptArtifacts } from \"./principalPolicyReceiptArtifacts\";\n\nexport type { AcknowledgedPrincipalCurrentRetirement } from \"../../data/persistence/principalCurrentAcknowledgementPersistence\";\n\nexport interface AcknowledgedPrincipalCurrentInput {\n /** Only a newly authored group at version one; never skips a predecessor. */\n readonly initialGroup?: boolean | undefined;\n /** The same scoped protection and verification mode used to recover the predecessor. */\n readonly recovery: Omit<\n RecoverPrincipalPolicyHistoryOptions,\n \"execSql\" | \"organizationId\" | \"stillCurrent\"\n >;\n readonly request: PutPrincipalPolicyRequest;\n readonly response: PrincipalPolicyMutationResponse;\n}\n\nasync function restorePredecessor(\n options: RecoverPrincipalPolicyHistoryOptions,\n) {\n const scopeId = await principalHistoryEvidenceScopeId({\n organizationId: options.organizationId,\n head: options.expectedHead,\n protection: options.protection,\n });\n const saved = await loadPrincipalHistoryPrefix(options.execSql, scopeId);\n if (!saved || saved.organizationId !== options.organizationId)\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Acknowledgement requires its authenticated predecessor prefix\",\n );\n const restored = await restorePrincipalPolicyHistoryVerifier(\n {\n principalId: options.expectedHead.principalId,\n principalType: options.expectedHead.principalType,\n },\n saved.progress,\n await principalHistoryPrefixProtection(options.protection, saved),\n );\n if (!restored.ok) throw restored.error;\n const history = restored.value.finish(options.expectedHead);\n if (!history.ok) throw history.error;\n const artifacts = parsePrincipalHistoryStageCurrent({\n currentJson: saved.currentJson,\n afterVersion: saved.version - 1,\n });\n if (!artifacts)\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Acknowledged predecessor artifacts are malformed\",\n );\n const previous = await verifyPrincipalPolicyCurrent({\n current: artifacts,\n history: history.value,\n });\n if (!previous.ok) throw previous.error;\n return {\n scopeId,\n saved,\n artifacts,\n verifier: restored.value,\n previous: previous.value,\n };\n}\n\nasync function preparePublication(\n options: RecoverPrincipalPolicyHistoryOptions,\n request: PutPrincipalPolicyRequest,\n response: PrincipalPolicyMutationResponse,\n): Promise<AcknowledgedPrincipalCurrentPublication> {\n options = {\n ...options,\n protection: {\n ...options.protection,\n context: principalHistoryVerificationContext(options),\n },\n };\n const current = () => !options.signal?.aborted && options.stillCurrent();\n assertProjectionVerificationCurrent(current);\n const { scopeId, saved, artifacts, verifier, previous } =\n await restorePredecessor(options);\n const expectedHead = await groupPolicyMutationHead(request);\n assertPrincipalPolicyReceiptArtifacts({ expectedHead, request, response });\n const keys = await collectPrincipalPolicySignerPublicKeys({\n bundle: { currentState: response.currentState, previousStates: [] },\n resolveTrustedUserIdentity: options.resolveTrustedUserIdentity,\n });\n assertProjectionVerificationCurrent(current);\n if (\"error\" in keys)\n throw new KeyingVerificationError(\n keys.error === \"not-found\" ? \"missing_dependency\" : \"signer_mismatch\",\n \"Acknowledged principal signer could not be authenticated\",\n );\n const externalAuthority = await options.loadExternalAuthority?.(\n request.state.externalAuthority ? [request.state.externalAuthority] : [],\n );\n assertProjectionVerificationCurrent(current);\n const policy = await acknowledgeGroupPolicyState({\n verifiedCurrentPolicy: previous,\n expectedHead,\n request,\n response: response.currentState,\n signerPublicKeys: keys.signerPublicKeys,\n externalAuthority,\n stillCurrent: current,\n });\n const entry = {\n state: response.currentState,\n projection: response.currentProjection,\n grants: response.currentGrants,\n };\n assertPrincipalHistoryVerificationMode(options, [entry]);\n const predecessorStage = await sealPrincipalCurrentStage(\n options,\n previous.state,\n verifier,\n artifacts,\n );\n const appended = await verifier.append({\n entries: [entry],\n signerPublicKeys: keys.signerPublicKeys,\n ...(externalAuthority ? { externalAuthority } : {}),\n });\n if (!appended.ok) throw appended.error;\n const sealed = await sealPrincipalCurrentPublication(\n options,\n scopeId,\n expectedHead,\n verifier,\n response,\n );\n assertProjectionVerificationCurrent(current);\n return {\n policy,\n previousPrefixProgress: saved.progress,\n predecessorStage,\n ...sealed,\n evidence: await preparePrincipalHistoryEvidencePage({\n scopeId,\n organizationId: options.organizationId,\n entries: [entry],\n nodes: appended.value.indexNodes,\n }),\n };\n}\n\n/** Extend authenticated local progress and retain exact acknowledged artifacts atomically with pins. */\nexport async function retainAcknowledgedPrincipalCurrents(input: {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly entries: readonly AcknowledgedPrincipalCurrentInput[];\n readonly retirements?:\n | readonly AcknowledgedPrincipalCurrentRetirement[]\n | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<VerifiedPrincipalPolicyCurrent[]> {\n const execSql = input.execSql;\n const organizationId = input.organizationId;\n const stillCurrent = input.stillCurrent;\n const retirements = structuredClone(input.retirements ?? []);\n const entries: {\n initialGroup: boolean;\n request: PutPrincipalPolicyRequest;\n response: PrincipalPolicyMutationResponse;\n options: RecoverPrincipalPolicyHistoryOptions;\n }[] = [];\n try {\n assertProjectionVerificationCurrent(stillCurrent);\n for (const entry of input.entries)\n entries.push({\n initialGroup: entry.initialGroup === true,\n request: structuredClone(entry.request),\n response: structuredClone(entry.response),\n options: {\n ...entry.recovery,\n expectedHead: structuredClone(entry.recovery.expectedHead),\n protection: ownPrincipalHistoryProtection(entry.recovery.protection),\n execSql,\n organizationId,\n stillCurrent,\n },\n });\n const publications: AcknowledgedPrincipalCurrentPublication[] = [];\n for (const entry of entries)\n publications.push(\n await (entry.initialGroup\n ? prepareInitialGroupCurrentPublication\n : preparePublication)(entry.options, entry.request, entry.response),\n );\n assertAcknowledgedDirectoryBindings(\n organizationId,\n entries.map(({ response }) => response),\n );\n await persistAcknowledgedPrincipalCurrents({\n execSql,\n organizationId,\n entries: publications,\n retirements,\n stillCurrent: () =>\n stillCurrent() &&\n entries.every((entry) => !entry.options.signal?.aborted),\n });\n return publications.map(({ policy }) => policy);\n } finally {\n for (const entry of entries) entry.options.protection.localKey.fill(0);\n }\n}\n"]}