@tearleads/client-sdk 0.1.217 → 0.1.219

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 (168) hide show
  1. package/client/containerContents/documentDiscovery.js +6 -4
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/containerContents/index.js +3 -4
  4. package/client/containerContents/index.js.map +1 -1
  5. package/client/deviceFirst/index.js +2 -2
  6. package/client/deviceFirst/index.js.map +1 -1
  7. package/client/documents/index.js +2 -2
  8. package/client/documents/index.js.map +1 -1
  9. package/client/organizations/organizationGroupHistory.js +1 -2
  10. package/client/organizations/organizationGroupHistory.js.map +1 -1
  11. package/client/organizations/organizationGroupNameHydration.js +1 -2
  12. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  13. package/client/organizations/organizationHistory.js +2 -4
  14. package/client/organizations/organizationHistory.js.map +1 -1
  15. package/client/organizations/principalContainerMutations.js +1 -2
  16. package/client/organizations/principalContainerMutations.js.map +1 -1
  17. package/client/organizations/principalMutations.js +1 -2
  18. package/client/organizations/principalMutations.js.map +1 -1
  19. package/client/organizations/rosterAdmissionEvidence.js +1 -2
  20. package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
  21. package/client/runtime/workflowRuntime.d.ts +3 -2
  22. package/client/runtime/workflowRuntime.js +13 -3
  23. package/client/runtime/workflowRuntime.js.map +1 -1
  24. package/index.d.ts +3 -3
  25. package/index.js +1 -1
  26. package/index.js.map +1 -1
  27. package/package.json +1 -1
  28. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  29. package/stores/documents/documentStore/attachments/attachmentHydration.js +3 -2
  30. package/stores/documents/documentStore/attachments/attachmentHydration.js.map +1 -1
  31. package/stores/documents/documentStore/history/historyRebuild.js.map +1 -1
  32. package/stores/documents/documentStore/rotation/index.js +11 -8
  33. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  34. package/stores/documents/documentStore/rotation/rotationSettlement.js +1 -1
  35. package/stores/documents/documentStore/rotation/rotationSettlement.js.map +1 -1
  36. package/stores/documents/documentStore/state.js.map +1 -1
  37. package/stores/documents/documentStore/sync/carriedFirstUpdate.js.map +1 -1
  38. package/stores/documents/documentStore/sync/createdDocumentPersistence.js.map +1 -1
  39. package/stores/documents/documentStore/sync/index.js.map +1 -1
  40. package/stores/documents/documentStore/sync/syncAttachments.js +3 -2
  41. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  42. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -2
  43. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  44. package/stores/documents/documentStore/sync/syncRequest.js +12 -8
  45. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  46. package/stores/documents/documentStore/sync/syncRevalidation.js.map +1 -1
  47. package/stores/documents/documentStore/sync/syncSeededCreate.js.map +1 -1
  48. package/stores/documents/documentStore/sync/syncShared.js +12 -8
  49. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  50. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  51. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  52. package/workflows/container-contents/container-state/create/createWithMetadata.js +1 -2
  53. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  54. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +1 -2
  55. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  56. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -2
  57. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  58. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -2
  59. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  60. package/workflows/container-contents/container-state/remote.js +3 -4
  61. package/workflows/container-contents/container-state/remote.js.map +1 -1
  62. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
  63. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  64. package/workflows/container-contents/container-state/share/index.js +2 -3
  65. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  66. package/workflows/container-contents/container-state/types.js.map +1 -1
  67. package/workflows/container-contents/documentLinks/documentLinksMove.js +4 -2
  68. package/workflows/container-contents/documentLinks/documentLinksMove.js.map +1 -1
  69. package/workflows/container-contents/documentLinks/index.js +3 -2
  70. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  71. package/workflows/container-contents/index.d.ts +1 -1
  72. package/workflows/container-contents/index.js +1 -1
  73. package/workflows/container-contents/index.js.map +1 -1
  74. package/workflows/container-contents/metadata/index.d.ts +1 -1
  75. package/workflows/container-contents/metadata/index.js.map +1 -1
  76. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +6 -8
  77. package/workflows/container-contents/metadata/metadataRemoteSync.js +14 -9
  78. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  79. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -2
  80. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  81. package/workflows/container-contents/remoteHydration/index.js +1 -2
  82. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  83. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +4 -2
  84. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  85. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  86. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  87. package/workflows/container-contents/runtime.d.ts +13 -2
  88. package/workflows/container-contents/runtime.js +33 -21
  89. package/workflows/container-contents/runtime.js.map +1 -1
  90. package/workflows/container-contents/syncLane.d.ts +1 -1
  91. package/workflows/container-contents/syncLane.js.map +1 -1
  92. package/workflows/container-contents/tombstones/documentPurge.d.ts +2 -3
  93. package/workflows/container-contents/tombstones/documentPurge.js +1 -2
  94. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  95. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +3 -2
  96. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  97. package/workflows/documents/create/index.d.ts +5 -42
  98. package/workflows/documents/create/index.js +12 -1
  99. package/workflows/documents/create/index.js.map +1 -1
  100. package/workflows/documents/create/remoteDocumentCreateRequest.d.ts +47 -0
  101. package/workflows/documents/create/remoteDocumentCreateRequest.js +2 -0
  102. package/workflows/documents/create/remoteDocumentCreateRequest.js.map +1 -0
  103. package/workflows/documents/index.d.ts +6 -5
  104. package/workflows/documents/index.js +2 -3
  105. package/workflows/documents/index.js.map +1 -1
  106. package/workflows/documents/remote/remoteDocumentCollaborators.d.ts +6 -4
  107. package/workflows/documents/remote/remoteDocumentCollaborators.js.map +1 -1
  108. package/workflows/documents/remote/remoteDocumentService.d.ts +12 -5
  109. package/workflows/documents/remote/remoteDocumentService.js +14 -4
  110. package/workflows/documents/remote/remoteDocumentService.js.map +1 -1
  111. package/workflows/documents/runtime.d.ts +12 -1
  112. package/workflows/documents/runtime.js +24 -16
  113. package/workflows/documents/runtime.js.map +1 -1
  114. package/workflows/documents/sync/index.js +18 -6
  115. package/workflows/documents/sync/index.js.map +1 -1
  116. package/workflows/documents/sync/readOnlySync.js.map +1 -1
  117. package/workflows/documents/sync/{readOnlySync.d.ts → remoteDocumentSyncPass.d.ts} +18 -18
  118. package/workflows/documents/sync/remoteDocumentSyncPass.js +2 -0
  119. package/workflows/documents/sync/remoteDocumentSyncPass.js.map +1 -0
  120. package/workflows/documents/sync/syncAttemptPlanning.js.map +1 -1
  121. package/workflows/documents/sync/syncLane.d.ts +1 -1
  122. package/workflows/documents/sync/syncLane.js.map +1 -1
  123. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  124. package/workflows/documents/syncFailures/syncAbandon.js.map +1 -1
  125. package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -1
  126. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  127. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js +4 -3
  128. package/workflows/documents/syncRekeys/syncContainerRekeyPreparation.js.map +1 -1
  129. package/workflows/documents/syncRekeys/syncContainerRekeys.js.map +1 -1
  130. package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -2
  131. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  132. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +5 -4
  133. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js +2 -4
  134. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -1
  135. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js +1 -2
  136. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -1
  137. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  138. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -2
  139. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +2 -2
  140. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  141. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js +4 -8
  142. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js.map +1 -1
  143. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +2 -3
  144. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  145. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
  146. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +2 -2
  147. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
  148. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +2 -2
  149. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  150. package/workflows/principals/index.d.ts +1 -0
  151. package/workflows/principals/index.js.map +1 -1
  152. package/workflows/principals/principalPolicyService.d.ts +64 -0
  153. package/workflows/principals/principalPolicyService.js +117 -0
  154. package/workflows/principals/principalPolicyService.js.map +1 -0
  155. package/workflows/principals/runtimePolicyRecovery.d.ts +13 -10
  156. package/workflows/principals/runtimePolicyRecovery.js +9 -17
  157. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  158. package/workflows/principals/runtimeProjectionPolicyRecovery.js +7 -8
  159. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  160. package/data/principals/principalHistoryRuntime.js +0 -12
  161. package/data/principals/principalHistoryRuntime.js.map +0 -1
  162. package/workflows/documents/sync/index.d.ts +0 -3
  163. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.d.ts +0 -16
  164. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js +0 -39
  165. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js.map +0 -1
  166. package/workflows/principals/runtimePolicyWarmer.d.ts +0 -26
  167. package/workflows/principals/runtimePolicyWarmer.js +0 -48
  168. package/workflows/principals/runtimePolicyWarmer.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC,EAAE,MAAM,kBAAkB,CAAC;AAEvE,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,yBAAyB,EAAE,MAAM,kCAAkC,CAAC;AAC7E,OAA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CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
1
+ {"version":3,"file":"syncAutomaticContainerRekeys.js","sourceRoot":"","sources":["syncAutomaticContainerRekeys.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAK5D,OAAO,EAAE,2BAA2B,EAAE,MAAM,4BAA4B,CAAC;AACzE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8CAA8C,CAAC;AAE1F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kEAAkE,CAAC;AACvH,OAAO,EAAE,kCAAkC,EAAE,MAAM,8DAA8D,CAAC;AAClH,OAAO,EAAE,4BAA4B,EAAE,MAAM,kFAAkF,CAAC;AAChI,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,mCAAmC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,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAC/C,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACpB,UAAU,GAAG,MAAM,uBAAuB,CAAC,UAAU,EAAE,OAAO,CAAC,CAAC;IAClE,CAAC;AACH,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type {\n ContainerWriterProjectionResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport { MAX_INLINE_CONTAINER_REKEYS } from \"@tearleads/validators/util\";\nimport { ContainerAuthorAccessError } from \"../../../data/containers/shared/authorAccess\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { ContainerKekRepairInaccessibleError } from \"../../../data/documents/shared/containerKek/containerKekCurrency\";\nimport { ContainerKekTargetUnreachableError } from \"../../../data/documents/shared/containerKek/containerKekPath\";\nimport { documentContainerProjections } from \"../../../data/keyingProjectionVerification/document/documentContainerProjections\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { buildMaterializedContainerRekeyPlan } from \"../../containers\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { hasOtherLinkedWriteAccess } from \"../syncFailures/syncRepairAccess\";\nimport { applyContainerRekeyPlan } from \"./syncContainerRekeyProjection\";\n\ninterface StaleContainer {\n /** The stale container is the one the document itself is linked into. */\n readonly isPathTarget: boolean;\n readonly projection: ContainerWriterProjectionResponse;\n}\n\nfunction firstStaleContainer(\n projection: DocumentWriterProjectionResponse,\n): StaleContainer | null {\n for (const path of documentContainerProjections(projection)) {\n for (let index = 1; index < path.containerKeks.length; index += 1) {\n const parent = path.containerKeks[index - 1];\n const child = path.containerKeks[index];\n if (!parent || !child)\n throw new Error(\"Container KEK path is incomplete\");\n if (child.parentContainerKeyEpochId === parent.containerKeyEpochId) {\n continue;\n }\n return {\n isPathTarget: index === path.containerKeks.length - 1,\n projection: {\n ...path,\n containerId: child.containerId,\n containerKeks: path.containerKeks.slice(0, index + 1),\n path: path.path.slice(0, index + 1),\n },\n };\n }\n }\n return null;\n}\n\n/**\n * The stale container is not this writer's to re-key: no wrap on the verified\n * path opens it, or the signed path grants the signer no write access there.\n * Both are judged against the path sliced at the stale container, so a grant\n * held only further down never counts — exactly the API's `container.rekey`\n * rule. Anything else (keyring damage, a forged path) stays an error.\n *\n * A target's write refusal is handled separately: another linked target may\n * still authorize the document write. Key unwrap failures on a target stay\n * errors, because this path's readable grant should open its own key.\n */\nfunction isRepairInaccessible(error: unknown, stale: StaleContainer): boolean {\n if (stale.isPathTarget) return false;\n return (\n error instanceof ContainerAuthorAccessError ||\n (error instanceof ContainerKekTargetUnreachableError &&\n error.containerId === stale.projection.containerId)\n );\n}\n\n/** Prepare parent-first repairs; the sync transaction commits them with the write. */\nexport async function buildAutomaticContainerRekeys(\n sync: RemoteDocumentSyncPass,\n initialProjection: DocumentWriterProjectionResponse,\n): Promise<{ plans: MaterializedContainerRekeyPlan[]; hasMore: boolean }> {\n const plans: MaterializedContainerRekeyPlan[] = [];\n const plannedIds = new Set<string>();\n let projection = initialProjection;\n for (;;) {\n const stale = firstStaleContainer(projection);\n if (!stale) return { plans, hasMore: false };\n const previousProjection = stale.projection;\n if (plans.length >= MAX_INLINE_CONTAINER_REKEYS) {\n return { plans, hasMore: true };\n }\n // Use the shared cancellation sentinel: syncRemoteDocument converts only\n // that to a graceful null, so a plain Error would report a routine\n // generation flip mid-repair as a real sync failure.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n if (plannedIds.has(previousProjection.containerId)) {\n // Abandon like every other routine repair failure: two linked paths\n // disagreeing about a container is a concurrent-rotation race, not a\n // defect, and a raw Error would crash the sync lane instead.\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n // Assert rather than adopt: resolveRotationContext compares the verified\n // manifest's organization against the author's, so substituting the path's\n // own organization here would make that the only cross-org check and leave\n // it comparing a server-supplied value with itself.\n if (previousProjection.organizationId !== sync.author.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair crosses the author's organization\",\n );\n }\n const planned = await buildMaterializedContainerRekeyPlan({\n author: sync.author,\n persistVerificationCheckpoints: false,\n previousProjection,\n signedAt: sync.signedAt,\n targetSecretKey: sync.targetSecretKey,\n resolveProjectionUserKey: sync.resolveProjectionUserKey,\n stillCurrent: sync.stillCurrent,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n execSql: sync.execSql,\n }).catch(async (error: unknown) => {\n if (error instanceof ContainerAuthorAccessError && stale.isPathTarget) {\n if (\n await hasOtherLinkedWriteAccess(\n sync,\n initialProjection,\n previousProjection.containerId,\n )\n ) {\n throw new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n );\n }\n await sync.onTerminalSubmitFailure?.({\n code: error.code,\n message: error.message,\n ok: false,\n report: () => undefined,\n status: error.status,\n });\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n }\n // Repairs run parent-first and access inherits downward, so only the\n // first stale container can be out of reach. Retry-classified like any\n // stale path: one refetch sees a repair a capable member already made.\n throw isRepairInaccessible(error, stale)\n ? new ContainerKekRepairInaccessibleError(\n previousProjection.containerId,\n )\n : error;\n });\n plannedIds.add(previousProjection.containerId);\n plans.push(planned);\n projection = await applyContainerRekeyPlan(projection, planned);\n }\n}\n"]}
@@ -11,9 +11,10 @@ import { shouldRetrySyncWithFreshWriterProjection } from "../syncFailures/syncFa
11
11
  import { DocumentAncestorRepairAbandonedError } from "../syncFailures/syncRepairAbandon.js";
12
12
  import { buildAutomaticContainerRekeys } from "./syncAutomaticContainerRekeys.js";
13
13
  /**
14
- * Repairs committed during one sync pass, keyed by the pass's own input object
15
- * (stable across all three attempts). The sync loop explicitly prepares each
16
- * attempt, so a counter local to one call would not bound the whole pass.
14
+ * Repairs committed during one sync pass, keyed by the pass object that one
15
+ * `syncRemoteDocument` call builds and hands to all three attempts. The sync
16
+ * loop explicitly prepares each attempt, so a counter local to one call would
17
+ * not bound the whole pass.
17
18
  */
18
19
  const passRepairTotals = new WeakMap();
19
20
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"syncContainerRekeyPreparation.js","sourceRoot":"","sources":["syncContainerRekeyPreparation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,yDAAyD,CAAC;AAE5G,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAC9F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EACL,uBAAuB,EACvB,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAE/E;;;;GAIG;AACH,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAmC,CAAC;AAExE;;;;;GAKG;AACH,MAAM,sBAAsB,GAAG,IAAI,OAAO,EAA2B,CAAC;AAEtE,MAAM,UAAU,iCAAiC,CAC/C,IAA6B;IAE7B,OAAO,sBAAsB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,IAA6B;IAE7B,sBAAsB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC;AAED,gF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ACvD,0EAA0E;YAC1E,0EAA0E;YAC1E,qCAAqC;YACrC,MAAM,IAAI,oCAAoC,CAAC,eAAe,CAAC,CAAC;QAClE,CAAC;QACD,4EAA4E;QAC5E,0EAA0E;QAC1E,mCAAmC;QACnC,IAAI,KAAK,CAAC,UAAU,KAAK,IAAI,CAAC,UAAU,EAAE,CAAC;YACzC,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;QACJ,CAAC;QACD,UAAU,GAAG,KAAK,CAAC;IACrB,CAAC;AACH,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,IAA6B,EAC7B,UAA4C;IAE5C,IAAI,CAAC;QACH,OAAO,MAAM,+BAA+B,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IACjE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IACE,CAAC,IAAI,CAAC,SAAS,CAAC,6BAA6B;YAC7C,CAAC,wCAAwC,CAAC,KAAK,CAAC;YAEhD,MAAM,KAAK,CAAC;IAChB,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC;QACrD,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;QACrD,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,iBAAiB,EAAE,IAAI,CAAC,uBAAuB;QAC/C,YAAY,EAAE,IAAI,CAAC,YAAY;KAChC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,CAAC,CAAC,+BAA+B,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { acknowledgeContainerMutationBatch } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n submitContainerRotation,\n submitRotationCarryingDescendants,\n} from \"../../containers/child/mutationSubmit\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { shouldRetrySyncWithFreshWriterProjection } from \"../syncFailures/syncFailureClassification\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\n\n/**\n * Repairs committed during one sync pass, keyed by the pass's own input object\n * (stable across all three attempts). The sync loop explicitly prepares each\n * attempt, so a counter local to one call would not bound the whole pass.\n */\nconst passRepairTotals = new WeakMap<SyncRemoteDocumentInput, number>();\n\n/**\n * Passes whose inline repairs the server refused for stranding a level above a\n * directly granted container. The write's flat rekey list cannot say which\n * descendants each repair must carry; a standalone rekey can, so the rest of\n * the pass commits every repair standalone before writing.\n */\nconst standaloneRepairPasses = new WeakSet<SyncRemoteDocumentInput>();\n\nexport function requiresStandaloneAncestorRepairs(\n sync: SyncRemoteDocumentInput,\n): boolean {\n return standaloneRepairPasses.has(sync);\n}\n\nexport function requireStandaloneAncestorRepairs(\n sync: SyncRemoteDocumentInput,\n): void {\n standaloneRepairPasses.add(sync);\n}\n\n/** A refusal the writer cannot clear by retrying, as opposed to 5xx/offline. */\nfunction isTerminalRepairStatus(status: number | null): boolean {\n return status === 401 || status === 402 || status === 403;\n}\n\n/**\n * One standalone repair. Prefers the status-bearing rekey: a permanent refusal\n * (403 once ancestor write access is revoked, 402) must leave a durable record,\n * while a 5xx or an offline blip must not, and plain `rekeyContainer` collapses\n * both to null. It is also the only way to learn which descendant rekeys this\n * repair must carry. An adapter without it still repairs; its refusals are just\n * reported as an ordinary abandon.\n */\nfunction submitStandaloneRepair(\n sync: SyncRemoteDocumentInput,\n plan: MaterializedContainerRekeyPlan[\"plan\"],\n writerProjection: MaterializedContainerRekeyPlan[\"writerProjection\"],\n) {\n const options = {\n expectedPaymentRequiredOrganizationId: plan.state.organizationId,\n };\n const { getContainerWriterProjection, rekeyContainerResult } = sync.apiClient;\n return submitRotationCarryingDescendants({\n carriedRekeys: getContainerWriterProjection && {\n planning: {\n apiClient: {\n getContainerWriterProjection: getContainerWriterProjection.bind(\n sync.apiClient,\n ),\n },\n author: sync.author,\n execSql: sync.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n sync.resolveProjectionUserKey,\n \"Document ancestor repair\",\n ),\n stillCurrent: sync.stillCurrent,\n targetSecretKey: sync.targetSecretKey,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n },\n rotated: async () => writerProjection,\n },\n stillCurrent: sync.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...plan.request, containerRekeys: [...carried] }\n : plan.request;\n return submitContainerRotation({\n plain: () =>\n sync.apiClient.rekeyContainer(plan.containerId, request, options),\n result: rekeyContainerResult\n ? () =>\n rekeyContainerResult.call(\n sync.apiClient,\n plan.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n\nasync function abandonRefusedRepair(\n sync: SyncRemoteDocumentInput,\n containerId: string,\n result: Awaited<ReturnType<typeof submitStandaloneRepair>>[\"result\"],\n): Promise<never> {\n if (!result.ok && isTerminalRepairStatus(result.status)) {\n await sync.onTerminalSubmitFailure?.({\n code: \"document_ancestor_repair_refused\",\n message: `Ancestor repair refused for ${containerId}`,\n ok: false,\n report: () => undefined,\n status: result.status,\n });\n }\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n}\n\n/** A repair and everything it carried committed together. */\nfunction markRepaired(\n repairedIds: Set<string>,\n plan: { readonly containerId: string },\n carriedPlans: readonly { readonly plan: { readonly containerId: string } }[],\n): void {\n repairedIds.add(plan.containerId);\n for (const carried of carriedPlans) {\n repairedIds.add(carried.plan.containerId);\n }\n}\n\nasync function commitRepairPrefix(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n repairedIds: Set<string>;\n sync: SyncRemoteDocumentInput;\n}): Promise<number> {\n let committed = 0;\n for (const { plan, writerProjection } of input.plans) {\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n if (input.sync.isRemoteSyncBlocked?.(plan.state.organizationId)) {\n throw new DocumentAncestorRepairAbandonedError(\"blocked\");\n }\n if (input.repairedIds.has(plan.containerId)) {\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n const { carriedPlans, result } = await submitStandaloneRepair(\n input.sync,\n plan,\n writerProjection,\n );\n const response = result.ok ? result.data : null;\n // Deliberately not ContainerKekRepairRequiredError: that is classified as\n // retryable, so a handled refusal would re-sign the whole prefix before\n // failing again, and the retry never reaches onTerminalSubmitFailure\n // regardless, because this throws before submission.\n if (!response) {\n return abandonRefusedRepair(input.sync, plan.containerId, result);\n }\n // What a repair carried committed with it, so the pins advance together.\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.sync.execSql,\n plans: [plan, ...carriedPlans.map((carried) => carried.plan)],\n responses: [response, ...(response.containerRekeys ?? [])],\n stillCurrent: input.sync.stillCurrent,\n });\n if (!acknowledged) {\n // A refused guarded transaction is usually a generation flip; surface it\n // as the shared cancellation so syncRemoteDocument returns null instead\n // of reporting a routine flip as a sync failure.\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n throw new Error(\"Document ancestor repair was superseded\");\n }\n markRepaired(input.repairedIds, plan, carriedPlans);\n committed += 1 + carriedPlans.length;\n // The rest of this prefix was signed before the carry. A plan for a carried\n // container extends a superseded head, and one below it pins an epoch that\n // was never minted. Stop here; the caller refetches and re-plans.\n if (carriedPlans.length > 0) return committed;\n }\n return committed;\n}\n\n/**\n * Large repairs commit a bounded prefix; the last batch stays atomic with content.\n * A tighter local resource budget may be used, but never above the protocol cap.\n */\nexport async function prepareAutomaticContainerRekeys(\n sync: SyncRemoteDocumentInput,\n initialProjection: DocumentWriterProjectionResponse,\n maxRepairs = MAX_CONTAINER_PATH_LENGTH,\n): Promise<{\n plans: readonly MaterializedContainerRekeyPlan[];\n projection: DocumentWriterProjectionResponse;\n}> {\n if (initialProjection.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n let projection = initialProjection;\n const repairedIds = new Set<string>();\n // `repairedIds` only breaks a loop within one preparation. An explicit sync\n // retry starts another preparation with a fresh set. Bound the\n // work by the deepest authorizing path the protocol allows, counted across\n // the whole pass rather than per call: no honest chain needs more repairs\n // than that, so re-entry cannot multiply the budget.\n for (;;) {\n const batch = await buildAutomaticContainerRekeys(sync, projection);\n const commitsStandalone =\n batch.hasMore ||\n (batch.plans.length > 0 && standaloneRepairPasses.has(sync));\n if (!commitsStandalone) return { plans: batch.plans, projection };\n // Standalone mutations require authentic document scope before any request.\n // Persist the verified heads here, unlike the inline path: a committed\n // repair is acknowledged against the latest durable pin, and a repaired\n // ancestor is always past epoch 1, so a device that has never pinned it\n // would reject its own acknowledgement after the server already committed\n // the rekey. The inline path needs no pin because the sync response\n // re-verifies and pins before anything is acknowledged.\n await assertDocumentWriterProjectionConsistent(projection, {\n ...projectionVerificationOptions(sync),\n persistVerificationCheckpoints: true,\n allowStaleContentKeyBundle: true,\n });\n // Charge what this prefix can still commit, then settle to what it did: it\n // stops early after a repair that carried something, and charging the plans\n // it never submitted would spend the budget on work that did not happen.\n const committedBefore = passRepairTotals.get(sync) ?? 0;\n if (\n committedBefore + batch.plans.length >\n Math.min(maxRepairs, MAX_CONTAINER_PATH_LENGTH)\n ) {\n throw new DocumentAncestorRepairAbandonedError(\"depth-budget\");\n }\n passRepairTotals.set(\n sync,\n committedBefore +\n (await commitRepairPrefix({ plans: batch.plans, repairedIds, sync })),\n );\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n // Always a write-bearing pass, so a terminal projection failure (a 403\n // after revocation mid-repair) must leave the durable record that the\n // queued writes are blocked. onReadOnlyProjectionFailure is documented\n // for passes without queued writes and would not apply here.\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n if (!fresh) {\n // refreshSyncAttemptWriterProjection returns null on a generation flip.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n // It has already called onSyncAbandoned by this point, and on a coded 404\n // ran the verified local teardown, so a bare Error would double-signal as\n // an abandon plus a sync-lane crash.\n throw new DocumentAncestorRepairAbandonedError(\"unrefreshable\");\n }\n // The scope check above guards the first round only; a refetched projection\n // is server-supplied too, and nothing in the refresh path proves it names\n // the document this repair is for.\n if (fresh.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n projection = fresh;\n }\n}\n\n/** An explicit preparation retry may commit repairs; plan retries never do. */\nexport async function prepareSyncAttemptContainerRekeys(\n sync: SyncRemoteDocumentInput,\n projection: DocumentWriterProjectionResponse,\n) {\n try {\n return await prepareAutomaticContainerRekeys(sync, projection);\n } catch (error) {\n if (\n !sync.apiClient.evictDocumentWriterProjection ||\n !shouldRetrySyncWithFreshWriterProjection(error)\n )\n throw error;\n }\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n return fresh ? prepareAutomaticContainerRekeys(sync, fresh) : null;\n}\n"]}
1
+ {"version":3,"file":"syncContainerRekeyPreparation.js","sourceRoot":"","sources":["syncContainerRekeyPreparation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAE5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,EAAE,iCAAiC,EAAE,MAAM,yDAAyD,CAAC;AAE5G,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AACxH,OAAO,EAAE,gCAAgC,EAAE,MAAM,4CAA4C,CAAC;AAC9F,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EACL,uBAAuB,EACvB,iCAAiC,GAClC,MAAM,uCAAuC,CAAC;AAE/C,OAAO,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,wCAAwC,EAAE,MAAM,2CAA2C,CAAC;AACrG,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAE/E;;;;;GAKG;AACH,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAAkC,CAAC;AAEvE;;;;;GAKG;AACH,MAAM,sBAAsB,GAAG,IAAI,OAAO,EAA0B,CAAC;AAErE,MAAM,UAAU,iCAAiC,CAC/C,IAA4B;IAE5B,OAAO,sBAAsB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,IAA4B;IAE5B,sBAAsB,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;AACnC,CAA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C,CAAC;YACvD,0EAA0E;YAC1E,0EAA0E;YAC1E,qCAAqC;YACrC,MAAM,IAAI,oCAAoC,CAAC,eAAe,CAAC,CAAC;QAClE,CAAC;QACD,4EAA4E;QAC5E,0EAA0E;QAC1E,mCAAmC;QACnC,IAAI,KAAK,CAAC,UAAU,KAAK,IAAI,CAAC,UAAU,EAAE,CAAC;YACzC,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;QACJ,CAAC;QACD,UAAU,GAAG,KAAK,CAAC;IACrB,CAAC;AACH,CAAC;AAED,+EAA+E;AAC/E,MAAM,CAAC,KAAK,UAAU,iCAAiC,CACrD,IAA4B,EAC5B,UAA4C;IAE5C,IAAI,CAAC;QACH,OAAO,MAAM,+BAA+B,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IACjE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IACE,CAAC,IAAI,CAAC,SAAS,CAAC,6BAA6B;YAC7C,CAAC,wCAAwC,CAAC,KAAK,CAAC;YAEhD,MAAM,KAAK,CAAC;IAChB,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,kCAAkC,CAAC;QACrD,SAAS,EAAE,IAAI,CAAC,SAAS;QACzB,UAAU,EAAE,IAAI,CAAC,UAAU;QAC3B,uBAAuB,EAAE,IAAI,CAAC,uBAAuB;QACrD,eAAe,EAAE,IAAI,CAAC,eAAe;QACrC,WAAW,EAAE,IAAI,CAAC,WAAW;QAC7B,iBAAiB,EAAE,IAAI,CAAC,uBAAuB;QAC/C,YAAY,EAAE,IAAI,CAAC,YAAY;KAChC,CAAC,CAAC;IACH,OAAO,KAAK,CAAC,CAAC,CAAC,+BAA+B,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport { MAX_CONTAINER_PATH_LENGTH } from \"@tearleads/validators/util\";\nimport { acknowledgeContainerMutationBatch } from \"../../../data/containers/shared/mutationAcknowledgement\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { assertDocumentWriterProjectionConsistent } from \"../../../data/documents/shared/projection\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport { requireProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport {\n submitContainerRotation,\n submitRotationCarryingDescendants,\n} from \"../../containers/child/mutationSubmit\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { refreshSyncAttemptWriterProjection } from \"../syncFailures\";\nimport { shouldRetrySyncWithFreshWriterProjection } from \"../syncFailures/syncFailureClassification\";\nimport { DocumentAncestorRepairAbandonedError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\n\n/**\n * Repairs committed during one sync pass, keyed by the pass object that one\n * `syncRemoteDocument` call builds and hands to all three attempts. The sync\n * loop explicitly prepares each attempt, so a counter local to one call would\n * not bound the whole pass.\n */\nconst passRepairTotals = new WeakMap<RemoteDocumentSyncPass, number>();\n\n/**\n * Passes whose inline repairs the server refused for stranding a level above a\n * directly granted container. The write's flat rekey list cannot say which\n * descendants each repair must carry; a standalone rekey can, so the rest of\n * the pass commits every repair standalone before writing.\n */\nconst standaloneRepairPasses = new WeakSet<RemoteDocumentSyncPass>();\n\nexport function requiresStandaloneAncestorRepairs(\n sync: RemoteDocumentSyncPass,\n): boolean {\n return standaloneRepairPasses.has(sync);\n}\n\nexport function requireStandaloneAncestorRepairs(\n sync: RemoteDocumentSyncPass,\n): void {\n standaloneRepairPasses.add(sync);\n}\n\n/** A refusal the writer cannot clear by retrying, as opposed to 5xx/offline. */\nfunction isTerminalRepairStatus(status: number | null): boolean {\n return status === 401 || status === 402 || status === 403;\n}\n\n/**\n * One standalone repair. Prefers the status-bearing rekey: a permanent refusal\n * (403 once ancestor write access is revoked, 402) must leave a durable record,\n * while a 5xx or an offline blip must not, and plain `rekeyContainer` collapses\n * both to null. It is also the only way to learn which descendant rekeys this\n * repair must carry. An adapter without it still repairs; its refusals are just\n * reported as an ordinary abandon.\n */\nfunction submitStandaloneRepair(\n sync: RemoteDocumentSyncPass,\n plan: MaterializedContainerRekeyPlan[\"plan\"],\n writerProjection: MaterializedContainerRekeyPlan[\"writerProjection\"],\n) {\n const options = {\n expectedPaymentRequiredOrganizationId: plan.state.organizationId,\n };\n const { getContainerWriterProjection, rekeyContainerResult } = sync.apiClient;\n return submitRotationCarryingDescendants({\n carriedRekeys: getContainerWriterProjection && {\n planning: {\n apiClient: {\n getContainerWriterProjection: getContainerWriterProjection.bind(\n sync.apiClient,\n ),\n },\n author: sync.author,\n execSql: sync.execSql,\n resolveProjectionUserKey: requireProjectionUserKeyResolver(\n sync.resolveProjectionUserKey,\n \"Document ancestor repair\",\n ),\n stillCurrent: sync.stillCurrent,\n targetSecretKey: sync.targetSecretKey,\n warmReferencedPrincipalPolicies: sync.warmReferencedPrincipalPolicies,\n },\n rotated: async () => writerProjection,\n },\n stillCurrent: sync.stillCurrent,\n submit: (carried) => {\n const request = carried.length\n ? { ...plan.request, containerRekeys: [...carried] }\n : plan.request;\n return submitContainerRotation({\n plain: () =>\n sync.apiClient.rekeyContainer(plan.containerId, request, options),\n result: rekeyContainerResult\n ? () =>\n rekeyContainerResult.call(\n sync.apiClient,\n plan.containerId,\n request,\n { ...options, reportErrors: false },\n )\n : undefined,\n });\n },\n });\n}\n\nasync function abandonRefusedRepair(\n sync: RemoteDocumentSyncPass,\n containerId: string,\n result: Awaited<ReturnType<typeof submitStandaloneRepair>>[\"result\"],\n): Promise<never> {\n if (!result.ok && isTerminalRepairStatus(result.status)) {\n await sync.onTerminalSubmitFailure?.({\n code: \"document_ancestor_repair_refused\",\n message: `Ancestor repair refused for ${containerId}`,\n ok: false,\n report: () => undefined,\n status: result.status,\n });\n }\n throw new DocumentAncestorRepairAbandonedError(\"refused\");\n}\n\n/** A repair and everything it carried committed together. */\nfunction markRepaired(\n repairedIds: Set<string>,\n plan: { readonly containerId: string },\n carriedPlans: readonly { readonly plan: { readonly containerId: string } }[],\n): void {\n repairedIds.add(plan.containerId);\n for (const carried of carriedPlans) {\n repairedIds.add(carried.plan.containerId);\n }\n}\n\nasync function commitRepairPrefix(input: {\n plans: readonly MaterializedContainerRekeyPlan[];\n repairedIds: Set<string>;\n sync: RemoteDocumentSyncPass;\n}): Promise<number> {\n let committed = 0;\n for (const { plan, writerProjection } of input.plans) {\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n if (input.sync.isRemoteSyncBlocked?.(plan.state.organizationId)) {\n throw new DocumentAncestorRepairAbandonedError(\"blocked\");\n }\n if (input.repairedIds.has(plan.containerId)) {\n throw new DocumentAncestorRepairAbandonedError(\"peer-rotation\");\n }\n const { carriedPlans, result } = await submitStandaloneRepair(\n input.sync,\n plan,\n writerProjection,\n );\n const response = result.ok ? result.data : null;\n // Deliberately not ContainerKekRepairRequiredError: that is classified as\n // retryable, so a handled refusal would re-sign the whole prefix before\n // failing again, and the retry never reaches onTerminalSubmitFailure\n // regardless, because this throws before submission.\n if (!response) {\n return abandonRefusedRepair(input.sync, plan.containerId, result);\n }\n // What a repair carried committed with it, so the pins advance together.\n const acknowledged = await acknowledgeContainerMutationBatch({\n execSql: input.sync.execSql,\n plans: [plan, ...carriedPlans.map((carried) => carried.plan)],\n responses: [response, ...(response.containerRekeys ?? [])],\n stillCurrent: input.sync.stillCurrent,\n });\n if (!acknowledged) {\n // A refused guarded transaction is usually a generation flip; surface it\n // as the shared cancellation so syncRemoteDocument returns null instead\n // of reporting a routine flip as a sync failure.\n assertProjectionVerificationCurrent(input.sync.stillCurrent);\n throw new Error(\"Document ancestor repair was superseded\");\n }\n markRepaired(input.repairedIds, plan, carriedPlans);\n committed += 1 + carriedPlans.length;\n // The rest of this prefix was signed before the carry. A plan for a carried\n // container extends a superseded head, and one below it pins an epoch that\n // was never minted. Stop here; the caller refetches and re-plans.\n if (carriedPlans.length > 0) return committed;\n }\n return committed;\n}\n\n/**\n * Large repairs commit a bounded prefix; the last batch stays atomic with content.\n * A tighter local resource budget may be used, but never above the protocol cap.\n */\nexport async function prepareAutomaticContainerRekeys(\n sync: RemoteDocumentSyncPass,\n initialProjection: DocumentWriterProjectionResponse,\n maxRepairs = MAX_CONTAINER_PATH_LENGTH,\n): Promise<{\n plans: readonly MaterializedContainerRekeyPlan[];\n projection: DocumentWriterProjectionResponse;\n}> {\n if (initialProjection.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n let projection = initialProjection;\n const repairedIds = new Set<string>();\n // `repairedIds` only breaks a loop within one preparation. An explicit sync\n // retry starts another preparation with a fresh set. Bound the\n // work by the deepest authorizing path the protocol allows, counted across\n // the whole pass rather than per call: no honest chain needs more repairs\n // than that, so re-entry cannot multiply the budget.\n for (;;) {\n const batch = await buildAutomaticContainerRekeys(sync, projection);\n const commitsStandalone =\n batch.hasMore ||\n (batch.plans.length > 0 && standaloneRepairPasses.has(sync));\n if (!commitsStandalone) return { plans: batch.plans, projection };\n // Standalone mutations require authentic document scope before any request.\n // Persist the verified heads here, unlike the inline path: a committed\n // repair is acknowledged against the latest durable pin, and a repaired\n // ancestor is always past epoch 1, so a device that has never pinned it\n // would reject its own acknowledgement after the server already committed\n // the rekey. The inline path needs no pin because the sync response\n // re-verifies and pins before anything is acknowledged.\n await assertDocumentWriterProjectionConsistent(projection, {\n ...projectionVerificationOptions(sync),\n persistVerificationCheckpoints: true,\n allowStaleContentKeyBundle: true,\n });\n // Charge what this prefix can still commit, then settle to what it did: it\n // stops early after a repair that carried something, and charging the plans\n // it never submitted would spend the budget on work that did not happen.\n const committedBefore = passRepairTotals.get(sync) ?? 0;\n if (\n committedBefore + batch.plans.length >\n Math.min(maxRepairs, MAX_CONTAINER_PATH_LENGTH)\n ) {\n throw new DocumentAncestorRepairAbandonedError(\"depth-budget\");\n }\n passRepairTotals.set(\n sync,\n committedBefore +\n (await commitRepairPrefix({ plans: batch.plans, repairedIds, sync })),\n );\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n // Always a write-bearing pass, so a terminal projection failure (a 403\n // after revocation mid-repair) must leave the durable record that the\n // queued writes are blocked. onReadOnlyProjectionFailure is documented\n // for passes without queued writes and would not apply here.\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n if (!fresh) {\n // refreshSyncAttemptWriterProjection returns null on a generation flip.\n assertProjectionVerificationCurrent(sync.stillCurrent);\n // It has already called onSyncAbandoned by this point, and on a coded 404\n // ran the verified local teardown, so a bare Error would double-signal as\n // an abandon plus a sync-lane crash.\n throw new DocumentAncestorRepairAbandonedError(\"unrefreshable\");\n }\n // The scope check above guards the first round only; a refetched projection\n // is server-supplied too, and nothing in the refresh path proves it names\n // the document this repair is for.\n if (fresh.documentId !== sync.documentId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document ancestor repair projection targets another document\",\n );\n }\n projection = fresh;\n }\n}\n\n/** An explicit preparation retry may commit repairs; plan retries never do. */\nexport async function prepareSyncAttemptContainerRekeys(\n sync: RemoteDocumentSyncPass,\n projection: DocumentWriterProjectionResponse,\n) {\n try {\n return await prepareAutomaticContainerRekeys(sync, projection);\n } catch (error) {\n if (\n !sync.apiClient.evictDocumentWriterProjection ||\n !shouldRetrySyncWithFreshWriterProjection(error)\n )\n throw error;\n }\n const fresh = await refreshSyncAttemptWriterProjection({\n apiClient: sync.apiClient,\n documentId: sync.documentId,\n onRemoteDocumentDeleted: sync.onRemoteDocumentDeleted,\n onSyncAbandoned: sync.onSyncAbandoned,\n onSyncTrace: sync.onSyncTrace,\n onTerminalFailure: sync.onTerminalSubmitFailure,\n stillCurrent: sync.stillCurrent,\n });\n return fresh ? prepareAutomaticContainerRekeys(sync, fresh) : null;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"syncContainerRekeys.js","sourceRoot":"","sources":["syncContainerRekeys.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAGxH,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,iCAAiC,EAAE,MAAM,8BAA8B,CAAC;AACjF,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAE/D,6EAA6E;AAC7E,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAUjD;IACC,2EAA2E;IAC3E,4EAA4E;IAC5E,yEAAyE;IACzE,8EAA8E;IAC9E,8EAA8E;IAC9E,6EAA6E;IAC7E,4EAA4E;IAC5E,MAAM,kBAAkB,GAAG,KAAK,CAAC,IAAI,CAAC,qBAAqB,KAAK,SAAS,CAAC;IAC1E,IAAI,cAAc,GAAG,KAAK,CAAC,cAAc,CAAC;IAC1C,IACE,KAAK,CAAC,cAAc,CAAC,MAAM;QAC3B,CAAC,KAAK,CAAC,IAAI,CAAC,oBAAoB;QAChC,kBAAkB;QAClB,cAAc,KAAK,SAAS,EAC5B,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,6BAA6B,CAC/C,KAAK,CAAC,IAAI,EACV,KAAK,CAAC,UAAU,CACjB,CAAC;QACF,IACE,KAAK,CAAC,OAAO;YACb,CAAC,KAAK,CAAC,K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CAAC,IAAI,CAAC,OAAO,CAAC;QAC5D,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,OAAO;QAC3B,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACnC,mBAAmB;QACnB,kBAAkB,EAChB,KAAK,CAAC,kBAAkB,KAAK,SAAS;YACpC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,kBAAkB;YAC/B,CAAC,CAAC,KAAK,CAAC,kBAAkB;QAC9B,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACnC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,8BAA8B,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;QACtE,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;QAC9D,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ;QAC7B,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe;QAC3C,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC,IAAI,CAAC;KAC7C,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport type { SyncRemoteDocumentInput } from \"../sync/readOnlySync\";\nimport { DocumentSyncPreparationRequiredError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildMaterializedDocumentSyncPlan } from \"../syncPlan/syncPlanMaterial\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\nimport { requiresStandaloneAncestorRepairs } from \"./syncContainerRekeyPreparation\";\nimport { applyDocumentSyncContainerRekeys } from \"./syncContainerRekeyProjection\";\nimport { computeInlineRekeyCommitId } from \"./syncRekeyCommit\";\n\n/** Plan only: standalone server repairs belong to the outer sync attempt. */\nexport async function buildRemoteDocumentSyncPlan(input: {\n preparedRekeys?: readonly MaterializedContainerRekeyPlan[] | undefined;\n /** The version the request advertises; defaults to the sync's live one. */\n localVersionVector?: string | null | undefined;\n minLsn?: string | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullCursor?: string | undefined;\n projection: DocumentWriterProjectionResponse;\n regenerateQueuedCheckpoints: boolean;\n sync: SyncRemoteDocumentInput;\n}) {\n // Repairing this document's own container moves its key target hash, which\n // marks the content-key bundle stale. Only a pass that can build a rotation\n // snapshot is able to heal that; rotation settlement deliberately cannot\n // (`syncRequest.ts` omits the builder for `allowRecoveryBaseline: false`), so\n // repairing there would trade a classified \"ancestor repair required\" failure\n // for an unhealable bundle — after a standalone prefix may already have been\n // committed. Such a pass is left to fail as it did before automatic repair.\n const canHealStaleBundle = input.sync.buildRotationSnapshot !== undefined;\n let automaticPlans = input.preparedRekeys;\n if (\n input.pendingUpdates.length &&\n !input.sync.buildContainerRekeys &&\n canHealStaleBundle &&\n automaticPlans === undefined\n ) {\n const batch = await buildAutomaticContainerRekeys(\n input.sync,\n input.projection,\n );\n if (\n batch.hasMore ||\n (batch.plans.length > 0 && requiresStandaloneAncestorRepairs(input.sync))\n ) {\n throw new DocumentSyncPreparationRequiredError();\n }\n automaticPlans = batch.plans;\n }\n const rekeyPlans =\n input.pendingUpdates.length && input.sync.buildContainerRekeys\n ? await input.sync.buildContainerRekeys(input.projection, {\n persistVerificationCheckpoints: false,\n })\n : automaticPlans;\n const writerProjection = rekeyPlans?.length\n ? await applyDocumentSyncContainerRekeys({\n plans: rekeyPlans,\n writerProjection: input.projection,\n })\n : input.projection;\n let inlineRekeyCommitId: string | undefined;\n if (rekeyPlans?.length) {\n const headPendingUpdate = input.pendingUpdates[0];\n if (!headPendingUpdate) {\n throw new Error(\"Document inline rekey pending queue is empty\");\n }\n inlineRekeyCommitId = await computeInlineRekeyCommitId({\n headPendingUpdateId: headPendingUpdate.id,\n projection: input.projection,\n });\n }\n return buildMaterializedDocumentSyncPlan({\n author: input.sync.author,\n buildRotationSnapshot: input.sync.buildRotationSnapshot,\n containerRekeys: rekeyPlans?.map(({ plan }) => plan.request),\n execSql: input.sync.execSql,\n historyMode: input.sync.historyMode,\n inlineRekeyCommitId,\n localVersionVector:\n input.localVersionVector === undefined\n ? input.sync.localVersionVector\n : input.localVersionVector,\n minLsn: input.minLsn,\n onSyncTrace: input.sync.onSyncTrace,\n pendingUpdates: input.pendingUpdates,\n persistVerificationCheckpoints: rekeyPlans?.length ? false : undefined,\n pullCursor: input.pullCursor,\n regenerateQueuedCheckpoints: input.regenerateQueuedCheckpoints,\n signedAt: input.sync.signedAt,\n targetSecretKey: input.sync.targetSecretKey,\n writerProjection,\n ...projectionVerificationOptions(input.sync),\n });\n}\n"]}
1
+ {"version":3,"file":"syncContainerRekeys.js","sourceRoot":"","sources":["syncContainerRekeys.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,6BAA6B,EAAE,MAAM,yEAAyE,CAAC;AAGxH,OAAO,EAAE,oCAAoC,EAAE,MAAM,mCAAmC,CAAC;AACzF,OAAO,EAAE,iCAAiC,EAAE,MAAM,8BAA8B,CAAC;AACjF,OAAO,EAAE,6BAA6B,EAAE,MAAM,gCAAgC,CAAC;AAC/E,OAAO,EAAE,iCAAiC,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,gCAAgC,EAAE,MAAM,gCAAgC,CAAC;AAClF,OAAO,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAE/D,6EAA6E;AAC7E,MAAM,CAAC,KAAK,UAAU,2BAA2B,CAAC,KAUjD;IACC,2EAA2E;IAC3E,4EAA4E;IAC5E,yEAAyE;IACzE,8EAA8E;IAC9E,8EAA8E;IAC9E,6EAA6E;IAC7E,4EAA4E;IAC5E,MAAM,kBAAkB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KAAK,CAAC,8CAA8C,CAAC,CAAC;QAClE,CAAC;QACD,mBAAmB,GAAG,MAAM,0BAA0B,CAAC;YACrD,mBAAmB,EAAE,iBAAiB,CAAC,EAAE;YACzC,UAAU,EAAE,KAAK,CAAC,UAAU;SAC7B,CAAC,CAAC;IACL,CAAC;IACD,OAAO,iCAAiC,CAAC;QACvC,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,MAAM;QACzB,qBAAqB,EAAE,KAAK,CAAC,IAAI,CAAC,qBAAqB;QACvD,eAAe,EAAE,UAAU,EAAE,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC;QAC5D,OAAO,EAAE,KAAK,CAAC,IAAI,CAAC,OAAO;QAC3B,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACnC,mBAAmB;QACnB,kBAAkB,EAChB,KAAK,CAAC,kBAAkB,KAAK,SAAS;YACpC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,kBAAkB;YAC/B,CAAC,CAAC,KAAK,CAAC,kBAAkB;QAC9B,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,WAAW,EAAE,KAAK,CAAC,IAAI,CAAC,WAAW;QACnC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,8BAA8B,EAAE,UAAU,EAAE,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS;QACtE,UAAU,EAAE,KAAK,CAAC,UAAU;QAC5B,2BAA2B,EAAE,KAAK,CAAC,2BAA2B;QAC9D,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ;QAC7B,eAAe,EAAE,KAAK,CAAC,IAAI,CAAC,eAAe;QAC3C,gBAAgB;QAChB,GAAG,6BAA6B,CAAC,KAAK,CAAC,IAAI,CAAC;KAC7C,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { MaterializedContainerRekeyPlan } from \"../../../data/containers/shared/types\";\nimport { projectionVerificationOptions } from \"../../../data/documents/shared/projection/projectionVerificationOptions\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport type { RemoteDocumentSyncPass } from \"../sync/remoteDocumentSyncPass\";\nimport { DocumentSyncPreparationRequiredError } from \"../syncFailures/syncRepairAbandon\";\nimport { buildMaterializedDocumentSyncPlan } from \"../syncPlan/syncPlanMaterial\";\nimport { buildAutomaticContainerRekeys } from \"./syncAutomaticContainerRekeys\";\nimport { requiresStandaloneAncestorRepairs } from \"./syncContainerRekeyPreparation\";\nimport { applyDocumentSyncContainerRekeys } from \"./syncContainerRekeyProjection\";\nimport { computeInlineRekeyCommitId } from \"./syncRekeyCommit\";\n\n/** Plan only: standalone server repairs belong to the outer sync attempt. */\nexport async function buildRemoteDocumentSyncPlan(input: {\n preparedRekeys?: readonly MaterializedContainerRekeyPlan[] | undefined;\n /** The version the request advertises; defaults to the sync's live one. */\n localVersionVector?: string | null | undefined;\n minLsn?: string | undefined;\n pendingUpdates: readonly PendingUpdateRecord[];\n pullCursor?: string | undefined;\n projection: DocumentWriterProjectionResponse;\n regenerateQueuedCheckpoints: boolean;\n sync: RemoteDocumentSyncPass;\n}) {\n // Repairing this document's own container moves its key target hash, which\n // marks the content-key bundle stale. Only a pass that can build a rotation\n // snapshot is able to heal that; rotation settlement deliberately cannot\n // (`syncRequest.ts` omits the builder for `allowRecoveryBaseline: false`), so\n // repairing there would trade a classified \"ancestor repair required\" failure\n // for an unhealable bundle — after a standalone prefix may already have been\n // committed. Such a pass is left to fail as it did before automatic repair.\n const canHealStaleBundle = input.sync.buildRotationSnapshot !== undefined;\n let automaticPlans = input.preparedRekeys;\n if (\n input.pendingUpdates.length &&\n !input.sync.buildContainerRekeys &&\n canHealStaleBundle &&\n automaticPlans === undefined\n ) {\n const batch = await buildAutomaticContainerRekeys(\n input.sync,\n input.projection,\n );\n if (\n batch.hasMore ||\n (batch.plans.length > 0 && requiresStandaloneAncestorRepairs(input.sync))\n ) {\n throw new DocumentSyncPreparationRequiredError();\n }\n automaticPlans = batch.plans;\n }\n const rekeyPlans =\n input.pendingUpdates.length && input.sync.buildContainerRekeys\n ? await input.sync.buildContainerRekeys(input.projection, {\n persistVerificationCheckpoints: false,\n })\n : automaticPlans;\n const writerProjection = rekeyPlans?.length\n ? await applyDocumentSyncContainerRekeys({\n plans: rekeyPlans,\n writerProjection: input.projection,\n })\n : input.projection;\n let inlineRekeyCommitId: string | undefined;\n if (rekeyPlans?.length) {\n const headPendingUpdate = input.pendingUpdates[0];\n if (!headPendingUpdate) {\n throw new Error(\"Document inline rekey pending queue is empty\");\n }\n inlineRekeyCommitId = await computeInlineRekeyCommitId({\n headPendingUpdateId: headPendingUpdate.id,\n projection: input.projection,\n });\n }\n return buildMaterializedDocumentSyncPlan({\n author: input.sync.author,\n buildRotationSnapshot: input.sync.buildRotationSnapshot,\n containerRekeys: rekeyPlans?.map(({ plan }) => plan.request),\n execSql: input.sync.execSql,\n historyMode: input.sync.historyMode,\n inlineRekeyCommitId,\n localVersionVector:\n input.localVersionVector === undefined\n ? input.sync.localVersionVector\n : input.localVersionVector,\n minLsn: input.minLsn,\n onSyncTrace: input.sync.onSyncTrace,\n pendingUpdates: input.pendingUpdates,\n persistVerificationCheckpoints: rekeyPlans?.length ? false : undefined,\n pullCursor: input.pullCursor,\n regenerateQueuedCheckpoints: input.regenerateQueuedCheckpoints,\n signedAt: input.sync.signedAt,\n targetSecretKey: input.sync.targetSecretKey,\n writerProjection,\n ...projectionVerificationOptions(input.sync),\n });\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { type ReferencedPrincipalHead } from "../../internal/crypto/index.js";
2
2
  import type { ExecSql } from "../../data/sqlite/sqlSchema.js";
3
- import type { createRuntimePrincipalPolicyCurrentResolver, ResolvedPrincipalPolicyCurrent } from "../principals/runtimePolicyRecovery.js";
4
- type CurrentPolicyResolver = NonNullable<ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>>;
3
+ import type { PrincipalPolicyCurrentResolver as CurrentPolicyResolver, ResolvedPrincipalPolicyCurrent } from "../principals/runtimePolicyRecovery.js";
5
4
  interface CurrentOrganizationAuthorityInput {
6
5
  readonly execSql: ExecSql;
7
6
  readonly organizationId: string;
@@ -1 +1 @@
1
- {"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAoB/D,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAwC;IAExC,IAAI,KAAK,CAAC,qBAAqB;QAC7B,oBAAoB,CAClB,KAAK,CAAC,qBAAqB,EAC3B,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,IAAI,EAAE,CAAC;IAChD,MAAM,OAAO,GAAG,CAAC,SAA0C,EAAE,EAAE,CAC7D,KAAK,CAAC,oBAAoB,CAAC;QACzB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,SAAS,IAAI,SAAS;QACjC,kBAAkB,EAAE,IAAI;QACxB,aAAa;QACb,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IACL,MAAM,SAAS,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,qBAAqB,CAAC,CAAC;IAC7D,MAAM,kBAAkB,CACtB,SAAS,EACT,K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,QAAQ,CAAC;QAC9D,MAAM,IAAI,oCAAoC,CAC5C,iEAAiE,CAClE,CAAC;IACJ,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAqC,EACrC,SAAyC;IAEzC,MAAM,UAAU,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACxC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,cAAc;QACvC,MAAM,CAAC,WAAW,KAAK,SAAS,CAAC,MAAM,CAAC,WAAW,CACtD,CAAC;IACF,IACE,CAAC,UAAU;QACX,CAAC,6BAA6B,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC;QAExE,MAAM,IAAI,oCAAoC,CAC5C,4DAA4D,CAC7D,CAAC;AACN,CAAC;AAED,SAAS,sBAAsB,CAC7B,KAAqC,EACrC,QAAiC;IAEjC,MAAM,SAAS,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACvC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,OAAO;QAChC,MAAM,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,SAAS,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n createRuntimePrincipalPolicyCurrentResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ntype CurrentPolicyResolver = NonNullable<\n ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>\n>;\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
1
+ {"version":3,"file":"currentOrganizationAuthority.js","sourceRoot":"","sources":["currentOrganizationAuthority.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,oCAAoC,EAAE,MAAM,+DAA+D,CAAC;AACrH,OAAO,EAAE,mCAAmC,EAAE,MAAM,+CAA+C,CAAC;AACpG,OAAO,EAAE,0BAA0B,EAAE,MAAM,qEAAqE,CAAC;AACjH,OAAO,EAAE,kCAAkC,EAAE,MAAM,uEAAuE,CAAC;AAC3H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,uDAAuD,CAAC;AAgB/D,uFAAuF;AACvF,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAwC;IAExC,IAAI,KAAK,CAAC,qBAAqB;QAC7B,oBAAoB,CAClB,KAAK,CAAC,qBAAqB,EAC3B,cAAc,EACd,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,MAAM,aAAa,GAAG,KAAK,CAAC,aAAa,IAAI,EAAE,CAAC;IAChD,MAAM,OAAO,GAAG,CAAC,SAA0C,EAAE,EAAE,CAC7D,KAAK,CAAC,oBAAoB,CAAC;QACzB,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,SAAS,EAAE,SAAS,IAAI,SAAS;QACjC,kBAAkB,EAAE,IAAI;QACxB,aAAa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iC;IAEjC,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;IACxD,MAAM,kCAAkC,CAAC,KAAK,CAAC,CAAC;IAChD,IAAI,CAAC,6BAA6B,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC;QAC9D,MAAM,IAAI,oCAAoC,CAC5C,iEAAiE,CAClE,CAAC;IACJ,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;AAC1D,CAAC;AAED,SAAS,yBAAyB,CAChC,KAAqC,EACrC,SAAyC;IAEzC,MAAM,UAAU,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACxC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,cAAc;QACvC,MAAM,CAAC,WAAW,KAAK,SAAS,CAAC,MAAM,CAAC,WAAW,CACtD,CAAC;IACF,IACE,CAAC,UAAU;QACX,CAAC,6BAA6B,CAAC,UAAU,CAAC,KAAK,EAAE,SAAS,CAAC,MAAM,CAAC,KAAK,CAAC;QAExE,MAAM,IAAI,oCAAoC,CAC5C,4DAA4D,CAC7D,CAAC;AACN,CAAC;AAED,SAAS,sBAAsB,CAC7B,KAAqC,EACrC,QAAiC;IAEjC,MAAM,SAAS,GAAG,KAAK,CAAC,YAAY,CAAC,IAAI,CACvC,CAAC,MAAM,EAAE,EAAE,CACT,MAAM,CAAC,aAAa,KAAK,OAAO;QAChC,MAAM,CAAC,WAAW,KAAK,QAAQ,CAAC,WAAW,CAC9C,CAAC;IACF,IAAI,CAAC,SAAS,IAAI,CAAC,6BAA6B,CAAC,SAAS,CAAC,KAAK,EAAE,QAAQ,CAAC;QACzE,MAAM,IAAI,uBAAuB,CAC/B,oBAAoB,EACpB,wDAAwD,CACzD,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { assertProjectionVerificationCurrent } from \"../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { assertCurrentMatchesVerifiedPolicy } from \"../../data/persistence/principalPolicy/verifiedPrincipalPolicyCurrent\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../data/sqlite/sqlSchema\";\nimport type {\n PrincipalPolicyCurrentResolver as CurrentPolicyResolver,\n ResolvedPrincipalPolicyCurrent,\n} from \"../principals/runtimePolicyRecovery\";\n\ninterface CurrentOrganizationAuthorityInput {\n readonly execSql: ExecSql;\n readonly organizationId: string;\n readonly organizationReference?: ReferencedPrincipalHead | null | undefined;\n readonly resolveCurrentPolicy: CurrentPolicyResolver;\n readonly recoveryBatch?: object | undefined;\n readonly stillCurrent: () => boolean;\n}\n\n/** One directory view with bounded, authenticated current artifacts for its groups. */\nexport async function loadCurrentOrganizationAuthority(\n input: CurrentOrganizationAuthorityInput,\n) {\n if (input.organizationReference)\n assertReferenceScope(\n input.organizationReference,\n \"organization\",\n input.organizationId,\n );\n const recoveryBatch = input.recoveryBatch ?? {};\n const resolve = (reference?: ReferencedPrincipalHead | null) =>\n input.resolveCurrentPolicy({\n organizationId: input.organizationId,\n reference: reference ?? undefined,\n preferLocalCurrent: true,\n recoveryBatch,\n stillCurrent: input.stillCurrent,\n });\n const directory = await resolve(input.organizationReference);\n await assertExactCurrent(\n directory,\n input.organizationReference ?? directory.policy.state,\n );\n const descriptor = parseOrganizationAuthorityDescriptor(\n directory.current.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Organization current policy payload is outside its scope\",\n );\n const adminHead = requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n );\n const admins = await resolve(adminHead);\n await assertExactCurrent(admins, adminHead);\n assertDirectoryDependency(admins, directory);\n const stillCurrent = () =>\n input.stillCurrent() && directory.stillCurrent() && admins.stillCurrent();\n const validate = async (value: ResolvedPrincipalPolicyCurrent) => {\n assertProjectionVerificationCurrent(stillCurrent);\n await new KeyingCheckpointRepository(\n input.execSql,\n ).validateKeyingCheckpointsAtomically({\n access: [],\n policies: [...value.dependencies, value.policy],\n stillCurrent: () => stillCurrent() && value.stillCurrent(),\n });\n assertProjectionVerificationCurrent(\n () => stillCurrent() && value.stillCurrent(),\n );\n };\n await validate(admins);\n return {\n admins,\n descriptor,\n directory,\n stillCurrent,\n async readGroup(groupId: string, reference?: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const head = requireOrganizationGroupHead(descriptor, groupId);\n const selected = reference ?? head;\n assertReferenceScope(selected, \"group\", groupId);\n const result =\n groupId === descriptor.adminGroupId &&\n principalHeadMatchesReference(admins.policy.state, selected)\n ? admins\n : await resolve(selected);\n await assertExactCurrent(result, head);\n assertDirectoryDependency(result, directory);\n if (groupId !== descriptor.adminGroupId)\n assertAdminsDependency(result, adminHead);\n await validate(result);\n return result;\n },\n };\n}\n\nfunction assertReferenceScope(\n reference: ReferencedPrincipalHead,\n principalType: ReferencedPrincipalHead[\"principalType\"],\n principalId: string,\n) {\n if (\n reference.principalType !== principalType ||\n reference.principalId !== principalId\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Current policy reference is outside its scope\",\n );\n}\n\nasync function assertExactCurrent(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n assertProjectionVerificationCurrent(value.stillCurrent);\n await assertCurrentMatchesVerifiedPolicy(value);\n if (!principalHeadMatchesReference(value.policy.state, expected))\n throw new ProjectionDependencyUnavailableError(\n \"Current policy changed from the selected organization directory\",\n );\n assertProjectionVerificationCurrent(value.stillCurrent);\n}\n\nfunction assertDirectoryDependency(\n value: ResolvedPrincipalPolicyCurrent,\n directory: ResolvedPrincipalPolicyCurrent,\n) {\n const dependency = value.dependencies.find(\n (policy) =>\n policy.principalType === \"organization\" &&\n policy.principalId === directory.policy.principalId,\n );\n if (\n !dependency ||\n !principalHeadMatchesReference(dependency.state, directory.policy.state)\n )\n throw new ProjectionDependencyUnavailableError(\n \"Current policy belongs to a changed organization directory\",\n );\n}\n\nfunction assertAdminsDependency(\n value: ResolvedPrincipalPolicyCurrent,\n expected: ReferencedPrincipalHead,\n) {\n const authority = value.dependencies.find(\n (policy) =>\n policy.principalType === \"group\" &&\n policy.principalId === expected.principalId,\n );\n if (!authority || !principalHeadMatchesReference(authority.state, expected))\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Current group policy omits its exact Admins dependency\",\n );\n}\n"]}
@@ -2,18 +2,19 @@ import type { EncapsulationKeyPair } from "../../../internal/crypto/index.js";
2
2
  import type { SecurityIncidentReporter } from "../../../data/shared/securityIncidents.js";
3
3
  import type { ExecSql } from "../../../data/sqlite/sqlSchema.js";
4
4
  import type { TrustedUserIdentityResolver } from "../../../data/trustedUserIdentity/index.js";
5
- import { createRuntimePrincipalPolicyCurrentResolver, type PrincipalPolicyRecoveryRuntime } from "../../principals/runtimePolicyRecovery.js";
5
+ import type { PrincipalPolicyService } from "../../principals/principalPolicyService.js";
6
+ import type { PrincipalPolicyCurrentResolver } from "../../principals/runtimePolicyRecovery.js";
6
7
  import type { PrincipalPolicyReadApi } from "../groupPolicy/groupPolicyMutationContext.js";
7
8
  import { type GroupMetadataAccessInput } from "./groupMetadataAccess.js";
8
9
  interface GroupMetadataRuntime {
9
- readonly state?: PrincipalPolicyRecoveryRuntime["state"];
10
- readonly apiClient: GroupMetadataAccessInput["apiClient"] & PrincipalPolicyReadApi & PrincipalPolicyRecoveryRuntime["apiClient"];
10
+ readonly apiClient: GroupMetadataAccessInput["apiClient"] & PrincipalPolicyReadApi;
11
11
  readonly crypto: {
12
12
  readonly encapsulationKeyPair: EncapsulationKeyPair | null;
13
13
  };
14
14
  readonly infra: {
15
15
  readonly execSql: ExecSql;
16
16
  };
17
+ readonly principalPolicies: PrincipalPolicyService;
17
18
  readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;
18
19
  readonly util: {
19
20
  readonly log: (message: string) => void;
@@ -21,7 +22,7 @@ interface GroupMetadataRuntime {
21
22
  };
22
23
  }
23
24
  export declare function createRuntimeGroupMetadataAccess(runtime: GroupMetadataRuntime, organizationId: string, stillCurrent?: () => boolean, verifyMetadataContainer?: GroupMetadataAccessInput["verifyMetadataContainer"], currentRecovery?: {
24
- readonly resolveCurrentPolicy: ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>;
25
+ readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver | undefined;
25
26
  readonly recoveryBatch: object;
26
27
  }): {
27
28
  readName: import("../principalPolicy/principalPolicyRequest.js").GroupPolicyNameReader;
@@ -1,7 +1,5 @@
1
1
  import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
2
  import { createProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/userKeyResolver.js";
3
- import { createRuntimePrincipalPolicyCurrentResolver, } from "../../principals/runtimePolicyRecovery.js";
4
- import { createRuntimePrincipalPolicyWarmer } from "../../principals/runtimePolicyWarmer.js";
5
3
  import { createCurrentGroupMetadataContainerVerifier } from "./currentGroupMetadataAuthority.js";
6
4
  import { createGroupMetadataAccess, } from "./groupMetadataAccess.js";
7
5
  export function createRuntimeGroupMetadataAccess(runtime, organizationId, stillCurrent, verifyMetadataContainer, currentRecovery) {
@@ -10,11 +8,11 @@ export function createRuntimeGroupMetadataAccess(runtime, organizationId, stillC
10
8
  throw new Error("Group metadata identity is locked");
11
9
  // The signed metadata projection selects exact citations. Reuse matching
12
10
  // private evidence with its dependencies and pins before bounded online reads.
13
- const warmer = createRuntimePrincipalPolicyWarmer(runtime, {
11
+ const warmer = runtime.principalPolicies.createWarmer({
14
12
  preferLocalCurrent: true,
15
13
  });
16
14
  const resolveCurrentPolicy = currentRecovery?.resolveCurrentPolicy ??
17
- createRuntimePrincipalPolicyCurrentResolver(runtime);
15
+ runtime.principalPolicies.createCurrentPolicyResolver();
18
16
  const authorityInput = {
19
17
  apiClient: runtime.apiClient,
20
18
  execSql: runtime.infra.execSql,
@@ -1 +1 @@
1
- {"version":3,"file":"groupMetadataRuntime.js","sourceRoot":"","sources":["groupMetadataRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAI7G,OAAO,EACL,2CAA2C,GAE5C,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,kCAAkC,EAAE,MAAM,sCAAsC,CAAC;AAE1F,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EACL,yBAAyB,GAE1B,MAAM,uBAAuB,CAAC;AAkB/B,MAAM,UAAU,gCAAgC,CAC9C,OAA6B,EAC7B,cAAsB,EACtB,YAA4B,EAC5B,uBAA6E,EAC7E,eAKC;IAED,MAAM,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,SAAS,CAAC;IACvE,IAAI,CAAC,eAAe;QAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IAC3E,yEAAyE;IACzE,+EAA+E;IAC/E,MAAM,MAAM,GAAG,kCAAkC,CAAC,OAAO,EAAE;QACzD,kBAAkB,EAAE,IAAI;KACzB,CAAC,CAAC;IACH,MAAM,oBAAoB,GACxB,eAAe,EAAE,oBAAoB;QACrC,2CAA2C,CAAC,OAAO,CAAC,CAAC;IACvD,MAAM,cAAc,GAAG;QACrB,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,cAAc;QACd,sBAAsB,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB;QAC3D,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;QAC9D,YAAY,EAAE,YAAY,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC;KAC3C,CAAC;IACF,OAAO,yBAAyB,CAAC;QAC/B,uBAAuB,EACrB,uBAAuB;YACvB,2CAA2C,CAAC;gBAC1C,GAAG,cAAc;gBACjB,oBAAoB,EAAE,sBAAsB,CAAC,oBAAoB,CAAC;gBAClE,aAAa,EAAE,eAAe,EAAE,aAAa;aAC9C,CAAC;QACJ,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,cAAc;QACd,wBAAwB,EAAE,+BAA+B,CAAC,OAAO,CAAC;QAClE,eAAe;QACf,YAAY;QACZ,+BAA+B,EAAE,MAAM;KACxC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAuE;IAEvE,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { EncapsulationKeyPair } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport {\n createRuntimePrincipalPolicyCurrentResolver,\n type PrincipalPolicyRecoveryRuntime,\n} from \"../../principals/runtimePolicyRecovery\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../principals/runtimePolicyWarmer\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport {\n createGroupMetadataAccess,\n type GroupMetadataAccessInput,\n} from \"./groupMetadataAccess\";\n\ninterface GroupMetadataRuntime {\n readonly state?: PrincipalPolicyRecoveryRuntime[\"state\"];\n readonly apiClient: GroupMetadataAccessInput[\"apiClient\"] &\n PrincipalPolicyReadApi &\n PrincipalPolicyRecoveryRuntime[\"apiClient\"];\n readonly crypto: {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n };\n readonly infra: { readonly execSql: ExecSql };\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n };\n}\n\nexport function createRuntimeGroupMetadataAccess(\n runtime: GroupMetadataRuntime,\n organizationId: string,\n stillCurrent?: () => boolean,\n verifyMetadataContainer?: GroupMetadataAccessInput[\"verifyMetadataContainer\"],\n currentRecovery?: {\n readonly resolveCurrentPolicy: ReturnType<\n typeof createRuntimePrincipalPolicyCurrentResolver\n >;\n readonly recoveryBatch: object;\n },\n) {\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!targetSecretKey) throw new Error(\"Group metadata identity is locked\");\n // The signed metadata projection selects exact citations. Reuse matching\n // private evidence with its dependencies and pins before bounded online reads.\n const warmer = createRuntimePrincipalPolicyWarmer(runtime, {\n preferLocalCurrent: true,\n });\n const resolveCurrentPolicy =\n currentRecovery?.resolveCurrentPolicy ??\n createRuntimePrincipalPolicyCurrentResolver(runtime);\n const authorityInput = {\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: stillCurrent ?? (() => true),\n };\n return createGroupMetadataAccess({\n verifyMetadataContainer:\n verifyMetadataContainer ??\n createCurrentGroupMetadataContainerVerifier({\n ...authorityInput,\n resolveCurrentPolicy: requireCurrentResolver(resolveCurrentPolicy),\n recoveryBatch: currentRecovery?.recoveryBatch,\n }),\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: warmer,\n });\n}\n\nfunction requireCurrentResolver(\n resolve: ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>,\n) {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n return resolve;\n}\n"]}
1
+ {"version":3,"file":"groupMetadataRuntime.js","sourceRoot":"","sources":["groupMetadataRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EAAE,+BAA+B,EAAE,MAAM,4DAA4D,CAAC;AAO7G,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAC9F,OAAO,EACL,yBAAyB,GAE1B,MAAM,uBAAuB,CAAC;AAiB/B,MAAM,UAAU,gCAAgC,CAC9C,OAA6B,EAC7B,cAAsB,EACtB,YAA4B,EAC5B,uBAA6E,EAC7E,eAGC;IAED,MAAM,eAAe,GAAG,OAAO,CAAC,MAAM,CAAC,oBAAoB,EAAE,SAAS,CAAC;IACvE,IAAI,CAAC,eAAe;QAAE,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IAC3E,yEAAyE;IACzE,+EAA+E;IAC/E,MAAM,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC,YAAY,CAAC;QACpD,kBAAkB,EAAE,IAAI;KACzB,CAAC,CAAC;IACH,MAAM,oBAAoB,GACxB,eAAe,EAAE,oBAAoB;QACrC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAC1D,MAAM,cAAc,GAAG;QACrB,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,cAAc;QACd,sBAAsB,EAAE,OAAO,CAAC,IAAI,CAAC,sBAAsB;QAC3D,0BAA0B,EAAE,OAAO,CAAC,0BAA0B;QAC9D,YAAY,EAAE,YAAY,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC;KAC3C,CAAC;IACF,OAAO,yBAAyB,CAAC;QAC/B,uBAAuB,EACrB,uBAAuB;YACvB,2CAA2C,CAAC;gBAC1C,GAAG,cAAc;gBACjB,oBAAoB,EAAE,sBAAsB,CAAC,oBAAoB,CAAC;gBAClE,aAAa,EAAE,eAAe,EAAE,aAAa;aAC9C,CAAC;QACJ,SAAS,EAAE,OAAO,CAAC,SAAS;QAC5B,OAAO,EAAE,OAAO,CAAC,KAAK,CAAC,OAAO;QAC9B,cAAc;QACd,wBAAwB,EAAE,+BAA+B,CAAC,OAAO,CAAC;QAClE,eAAe;QACf,YAAY;QACZ,+BAA+B,EAAE,MAAM;KACxC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,sBAAsB,CAC7B,OAAmD;IAEnD,IAAI,CAAC,OAAO;QACV,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,OAAO,OAAO,CAAC;AACjB,CAAC","sourcesContent":["import type { EncapsulationKeyPair } from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { createProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification/userKeyResolver\";\nimport type { SecurityIncidentReporter } from \"../../../data/shared/securityIncidents\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { TrustedUserIdentityResolver } from \"../../../data/trustedUserIdentity\";\nimport type { PrincipalPolicyService } from \"../../principals/principalPolicyService\";\nimport type { PrincipalPolicyCurrentResolver } from \"../../principals/runtimePolicyRecovery\";\nimport type { PrincipalPolicyReadApi } from \"../groupPolicy/groupPolicyMutationContext\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\nimport {\n createGroupMetadataAccess,\n type GroupMetadataAccessInput,\n} from \"./groupMetadataAccess\";\n\ninterface GroupMetadataRuntime {\n readonly apiClient: GroupMetadataAccessInput[\"apiClient\"] &\n PrincipalPolicyReadApi;\n readonly crypto: {\n readonly encapsulationKeyPair: EncapsulationKeyPair | null;\n };\n readonly infra: { readonly execSql: ExecSql };\n readonly principalPolicies: PrincipalPolicyService;\n readonly resolveTrustedUserIdentity: TrustedUserIdentityResolver;\n readonly util: {\n readonly log: (message: string) => void;\n readonly reportSecurityIncident: SecurityIncidentReporter;\n };\n}\n\nexport function createRuntimeGroupMetadataAccess(\n runtime: GroupMetadataRuntime,\n organizationId: string,\n stillCurrent?: () => boolean,\n verifyMetadataContainer?: GroupMetadataAccessInput[\"verifyMetadataContainer\"],\n currentRecovery?: {\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver | undefined;\n readonly recoveryBatch: object;\n },\n) {\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n if (!targetSecretKey) throw new Error(\"Group metadata identity is locked\");\n // The signed metadata projection selects exact citations. Reuse matching\n // private evidence with its dependencies and pins before bounded online reads.\n const warmer = runtime.principalPolicies.createWarmer({\n preferLocalCurrent: true,\n });\n const resolveCurrentPolicy =\n currentRecovery?.resolveCurrentPolicy ??\n runtime.principalPolicies.createCurrentPolicyResolver();\n const authorityInput = {\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n reportSecurityIncident: runtime.util.reportSecurityIncident,\n resolveTrustedUserIdentity: runtime.resolveTrustedUserIdentity,\n stillCurrent: stillCurrent ?? (() => true),\n };\n return createGroupMetadataAccess({\n verifyMetadataContainer:\n verifyMetadataContainer ??\n createCurrentGroupMetadataContainerVerifier({\n ...authorityInput,\n resolveCurrentPolicy: requireCurrentResolver(resolveCurrentPolicy),\n recoveryBatch: currentRecovery?.recoveryBatch,\n }),\n apiClient: runtime.apiClient,\n execSql: runtime.infra.execSql,\n organizationId,\n resolveProjectionUserKey: createProjectionUserKeyResolver(runtime),\n targetSecretKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: warmer,\n });\n}\n\nfunction requireCurrentResolver(\n resolve: PrincipalPolicyCurrentResolver | undefined,\n) {\n if (!resolve)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n return resolve;\n}\n"]}
@@ -1,9 +1,8 @@
1
1
  import { ProjectionDependencyUnavailableError } from "../../../data/keyingProjectionVerification/dependencyUnavailable.js";
2
- import { createRuntimePrincipalPolicyCurrentResolver, } from "../../principals/runtimePolicyRecovery.js";
3
2
  import { createCurrentGroupMetadataContainerVerifier } from "./currentGroupMetadataAuthority.js";
4
3
  /** Remote metadata destinations require the same private authority as name reads. */
5
4
  export async function verifyRuntimeGroupMetadataAuthority(input) {
6
- const resolveCurrentPolicy = createRuntimePrincipalPolicyCurrentResolver(input.runtime);
5
+ const resolveCurrentPolicy = input.runtime.principalPolicies.createCurrentPolicyResolver();
7
6
  if (!resolveCurrentPolicy)
8
7
  throw new ProjectionDependencyUnavailableError("Group metadata requires private paged recovery");
9
8
  await createCurrentGroupMetadataContainerVerifier({
@@ -1 +1 @@
1
- {"version":3,"file":"runtimeGroupMetadataAuthority.js","sourceRoot":"","sources":["runtimeGroupMetadataAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AACxH,OAAO,EACL,2CAA2C,GAE5C,MAAM,wCAAwC,CAAC;AAChD,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAE9F,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAMzD;IACC,MAAM,oBAAoB,GAAG,2CAA2C,CACtE,KAAK,CAAC,OAAO,CACd,CAAC;IACF,IAAI,CAAC,oBAAoB;QACvB,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,MAAM,2CAA2C,CAAC;QAChD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB;QACpB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport {\n createRuntimePrincipalPolicyCurrentResolver,\n type PrincipalPolicyRecoveryRuntime,\n} from \"../../principals/runtimePolicyRecovery\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\n\n/** Remote metadata destinations require the same private authority as name reads. */\nexport async function verifyRuntimeGroupMetadataAuthority(input: {\n readonly runtime: PrincipalPolicyRecoveryRuntime;\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n readonly organizationReference?: ReferencedPrincipalHead | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const resolveCurrentPolicy = createRuntimePrincipalPolicyCurrentResolver(\n input.runtime,\n );\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n await createCurrentGroupMetadataContainerVerifier({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n })(input.state, input.organizationReference);\n}\n"]}
1
+ {"version":3,"file":"runtimeGroupMetadataAuthority.js","sourceRoot":"","sources":["runtimeGroupMetadataAuthority.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,oCAAoC,EAAE,MAAM,kEAAkE,CAAC;AAExH,OAAO,EAAE,2CAA2C,EAAE,MAAM,iCAAiC,CAAC;AAE9F,qFAAqF;AACrF,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAMzD;IACC,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,CAAC,iBAAiB,CAAC,2BAA2B,EAAE,CAAC;IAChE,IAAI,CAAC,oBAAoB;QACvB,MAAM,IAAI,oCAAoC,CAC5C,gDAAgD,CACjD,CAAC;IACJ,MAAM,2CAA2C,CAAC;QAChD,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO;QACpC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB;QACpB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,qBAAqB,CAAC,CAAC;AAC/C,CAAC","sourcesContent":["import type {\n ContainerAccessManifestState,\n ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { ProjectionDependencyUnavailableError } from \"../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport type { PrincipalPolicyRuntime } from \"../../principals/principalPolicyService\";\nimport { createCurrentGroupMetadataContainerVerifier } from \"./currentGroupMetadataAuthority\";\n\n/** Remote metadata destinations require the same private authority as name reads. */\nexport async function verifyRuntimeGroupMetadataAuthority(input: {\n readonly runtime: PrincipalPolicyRuntime;\n readonly organizationId: string;\n readonly state: ContainerAccessManifestState;\n readonly organizationReference?: ReferencedPrincipalHead | undefined;\n readonly stillCurrent: () => boolean;\n}): Promise<void> {\n const resolveCurrentPolicy =\n input.runtime.principalPolicies.createCurrentPolicyResolver();\n if (!resolveCurrentPolicy)\n throw new ProjectionDependencyUnavailableError(\n \"Group metadata requires private paged recovery\",\n );\n await createCurrentGroupMetadataContainerVerifier({\n execSql: input.runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: input.stillCurrent,\n })(input.state, input.organizationReference);\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"currentGroupPolicyMutationContext.js","sourceRoot":"","sources":["currentGroupPolicyMutationContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAE7B,MAAM,m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C,CAAC;YAClC,IAAI,CAAC,OAAO,EAAE,CAAC;gBACb,0EAA0E;gBAC1E,IAAI,UAAU,CAAC,IAAI,KAAK,GAAG,EAAE,CAAC;oBAC5B,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC;oBAC9C,IAAI,MAAM,KAAK,SAAS;wBAAE,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;gBACtD,CAAC;gBACD,OAAO,GAAG,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;gBACpD,UAAU,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YAC/B,CAAC;YACD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACtD,IAAI,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO;oBAAE,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5D,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC3D,OAAO,QAAQ,CAAC,MAAM,CAAC;QACzB,CAAC;QACD,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["import {\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { createRuntimePrincipalPolicyCurrentResolver } from \"../../principals/runtimePolicyRecovery\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../groupMetadata/currentGroupMetadataAuthority\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport { loadCurrentOrganizationMutationAuthority } from \"../principalMutations/currentOrganizationMutationAuthority\";\nimport { requireSignerCanManageGroup } from \"./groupMutationAuthorization\";\n\n/** Exact current directory, strict Admins and group evidence for one mutation. */\nexport async function loadCurrentGroupPolicyMutationContext(input: {\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly resolveCurrentPolicy: NonNullable<\n ReturnType<typeof createRuntimePrincipalPolicyCurrentResolver>\n >;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n readonly stillCurrent: () => boolean;\n}) {\n input = { ...input };\n const { authority, currentOrgAdminUserIds } =\n await loadCurrentOrganizationMutationAuthority(input);\n const group = await authority.readGroup(input.groupId);\n const stillCurrent = () =>\n input.stillCurrent() && authority.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n assertGroupMetadataBinding(group.current, authority.descriptor);\n requireSignerCanManageGroup(\n group.current,\n currentOrgAdminUserIds,\n input.signerUserId,\n );\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: [...group.dependencies, group.policy],\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const adminHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.adminGroupId,\n );\n const externalAuthority: PrincipalPolicyExternalAuthority = {\n currentHead: adminHead,\n states: [\n { head: adminHead, projection: authority.admins.policy.projection },\n ],\n };\n // A reused citation keeps the lifetime of the read that produced it.\n const references = new Map<\n string,\n Promise<{\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly stillCurrent: () => boolean;\n }>\n >();\n return {\n adminGroupId: authority.descriptor.adminGroupId,\n adminCurrent: authority.admins,\n currentPolicy: group.current,\n verifiedCurrentPolicy: group.policy,\n verifyMetadataContainer:\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent,\n }),\n currentOrgAdminUserIds,\n externalAuthority,\n isOrganizationAdminsGroup:\n input.groupId === authority.descriptor.adminGroupId,\n localPolicyCheckpoint: group.policy.checkpoint,\n memberGroupId: authority.descriptor.memberGroupId,\n organizationDescriptor: authority.descriptor,\n organizationCurrent: authority.directory,\n async readPredecessorReference(reference: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const owned = structuredClone(reference);\n const key = serializeKeyingCanonicalJson({ ...owned });\n let pending = references.get(key);\n if (!pending) {\n // Keep at most one bounded selection's citations, even across many paths.\n if (references.size === 128) {\n const oldest = references.keys().next().value;\n if (oldest !== undefined) references.delete(oldest);\n }\n pending = authority.readGroup(input.groupId, owned);\n references.set(key, pending);\n }\n const selected = await pending.catch((error: unknown) => {\n if (references.get(key) === pending) references.delete(key);\n throw error;\n });\n assertProjectionVerificationCurrent(stillCurrent);\n assertProjectionVerificationCurrent(selected.stillCurrent);\n return selected.policy;\n },\n stillCurrent,\n };\n}\n"]}
1
+ {"version":3,"file":"currentGroupPolicyMutationContext.js","sourceRoot":"","sources":["currentGroupPolicyMutationContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,4BAA4B,GAE7B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,4BAA4B,EAAE,MAAM,0DAA0D,CAAC;AAGxG,OAAO,EAAE,mDAAmD,EAAE,MAAM,gDAAgD,CAAC;AACrH,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,wCAAwC,EAAE,MAAM,4DAA4D,CAAC;AACtH,OA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AK,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;gBACpD,UAAU,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YAC/B,CAAC;YACD,MAAM,QAAQ,GAAG,MAAM,OAAO,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;gBACtD,IAAI,UAAU,CAAC,GAAG,CAAC,GAAG,CAAC,KAAK,OAAO;oBAAE,UAAU,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;gBAC5D,MAAM,KAAK,CAAC;YACd,CAAC,CAAC,CAAC;YACH,mCAAmC,CAAC,YAAY,CAAC,CAAC;YAClD,mCAAmC,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;YAC3D,OAAO,QAAQ,CAAC,MAAM,CAAC;QACzB,CAAC;QACD,YAAY;KACb,CAAC;AACJ,CAAC","sourcesContent":["import {\n type PrincipalPolicyExternalAuthority,\n type ReferencedPrincipalHead,\n serializeKeyingCanonicalJson,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { requireOrganizationGroupHead } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport type { ExecSql } from \"../../../data/sqlite/sqlSchema\";\nimport type { PrincipalPolicyCurrentResolver } from \"../../principals/runtimePolicyRecovery\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../groupMetadata/currentGroupMetadataAuthority\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport { loadCurrentOrganizationMutationAuthority } from \"../principalMutations/currentOrganizationMutationAuthority\";\nimport { requireSignerCanManageGroup } from \"./groupMutationAuthorization\";\n\n/** Exact current directory, strict Admins and group evidence for one mutation. */\nexport async function loadCurrentGroupPolicyMutationContext(input: {\n readonly execSql: ExecSql;\n readonly groupId: string;\n readonly organizationId: string;\n readonly signerUserId: string;\n readonly resolveCurrentPolicy: PrincipalPolicyCurrentResolver;\n readonly recoverPendingPrincipalMutation: (\n organizationId: string,\n ) => Promise<void>;\n readonly stillCurrent: () => boolean;\n}) {\n input = { ...input };\n const { authority, currentOrgAdminUserIds } =\n await loadCurrentOrganizationMutationAuthority(input);\n const group = await authority.readGroup(input.groupId);\n const stillCurrent = () =>\n input.stillCurrent() && authority.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n assertGroupMetadataBinding(group.current, authority.descriptor);\n requireSignerCanManageGroup(\n group.current,\n currentOrgAdminUserIds,\n input.signerUserId,\n );\n await new KeyingCheckpointRepository(\n input.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: [...group.dependencies, group.policy],\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const adminHead = requireOrganizationGroupHead(\n authority.descriptor,\n authority.descriptor.adminGroupId,\n );\n const externalAuthority: PrincipalPolicyExternalAuthority = {\n currentHead: adminHead,\n states: [\n { head: adminHead, projection: authority.admins.policy.projection },\n ],\n };\n // A reused citation keeps the lifetime of the read that produced it.\n const references = new Map<\n string,\n Promise<{\n readonly policy: VerifiedPrincipalPolicyCurrent;\n readonly stillCurrent: () => boolean;\n }>\n >();\n return {\n adminGroupId: authority.descriptor.adminGroupId,\n adminCurrent: authority.admins,\n currentPolicy: group.current,\n verifiedCurrentPolicy: group.policy,\n verifyMetadataContainer:\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent,\n }),\n currentOrgAdminUserIds,\n externalAuthority,\n isOrganizationAdminsGroup:\n input.groupId === authority.descriptor.adminGroupId,\n localPolicyCheckpoint: group.policy.checkpoint,\n memberGroupId: authority.descriptor.memberGroupId,\n organizationDescriptor: authority.descriptor,\n organizationCurrent: authority.directory,\n async readPredecessorReference(reference: ReferencedPrincipalHead) {\n assertProjectionVerificationCurrent(stillCurrent);\n const owned = structuredClone(reference);\n const key = serializeKeyingCanonicalJson({ ...owned });\n let pending = references.get(key);\n if (!pending) {\n // Keep at most one bounded selection's citations, even across many paths.\n if (references.size === 128) {\n const oldest = references.keys().next().value;\n if (oldest !== undefined) references.delete(oldest);\n }\n pending = authority.readGroup(input.groupId, owned);\n references.set(key, pending);\n }\n const selected = await pending.catch((error: unknown) => {\n if (references.get(key) === pending) references.delete(key);\n throw error;\n });\n assertProjectionVerificationCurrent(stillCurrent);\n assertProjectionVerificationCurrent(selected.stillCurrent);\n return selected.policy;\n },\n stillCurrent,\n };\n}\n"]}
@@ -1,10 +1,9 @@
1
1
  import { type ReferencedPrincipalHead } from "../../../internal/crypto/index.js";
2
2
  import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
3
3
  import { createRuntimeGroupMetadataAccess } from "../groupMetadata/groupMetadataRuntime.js";
4
- import { createCurrentPrincipalMutationLease } from "../principalMutations/currentPrincipalMutationLease.js";
5
4
  import type { PrincipalMutationRecoveryApi } from "../principalMutations/principalMutationJournalManagement.js";
6
5
  import { type GroupPolicyNameReader } from "../principalPolicy/principalPolicyRequest.js";
7
- type CurrentShareRuntime = Parameters<typeof createRuntimeGroupMetadataAccess>[0] & Parameters<typeof createCurrentPrincipalMutationLease>[0] & {
6
+ type CurrentShareRuntime = Parameters<typeof createRuntimeGroupMetadataAccess>[0] & {
8
7
  readonly apiClient: {
9
8
  readonly recoverPendingPrincipalMutation?: PrincipalMutationRecoveryApi["recoverPendingPrincipalMutation"] | undefined;
10
9
  };
@@ -2,16 +2,16 @@ import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { assertProjectionVerificationCurrent } from "../../../data/keyingProjectionVerification/types.js";
3
3
  import { KeyingCheckpointRepository } from "../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
4
  import { principalHeadMatchesReference } from "../../../data/principals/organizationAuthorityDescriptor.js";
5
+ import { createCurrentPrincipalMutationLease } from "../../principals/principalPolicyService.js";
5
6
  import { loadCurrentOrganizationAuthority } from "../currentOrganizationAuthority.js";
6
7
  import { createSelectedCurrentGroupMetadataContainerVerifier } from "../groupMetadata/currentGroupMetadataAuthority.js";
7
8
  import { assertGroupMetadataBinding } from "../groupMetadata/groupMetadataBinding.js";
8
9
  import { createRuntimeGroupMetadataAccess } from "../groupMetadata/groupMetadataRuntime.js";
9
- import { createCurrentPrincipalMutationLease } from "../principalMutations/currentPrincipalMutationLease.js";
10
10
  import { groupPolicyNameMismatch, } from "../principalPolicy/principalPolicyRequest.js";
11
11
  import { GroupShareNameMismatchError } from "./sharePrincipalPolicy.js";
12
12
  /** A share read need not be a group administrator; minting a grant checks that separately. */
13
13
  export function createRuntimeCurrentSharePrincipalPolicy(runtime) {
14
- const lease = createCurrentPrincipalMutationLease(runtime);
14
+ const lease = createCurrentPrincipalMutationLease(runtime.principalPolicies);
15
15
  if (!lease)
16
16
  return undefined;
17
17
  return async (input, work) => {
@@ -1 +1 @@
1
- {"version":3,"file":"currentSharePrincipalPolicy.js","sourceRoot":"","sources":["currentSharePrincipalPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,gCAAgC,EAAE,MAAM,iCAAiC,CAAC;AACnF,OAAO,EAAE,mDAAmD,EAAE,MAAM,gDAAgD,CAAC;AACrH,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,gCAAgC,EAAE,MAAM,uCAAuC,CAAC;AACzF,OAAO,EAAE,mCAAmC,EAAE,MAAM,qDAAqD,CAAC;AAE1G,OAAO,EAEL,uBAAuB,GACxB,MAAM,2CAA2C,CAAC;AAC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YACpC,YAAY;SACb,CAAC,CACH,CAAC,QAAQ,CAAC;IACb,MAAM,QAAQ,GAAG,MAAM,uBAAuB,CAC5C,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,iBAAiB,EACvB,QAAQ,CACT,CAAC;IACF,IAAI,QAAQ;QACV,MAAM,IAAI,2BAA2B,CACnC,QAAQ,KAAK,sBAAsB;YACjC,CAAC,CAAC,kEAAkE;YACpE,CAAC,CAAC,mEAAmE,CACxE,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../groupMetadata/currentGroupMetadataAuthority\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport { createRuntimeGroupMetadataAccess } from \"../groupMetadata/groupMetadataRuntime\";\nimport { createCurrentPrincipalMutationLease } from \"../principalMutations/currentPrincipalMutationLease\";\nimport type { PrincipalMutationRecoveryApi } from \"../principalMutations/principalMutationJournalManagement\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../principalPolicy/principalPolicyRequest\";\nimport { GroupShareNameMismatchError } from \"./sharePrincipalPolicy\";\n\ntype CurrentShareRuntime = Parameters<\n typeof createRuntimeGroupMetadataAccess\n>[0] &\n Parameters<typeof createCurrentPrincipalMutationLease>[0] & {\n readonly apiClient: {\n readonly recoverPendingPrincipalMutation?:\n | PrincipalMutationRecoveryApi[\"recoverPendingPrincipalMutation\"]\n | undefined;\n };\n };\n\ninterface CurrentShareInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly expectedGroupHead?: ReferencedPrincipalHead | undefined;\n readonly expectedGroupName?: string | undefined;\n /** Trusted internal reader; it must authenticate the signed metadata container. */\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly stillCurrent: () => boolean;\n}\n\ntype CurrentGroup = Awaited<\n ReturnType<\n Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>[\"readGroup\"]\n >\n>;\n\nexport interface CurrentSharePrincipalPolicy {\n readonly current: CurrentGroup[\"current\"];\n readonly policy: CurrentGroup[\"policy\"];\n readonly checkpointPolicies: readonly CurrentGroup[\"policy\"][];\n readonly stillCurrent: () => boolean;\n}\n\n/** A share read need not be a group administrator; minting a grant checks that separately. */\nexport function createRuntimeCurrentSharePrincipalPolicy(\n runtime: CurrentShareRuntime,\n) {\n const lease = createCurrentPrincipalMutationLease(runtime);\n if (!lease) return undefined;\n return async <T>(\n input: CurrentShareInput,\n work: (policy: CurrentSharePrincipalPolicy) => Promise<T>,\n ): Promise<T> => {\n input = {\n ...input,\n expectedGroupHead: input.expectedGroupHead\n ? { ...input.expectedGroupHead }\n : undefined,\n };\n return lease(\n input.stillCurrent,\n async ({ resolveCurrentPolicy, stillCurrent: leaseCurrent }) => {\n await runtime.apiClient.recoverPendingPrincipalMutation?.(\n input.organizationId,\n );\n assertProjectionVerificationCurrent(leaseCurrent);\n const authority = await loadCurrentOrganizationAuthority({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: leaseCurrent,\n });\n const group = await authority.readGroup(input.groupId);\n const stillCurrent = () =>\n leaseCurrent() && authority.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(\n group.policy.state,\n input.expectedGroupHead,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container share expected group head conflicts with the signed organization directory\",\n );\n assertGroupMetadataBinding(group.current, authority.descriptor);\n await assertCurrentShareName({\n runtime,\n input,\n authority,\n group,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const checkpointPolicies = [...group.dependencies, group.policy];\n await new KeyingCheckpointRepository(\n runtime.infra.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: checkpointPolicies,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n current: group.current,\n policy: group.policy,\n checkpointPolicies,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function assertCurrentShareName({\n runtime,\n input,\n authority,\n group,\n stillCurrent,\n}: {\n runtime: CurrentShareRuntime;\n input: CurrentShareInput;\n authority: Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>;\n group: CurrentGroup;\n stillCurrent: () => boolean;\n}) {\n if (input.expectedGroupName === undefined) return;\n const readName =\n input.readEncryptedName ??\n createRuntimeGroupMetadataAccess(\n runtime,\n input.organizationId,\n stillCurrent,\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent,\n }),\n ).readName;\n const mismatch = await groupPolicyNameMismatch(\n group.current,\n input.expectedGroupName,\n readName,\n );\n if (mismatch)\n throw new GroupShareNameMismatchError(\n mismatch === \"forbidden_characters\"\n ? \"Container share group name contains control or format characters\"\n : \"Container share group name does not match the signed group policy\",\n );\n}\n"]}
1
+ {"version":3,"file":"currentSharePrincipalPolicy.js","sourceRoot":"","sources":["currentSharePrincipalPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAExB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,mCAAmC,EAAE,MAAM,kDAAkD,CAAC;AACvG,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,6BAA6B,EAAE,MAAM,0DAA0D,CAAC;AACzG,OAAO,EAAE,mCAAmC,EAAE,MAAM,yCAAyC,CAAC;AAC9F,OA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AAK,EACL,SAAS,EACT,KAAK,EACL,YAAY,GAOb;IACC,IAAI,KAAK,CAAC,iBAAiB,KAAK,SAAS;QAAE,OAAO;IAClD,MAAM,QAAQ,GACZ,KAAK,CAAC,iBAAiB;QACvB,gCAAgC,CAC9B,OAAO,EACP,KAAK,CAAC,cAAc,EACpB,YAAY,EACZ,mDAAmD,CAAC;YAClD,SAAS;YACT,cAAc,EAAE,KAAK,CAAC,cAAc;YACpC,YAAY;SACb,CAAC,CACH,CAAC,QAAQ,CAAC;IACb,MAAM,QAAQ,GAAG,MAAM,uBAAuB,CAC5C,KAAK,CAAC,OAAO,EACb,KAAK,CAAC,iBAAiB,EACvB,QAAQ,CACT,CAAC;IACF,IAAI,QAAQ;QACV,MAAM,IAAI,2BAA2B,CACnC,QAAQ,KAAK,sBAAsB;YACjC,CAAC,CAAC,kEAAkE;YACpE,CAAC,CAAC,mEAAmE,CACxE,CAAC;AACN,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n} from \"@tearleads/crypto\";\nimport { assertProjectionVerificationCurrent } from \"../../../data/keyingProjectionVerification/types\";\nimport { KeyingCheckpointRepository } from \"../../../data/persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { principalHeadMatchesReference } from \"../../../data/principals/organizationAuthorityDescriptor\";\nimport { createCurrentPrincipalMutationLease } from \"../../principals/principalPolicyService\";\nimport { loadCurrentOrganizationAuthority } from \"../currentOrganizationAuthority\";\nimport { createSelectedCurrentGroupMetadataContainerVerifier } from \"../groupMetadata/currentGroupMetadataAuthority\";\nimport { assertGroupMetadataBinding } from \"../groupMetadata/groupMetadataBinding\";\nimport { createRuntimeGroupMetadataAccess } from \"../groupMetadata/groupMetadataRuntime\";\nimport type { PrincipalMutationRecoveryApi } from \"../principalMutations/principalMutationJournalManagement\";\nimport {\n type GroupPolicyNameReader,\n groupPolicyNameMismatch,\n} from \"../principalPolicy/principalPolicyRequest\";\nimport { GroupShareNameMismatchError } from \"./sharePrincipalPolicy\";\n\ntype CurrentShareRuntime = Parameters<\n typeof createRuntimeGroupMetadataAccess\n>[0] & {\n readonly apiClient: {\n readonly recoverPendingPrincipalMutation?:\n | PrincipalMutationRecoveryApi[\"recoverPendingPrincipalMutation\"]\n | undefined;\n };\n};\n\ninterface CurrentShareInput {\n readonly groupId: string;\n readonly organizationId: string;\n readonly expectedGroupHead?: ReferencedPrincipalHead | undefined;\n readonly expectedGroupName?: string | undefined;\n /** Trusted internal reader; it must authenticate the signed metadata container. */\n readonly readEncryptedName?: GroupPolicyNameReader | undefined;\n readonly stillCurrent: () => boolean;\n}\n\ntype CurrentGroup = Awaited<\n ReturnType<\n Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>[\"readGroup\"]\n >\n>;\n\nexport interface CurrentSharePrincipalPolicy {\n readonly current: CurrentGroup[\"current\"];\n readonly policy: CurrentGroup[\"policy\"];\n readonly checkpointPolicies: readonly CurrentGroup[\"policy\"][];\n readonly stillCurrent: () => boolean;\n}\n\n/** A share read need not be a group administrator; minting a grant checks that separately. */\nexport function createRuntimeCurrentSharePrincipalPolicy(\n runtime: CurrentShareRuntime,\n) {\n const lease = createCurrentPrincipalMutationLease(runtime.principalPolicies);\n if (!lease) return undefined;\n return async <T>(\n input: CurrentShareInput,\n work: (policy: CurrentSharePrincipalPolicy) => Promise<T>,\n ): Promise<T> => {\n input = {\n ...input,\n expectedGroupHead: input.expectedGroupHead\n ? { ...input.expectedGroupHead }\n : undefined,\n };\n return lease(\n input.stillCurrent,\n async ({ resolveCurrentPolicy, stillCurrent: leaseCurrent }) => {\n await runtime.apiClient.recoverPendingPrincipalMutation?.(\n input.organizationId,\n );\n assertProjectionVerificationCurrent(leaseCurrent);\n const authority = await loadCurrentOrganizationAuthority({\n execSql: runtime.infra.execSql,\n organizationId: input.organizationId,\n resolveCurrentPolicy,\n stillCurrent: leaseCurrent,\n });\n const group = await authority.readGroup(input.groupId);\n const stillCurrent = () =>\n leaseCurrent() && authority.stillCurrent() && group.stillCurrent();\n assertProjectionVerificationCurrent(stillCurrent);\n if (\n input.expectedGroupHead &&\n !principalHeadMatchesReference(\n group.policy.state,\n input.expectedGroupHead,\n )\n )\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Container share expected group head conflicts with the signed organization directory\",\n );\n assertGroupMetadataBinding(group.current, authority.descriptor);\n await assertCurrentShareName({\n runtime,\n input,\n authority,\n group,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const checkpointPolicies = [...group.dependencies, group.policy];\n await new KeyingCheckpointRepository(\n runtime.infra.execSql,\n ).advanceKeyingCheckpointsAtomically({\n access: [],\n organizationId: input.organizationId,\n policies: checkpointPolicies,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n const result = await work({\n current: group.current,\n policy: group.policy,\n checkpointPolicies,\n stillCurrent,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n return result;\n },\n );\n };\n}\n\nasync function assertCurrentShareName({\n runtime,\n input,\n authority,\n group,\n stillCurrent,\n}: {\n runtime: CurrentShareRuntime;\n input: CurrentShareInput;\n authority: Awaited<ReturnType<typeof loadCurrentOrganizationAuthority>>;\n group: CurrentGroup;\n stillCurrent: () => boolean;\n}) {\n if (input.expectedGroupName === undefined) return;\n const readName =\n input.readEncryptedName ??\n createRuntimeGroupMetadataAccess(\n runtime,\n input.organizationId,\n stillCurrent,\n createSelectedCurrentGroupMetadataContainerVerifier({\n authority,\n organizationId: input.organizationId,\n stillCurrent,\n }),\n ).readName;\n const mismatch = await groupPolicyNameMismatch(\n group.current,\n input.expectedGroupName,\n readName,\n );\n if (mismatch)\n throw new GroupShareNameMismatchError(\n mismatch === \"forbidden_characters\"\n ? \"Container share group name contains control or format characters\"\n : \"Container share group name does not match the signed group policy\",\n );\n}\n"]}
@@ -1,8 +1,6 @@
1
1
  import { nullOnProjectionVerificationCancellation, requireProjectionUserKeyResolver, } from "../../../data/keyingProjectionVerification/index.js";
2
2
  import { principalPolicyCacheForVerifiedPolicies } from "../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js";
3
- import { inheritPrincipalHistoryProtection } from "../../../data/principals/principalHistoryRuntime.js";
4
3
  import { buildMaterializedContainerSharePlan, resolveShareProjection, submitAcknowledgedContainerMutation, submitPlainContainerMutation, } from "../../containers/index.js";
5
- import { apiPrincipalPolicyPageReader, apiProjectionPolicyHistoryReader, } from "../../principals/principalPolicyHistoryReader.js";
6
4
  import { createRuntimeCurrentGroupMutation } from "../principalMutations/runtimeCurrentGroupMutation.js";
7
5
  import { commitCurrentShareGrant } from "./currentShareGrantMutation.js";
8
6
  import { createRuntimeCurrentSharePrincipalPolicy } from "./currentSharePrincipalPolicy.js";
@@ -11,21 +9,19 @@ import { shareWithGroupReplanningOnce } from "./groupShareReplan.js";
11
9
  export function createRuntimeCurrentGroupShare(runtime) {
12
10
  const readCurrent = createRuntimeCurrentSharePrincipalPolicy(runtime);
13
11
  const api = runtime.apiClient;
14
- const historyReader = apiPrincipalPolicyPageReader(api);
15
- if (!readCurrent || !historyReader)
12
+ if (!readCurrent)
16
13
  return undefined;
17
- const mutate = createRuntimeCurrentGroupMutation(inheritPrincipalHistoryProtection(runtime, {
14
+ // The derived runtime keeps this snapshot's policy service and its lease.
15
+ const mutate = createRuntimeCurrentGroupMutation({
18
16
  ...runtime,
19
17
  apiClient: {
20
- ...historyReader,
21
- ...apiProjectionPolicyHistoryReader(api),
22
18
  recoverPendingPrincipalMutation: async (organizationId) => {
23
19
  // Built-in clients supply journal recovery; standalone hosts retain
24
20
  // responsibility for transport and exact-outcome recovery.
25
21
  await api.recoverPendingPrincipalMutation?.(organizationId);
26
22
  },
27
23
  },
28
- }));
24
+ });
29
25
  if (!mutate)
30
26
  throw new Error("Current group mutation custody is unavailable");
31
27
  const shareOnce = async (input) => {