@tearleads/client-sdk 0.1.216 → 0.1.218

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (149) hide show
  1. package/client/containerContents/documentDiscovery.js +6 -4
  2. package/client/containerContents/documentDiscovery.js.map +1 -1
  3. package/client/containerContents/index.js +3 -4
  4. package/client/containerContents/index.js.map +1 -1
  5. package/client/deviceFirst/index.js +2 -2
  6. package/client/deviceFirst/index.js.map +1 -1
  7. package/client/documents/index.js +2 -2
  8. package/client/documents/index.js.map +1 -1
  9. package/client/organizations/organizationGroupHistory.js +1 -2
  10. package/client/organizations/organizationGroupHistory.js.map +1 -1
  11. package/client/organizations/organizationGroupNameHydration.js +1 -2
  12. package/client/organizations/organizationGroupNameHydration.js.map +1 -1
  13. package/client/organizations/organizationHistory.js +2 -4
  14. package/client/organizations/organizationHistory.js.map +1 -1
  15. package/client/organizations/principalContainerMutations.js +1 -2
  16. package/client/organizations/principalContainerMutations.js.map +1 -1
  17. package/client/organizations/principalMutations.js +1 -2
  18. package/client/organizations/principalMutations.js.map +1 -1
  19. package/client/organizations/rosterAdmissionEvidence.js +1 -2
  20. package/client/organizations/rosterAdmissionEvidence.js.map +1 -1
  21. package/client/runtime/workflowRuntime.d.ts +3 -2
  22. package/client/runtime/workflowRuntime.js +13 -3
  23. package/client/runtime/workflowRuntime.js.map +1 -1
  24. package/data/sync/organizationSyncPauses.d.ts +21 -10
  25. package/data/sync/organizationSyncPauses.js +73 -59
  26. package/data/sync/organizationSyncPauses.js.map +1 -1
  27. package/index.d.ts +1 -1
  28. package/index.js.map +1 -1
  29. package/package.json +1 -1
  30. package/stores/container-contents/syncAgent/syncLaneIteration.js.map +1 -1
  31. package/stores/documents/documentStore/attachments/attachmentHydration.js +3 -2
  32. package/stores/documents/documentStore/attachments/attachmentHydration.js.map +1 -1
  33. package/stores/documents/documentStore/initialization/index.js +2 -2
  34. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  35. package/stores/documents/documentStore/rotation/index.js +1 -2
  36. package/stores/documents/documentStore/rotation/index.js.map +1 -1
  37. package/stores/documents/documentStore/rotation/rotationSettlement.js +1 -1
  38. package/stores/documents/documentStore/rotation/rotationSettlement.js.map +1 -1
  39. package/stores/documents/documentStore/state.js.map +1 -1
  40. package/stores/documents/documentStore/sync/carriedFirstUpdate.js.map +1 -1
  41. package/stores/documents/documentStore/sync/index.js.map +1 -1
  42. package/stores/documents/documentStore/sync/syncAttachments.js +3 -2
  43. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  44. package/stores/documents/documentStore/sync/syncDetachedAttachments.js +3 -2
  45. package/stores/documents/documentStore/sync/syncDetachedAttachments.js.map +1 -1
  46. package/stores/documents/documentStore/sync/syncRequest.js +3 -2
  47. package/stores/documents/documentStore/sync/syncRequest.js.map +1 -1
  48. package/stores/documents/documentStore/sync/syncRevalidation.js.map +1 -1
  49. package/stores/documents/documentStore/sync/syncSeededCreate.js.map +1 -1
  50. package/stores/documents/documentStore/sync/syncShared.js +3 -2
  51. package/stores/documents/documentStore/sync/syncShared.js.map +1 -1
  52. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  53. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  54. package/workflows/container-contents/container-state/create/createWithMetadata.js +1 -2
  55. package/workflows/container-contents/container-state/create/createWithMetadata.js.map +1 -1
  56. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js +1 -2
  57. package/workflows/container-contents/container-state/create/createWithMetadataPlan.js.map +1 -1
  58. package/workflows/container-contents/container-state/move/moveIntentSync.js +1 -2
  59. package/workflows/container-contents/container-state/move/moveIntentSync.js.map +1 -1
  60. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -2
  61. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  62. package/workflows/container-contents/container-state/remote.js +3 -4
  63. package/workflows/container-contents/container-state/remote.js.map +1 -1
  64. package/workflows/container-contents/container-state/share/groupGrantVerification.js +1 -2
  65. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  66. package/workflows/container-contents/container-state/share/index.js +2 -3
  67. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  68. package/workflows/container-contents/container-state/types.js.map +1 -1
  69. package/workflows/container-contents/documentLinks/documentLinksMove.js +4 -2
  70. package/workflows/container-contents/documentLinks/documentLinksMove.js.map +1 -1
  71. package/workflows/container-contents/documentLinks/index.js +3 -2
  72. package/workflows/container-contents/documentLinks/index.js.map +1 -1
  73. package/workflows/container-contents/index.d.ts +1 -1
  74. package/workflows/container-contents/index.js +1 -1
  75. package/workflows/container-contents/index.js.map +1 -1
  76. package/workflows/container-contents/metadata/index.d.ts +1 -1
  77. package/workflows/container-contents/metadata/index.js.map +1 -1
  78. package/workflows/container-contents/metadata/metadataRemoteSync.d.ts +3 -3
  79. package/workflows/container-contents/metadata/metadataRemoteSync.js +3 -2
  80. package/workflows/container-contents/metadata/metadataRemoteSync.js.map +1 -1
  81. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -2
  82. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  83. package/workflows/container-contents/remoteHydration/index.js +1 -2
  84. package/workflows/container-contents/remoteHydration/index.js.map +1 -1
  85. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js +4 -2
  86. package/workflows/container-contents/remoteHydration/remoteContainers/remoteContainerPageHydration.js.map +1 -1
  87. package/workflows/container-contents/remoteHydration/types.d.ts +1 -1
  88. package/workflows/container-contents/remoteHydration/types.js.map +1 -1
  89. package/workflows/container-contents/runtime.d.ts +13 -2
  90. package/workflows/container-contents/runtime.js +33 -21
  91. package/workflows/container-contents/runtime.js.map +1 -1
  92. package/workflows/container-contents/syncLane.d.ts +1 -1
  93. package/workflows/container-contents/syncLane.js.map +1 -1
  94. package/workflows/container-contents/syncPause/documentRemoval.js +2 -2
  95. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
  96. package/workflows/container-contents/tombstones/documentPurge.d.ts +2 -3
  97. package/workflows/container-contents/tombstones/documentPurge.js +1 -2
  98. package/workflows/container-contents/tombstones/documentPurge.js.map +1 -1
  99. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js +3 -2
  100. package/workflows/container-contents/tombstones/documentTombstoneEvidence.js.map +1 -1
  101. package/workflows/documents/index.d.ts +1 -1
  102. package/workflows/documents/index.js +1 -1
  103. package/workflows/documents/index.js.map +1 -1
  104. package/workflows/documents/runtime.d.ts +12 -1
  105. package/workflows/documents/runtime.js +24 -16
  106. package/workflows/documents/runtime.js.map +1 -1
  107. package/workflows/documents/sync/syncLane.d.ts +1 -1
  108. package/workflows/documents/sync/syncLane.js.map +1 -1
  109. package/workflows/organizations/currentOrganizationAuthority.d.ts +1 -2
  110. package/workflows/organizations/currentOrganizationAuthority.js.map +1 -1
  111. package/workflows/organizations/groupMetadata/groupMetadataRuntime.d.ts +5 -4
  112. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js +2 -4
  113. package/workflows/organizations/groupMetadata/groupMetadataRuntime.js.map +1 -1
  114. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js +1 -2
  115. package/workflows/organizations/groupMetadata/runtimeGroupMetadataAuthority.js.map +1 -1
  116. package/workflows/organizations/groupPolicy/currentGroupPolicyMutationContext.js.map +1 -1
  117. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.d.ts +1 -2
  118. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js +2 -2
  119. package/workflows/organizations/groupShare/currentSharePrincipalPolicy.js.map +1 -1
  120. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js +4 -8
  121. package/workflows/organizations/groupShare/runtimeCurrentGroupShare.js.map +1 -1
  122. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js +2 -3
  123. package/workflows/organizations/memberships/leaveRequestMembersEvidence.js.map +1 -1
  124. package/workflows/organizations/principalMutations/currentOrganizationMutationRetention.js.map +1 -1
  125. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js +2 -2
  126. package/workflows/organizations/principalMutations/runtimeCurrentGroupMutation.js.map +1 -1
  127. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js +2 -2
  128. package/workflows/organizations/principalMutations/runtimeCurrentOrganizationMutation.js.map +1 -1
  129. package/workflows/principals/index.d.ts +1 -0
  130. package/workflows/principals/index.js.map +1 -1
  131. package/workflows/principals/principalPolicyService.d.ts +64 -0
  132. package/workflows/principals/principalPolicyService.js +117 -0
  133. package/workflows/principals/principalPolicyService.js.map +1 -0
  134. package/workflows/principals/runtimePolicyRecovery.d.ts +13 -10
  135. package/workflows/principals/runtimePolicyRecovery.js +9 -17
  136. package/workflows/principals/runtimePolicyRecovery.js.map +1 -1
  137. package/workflows/principals/runtimeProjectionPolicyRecovery.js +7 -8
  138. package/workflows/principals/runtimeProjectionPolicyRecovery.js.map +1 -1
  139. package/workflows/sync/index.d.ts +1 -1
  140. package/workflows/sync/index.js +1 -1
  141. package/workflows/sync/index.js.map +1 -1
  142. package/data/principals/principalHistoryRuntime.js +0 -12
  143. package/data/principals/principalHistoryRuntime.js.map +0 -1
  144. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.d.ts +0 -16
  145. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js +0 -39
  146. package/workflows/organizations/principalMutations/currentPrincipalMutationLease.js.map +0 -1
  147. package/workflows/principals/runtimePolicyWarmer.d.ts +0 -26
  148. package/workflows/principals/runtimePolicyWarmer.js +0 -48
  149. package/workflows/principals/runtimePolicyWarmer.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"groupGrantVerification.js","sourceRoot":"","sources":["groupGrantVerification.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,oCAAoC,EAAE,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,OAAO;YACpC,oBAAoB,EAClB,uCAAuC,CAAC,kBAAkB,CAAC;YAC7D,UAAU;YACV,cAAc,EAAE,KAAK,CAAC,wBAAwB;YAC9C,YAAY;YACZ,+BAA+B,EAAE,kCAAkC,CACjE,KAAK,CAAC,OAAO,CACd;SACF,CAAC,CAAC;QACH,OAAO,8BAA8B,CAAC;YACpC,WAAW,EAAE,KAAK,CAAC,WAAW;YAC9B,WAAW,EAAE,iCAAiC,CAAC,MAAM,CAAC;YACtD,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,UAAU;SACX,CAAC,CAAC;IACL,CAAC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuE;IAEvE,OAAO,CACL,CAAC,MAAM,wCAAwC,CAAC,GAAG,EAAE,CACnD,0CAA0C,CAAC,KAAK,CAAC,CAClD,CAAC,IAAI,KAAK,CACZ,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { referencedPrincipalHeadFromPolicy } from \"../../../containers\";\nimport { createRuntimeCurrentSharePrincipalPolicy } from \"../../../organizations/groupShare\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\ntype GroupGrantAccessLevel = \"read\" | \"write\" | \"admin\";\n\nfunction projectionHasCurrentGroupGrant(input: {\n accessLevel: GroupGrantAccessLevel;\n expectedContainerId: string;\n expectedOrganizationId: string;\n groupId: string;\n currentHead: ReferencedPrincipalHead;\n projection: NonNullable<\n Awaited<ReturnType<typeof loadContainerWriterProjectionForState>>\n >;\n}): boolean {\n const state = readContainerState(\n getTargetContainerContext(input.projection).manifest,\n );\n return (\n state.containerId === input.expectedContainerId &&\n state.organizationId === input.expectedOrganizationId &&\n state.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n ) &&\n state.referencedPrincipalHeads.some(\n (head) =>\n head.principalType === input.currentHead.principalType &&\n head.principalId === input.currentHead.principalId &&\n head.version === input.currentHead.version &&\n head.keyEpoch === input.currentHead.keyEpoch &&\n head.stateHash === input.currentHead.stateHash &&\n head.keyFingerprint === input.currentHead.keyFingerprint,\n )\n );\n}\n\nasync function containerStateHasCurrentGroupGrantInternal(input: {\n accessLevel: GroupGrantAccessLevel;\n containerState: ContainerState;\n expectedContainerId: string;\n expectedGroupHead: ReferencedPrincipalHead;\n expectedOrganizationId: string;\n groupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.stillCurrent?.() === false) return false;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (\n !projection ||\n input.stillCurrent?.() === false ||\n input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId ||\n input.containerState.container.id !== input.expectedContainerId ||\n input.containerState.container.organizationId !==\n input.expectedOrganizationId ||\n projection.containerId !== input.expectedContainerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n return false;\n }\n\n const readCurrent = createRuntimeCurrentSharePrincipalPolicy(input.runtime);\n if (!readCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n return readCurrent(\n {\n expectedGroupHead: input.expectedGroupHead,\n groupId: input.groupId,\n organizationId: input.expectedOrganizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n },\n async ({ checkpointPolicies, policy, stillCurrent }) => {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n principalPolicyCache:\n principalPolicyCacheForVerifiedPolicies(checkpointPolicies),\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n return projectionHasCurrentGroupGrant({\n accessLevel: input.accessLevel,\n currentHead: referencedPrincipalHeadFromPolicy(policy),\n expectedContainerId: input.expectedContainerId,\n expectedOrganizationId: input.expectedOrganizationId,\n groupId: input.groupId,\n projection,\n });\n },\n );\n}\n\nexport async function containerStateHasCurrentGroupGrant(\n input: Parameters<typeof containerStateHasCurrentGroupGrantInternal>[0],\n): Promise<boolean> {\n return (\n (await nullOnProjectionVerificationCancellation(() =>\n containerStateHasCurrentGroupGrantInternal(input),\n )) ?? false\n );\n}\n"]}
1
+ {"version":3,"file":"groupGrantVerification.js","sourceRoot":"","sources":["groupGrantVerification.ts"],"names":[],"mappings":"AACA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,oCAAoC,EAAE,MAAM,qEAAqE,CAAC;AAC3H,OAAO,EAAE,uCAAuC,EAAE,MAAM,oFAAoF,CAAC;AAC7I,OAAO,EAAE,iCAAiC,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAE,wCAAwC,EAAE,MAAM,mCAAmC,CAAC;AAG7F,OAAO,EAAE,qCAAqC,EAAE,MAAM,oBAAoB,C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EAAE,iCAAiC,CAAC,MAAM,CAAC;YACtD,mBAAmB,EAAE,KAAK,CAAC,mBAAmB;YAC9C,sBAAsB,EAAE,KAAK,CAAC,sBAAsB;YACpD,OAAO,EAAE,KAAK,CAAC,OAAO;YACtB,UAAU;SACX,CAAC,CAAC;IACL,CAAC,CACF,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,kCAAkC,CACtD,KAAuE;IAEvE,OAAO,CACL,CAAC,MAAM,wCAAwC,CAAC,GAAG,EAAE,CACnD,0CAA0C,CAAC,KAAK,CAAC,CAClD,CAAC,IAAI,KAAK,CACZ,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { ProjectionDependencyUnavailableError } from \"../../../../data/keyingProjectionVerification/dependencyUnavailable\";\nimport { principalPolicyCacheForVerifiedPolicies } from \"../../../../data/keyingProjectionVerification/principalPolicy/principalPolicyCache\";\nimport { referencedPrincipalHeadFromPolicy } from \"../../../containers\";\nimport { createRuntimeCurrentSharePrincipalPolicy } from \"../../../organizations/groupShare\";\n\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport type { ContainerWorkflowRuntime } from \"../types\";\n\ntype GroupGrantAccessLevel = \"read\" | \"write\" | \"admin\";\n\nfunction projectionHasCurrentGroupGrant(input: {\n accessLevel: GroupGrantAccessLevel;\n expectedContainerId: string;\n expectedOrganizationId: string;\n groupId: string;\n currentHead: ReferencedPrincipalHead;\n projection: NonNullable<\n Awaited<ReturnType<typeof loadContainerWriterProjectionForState>>\n >;\n}): boolean {\n const state = readContainerState(\n getTargetContainerContext(input.projection).manifest,\n );\n return (\n state.containerId === input.expectedContainerId &&\n state.organizationId === input.expectedOrganizationId &&\n state.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n ) &&\n state.referencedPrincipalHeads.some(\n (head) =>\n head.principalType === input.currentHead.principalType &&\n head.principalId === input.currentHead.principalId &&\n head.version === input.currentHead.version &&\n head.keyEpoch === input.currentHead.keyEpoch &&\n head.stateHash === input.currentHead.stateHash &&\n head.keyFingerprint === input.currentHead.keyFingerprint,\n )\n );\n}\n\nasync function containerStateHasCurrentGroupGrantInternal(input: {\n accessLevel: GroupGrantAccessLevel;\n containerState: ContainerState;\n expectedContainerId: string;\n expectedGroupHead: ReferencedPrincipalHead;\n expectedOrganizationId: string;\n groupId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<boolean> {\n if (input.stillCurrent?.() === false) return false;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (\n !projection ||\n input.stillCurrent?.() === false ||\n input.expectedGroupHead.principalType !== \"group\" ||\n input.expectedGroupHead.principalId !== input.groupId ||\n input.containerState.container.id !== input.expectedContainerId ||\n input.containerState.container.organizationId !==\n input.expectedOrganizationId ||\n projection.containerId !== input.expectedContainerId ||\n projection.organizationId !== input.expectedOrganizationId\n ) {\n return false;\n }\n\n const readCurrent = createRuntimeCurrentSharePrincipalPolicy(input.runtime);\n if (!readCurrent)\n throw new ProjectionDependencyUnavailableError(\n \"Group sharing requires private paged recovery\",\n );\n return readCurrent(\n {\n expectedGroupHead: input.expectedGroupHead,\n groupId: input.groupId,\n organizationId: input.expectedOrganizationId,\n stillCurrent: input.stillCurrent ?? (() => true),\n },\n async ({ checkpointPolicies, policy, stillCurrent }) => {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n principalPolicyCache:\n principalPolicyCacheForVerifiedPolicies(checkpointPolicies),\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n return projectionHasCurrentGroupGrant({\n accessLevel: input.accessLevel,\n currentHead: referencedPrincipalHeadFromPolicy(policy),\n expectedContainerId: input.expectedContainerId,\n expectedOrganizationId: input.expectedOrganizationId,\n groupId: input.groupId,\n projection,\n });\n },\n );\n}\n\nexport async function containerStateHasCurrentGroupGrant(\n input: Parameters<typeof containerStateHasCurrentGroupGrantInternal>[0],\n): Promise<boolean> {\n return (\n (await nullOnProjectionVerificationCancellation(() =>\n containerStateHasCurrentGroupGrantInternal(input),\n )) ?? false\n );\n}\n"]}
@@ -1,7 +1,6 @@
1
1
  import { getTargetContainerContext, readContainerState, } from "../../../../data/containers/shared/projection.js";
2
2
  import { unwrapContainerKekPath } from "../../../../data/documents/shared/projection/index.js";
3
3
  import { nullOnProjectionVerificationCancellation, verifyContainerWriterProjection, } from "../../../../data/keyingProjectionVerification/index.js";
4
- import { createRuntimePrincipalPolicyWarmer } from "../../../principals/runtimePolicyWarmer.js";
5
4
  import { projectionGeneration } from "../../projectionGeneration.js";
6
5
  import { loadContainerWriterProjectionForState } from "../projectionCache.js";
7
6
  import { shareRemoteContainer, shareRemoteContainerWithGroup } from "../remote.js";
@@ -115,7 +114,7 @@ async function prepareContainerStateGroupRewrapInternal(input) {
115
114
  projection,
116
115
  resolveUserKey: input.resolveProjectionUserKey,
117
116
  stillCurrent: input.stillCurrent,
118
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime),
117
+ warmReferencedPrincipalPolicies: input.runtime.principalPolicies.createWarmer(),
119
118
  });
120
119
  if (input.stillCurrent?.() === false)
121
120
  return null;
@@ -148,7 +147,7 @@ async function prepareContainerStateGroupRewrapInternal(input) {
148
147
  resolveProjectionUserKey: input.resolveProjectionUserKey,
149
148
  secretKey: targetSecretKey,
150
149
  stillCurrent: input.stillCurrent,
151
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime),
150
+ warmReferencedPrincipalPolicies: input.runtime.principalPolicies.createWarmer(),
152
151
  });
153
152
  if (input.stillCurrent?.() === false)
154
153
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAC;AAE7F,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,OAAO,EAAE,qCAAqC,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,MAAM,WAAW,CAAC;AAKhF,OAAO,EAAE,2BAA2B,EAAE,MAAM,mBAAmB,CAAC;AAChE,OAAO,EAEL,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,oBAAoB,CAAC;AAU5B,SAAS,4BAA4B,CACnC,UAA6C,EAC7C,GAAW;IAEX,MAAM,KAAK,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC;IAC3C,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC;AACtE,CAAC;AAED,gFAAgF;AAChF,iFAAiF;AACjF,8EAA8E;AAC9E,gFAAgF;AAChF,gFAAgF;AAChF,iFAAiF;AACjF,gFAAgF;AAChF,sEAAsE;AACtE,SAAS,iBAAiB,CAAC,KAI1B;IACC,MAAM,UAAU,GAAG,CAAC,KAAK,CAAC,wBAAwB,IAAI,EAAE,CAAC,CAAC,IAA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QAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;IAErE,OAAO,2BAA2B,CAAC;QACjC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,MAAM;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,0BAA0B;KAC3B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../../data/documents/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\nimport { createRuntimePrincipalPolicyWarmer } from \"../../../principals/runtimePolicyWarmer\";\nimport type { ContainerContentsPersistence } from \"../../containerPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport { shareRemoteContainer, shareRemoteContainerWithGroup } from \"../remote\";\nimport type {\n ContainerWorkflowRuntime,\n SharedContainerStateResult,\n} from \"../types\";\nimport { resolveCurrentGroupKeyEpoch } from \"./groupShareEpoch\";\nimport {\n type MatchingRemoteContainerGrant,\n persistDuplicateContainerShare,\n persistSharedContainerState,\n} from \"./sharePersistence\";\n\ntype ContainerShareSubjectType = \"group\" | \"user\";\ntype ContainerShareAccessLevel = \"read\" | \"write\" | \"admin\";\n\ninterface RemoteContainerShareContext {\n matchingGrant: MatchingRemoteContainerGrant | null;\n projection: ContainerWriterProjectionResponse;\n}\n\nfunction readOptionalProjectionString(\n projection: ContainerWriterProjectionResponse,\n key: string,\n): string | null {\n const value = Reflect.get(projection, key);\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n// A container's KEK is wrapped to a group's encapsulation key at a specific key\n// epoch, pinned into the manifest as a referenced principal head. When the group\n// rotates (org-admin add or any removal bumps the epoch and mints a fresh KEM\n// keypair), that wrap goes stale: members holding only the new epoch secret can\n// no longer unwrap it. A re-share to the same group at the same access level is\n// therefore NOT redundant when the pinned epoch trails the group's current head,\n// so it must not be deduped away. The current epoch comes from a network-fresh,\n// fully verified current policy guarded by durable local checkpoints.\nfunction groupGrantIsStale(input: {\n currentKeyEpoch: number;\n referencedPrincipalHeads: ReadonlyArray<ReferencedPrincipalStateResponse>;\n subjectId: string;\n}): boolean {\n const pinnedHead = (input.referencedPrincipalHeads ?? []).find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.subjectId,\n );\n if (!pinnedHead) {\n return true;\n }\n return pinnedHead.keyEpoch !== input.currentKeyEpoch;\n}\n\nfunction newGrantShareContext(\n input: {\n containerState: ContainerState;\n requireExistingGrant?: boolean | undefined;\n runtime: ContainerWorkflowRuntime;\n subjectId: string;\n subjectType: ContainerShareSubjectType;\n },\n projection: RemoteContainerShareContext[\"projection\"],\n): RemoteContainerShareContext | null {\n if (input.requireExistingGrant) {\n // Re-wrap-only callers must never mint a brand-new grant: the container's\n // system slot is server-supplied and could point at a container that does\n // not already grant this subject, so minting here would leak its contents.\n input.runtime.util.log(\n `Container contents: refused to create a new ${input.subjectType} grant for ${input.subjectId} on container ${input.containerState.container.id} because the re-share requires an existing grant`,\n );\n return null;\n }\n return { matchingGrant: null, projection };\n}\n\nasync function loadRemoteContainerShareContext(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n expectedGroupName?: string | undefined;\n forceExistingGrantRewrap?: boolean | undefined;\n requireExistingGrant?: boolean | undefined;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n subjectId: string;\n subjectType: ContainerShareSubjectType;\n}): Promise<RemoteContainerShareContext | null> {\n if (input.stillCurrent?.() === false) return null;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (!projection || input.stillCurrent?.() === false) {\n return null;\n }\n\n const target = getTargetContainerContext(projection);\n const remoteState = readContainerState(target.manifest);\n const hasMatchingGrant = remoteState.directGrants.some(\n (grant) =>\n grant.subjectType === input.subjectType &&\n grant.subjectId === input.subjectId &&\n grant.accessLevel === input.accessLevel,\n );\n if (!hasMatchingGrant) {\n return newGrantShareContext(input, projection);\n }\n\n if (\n input.subjectType === \"group\" &&\n input.requireExistingGrant &&\n input.forceExistingGrantRewrap\n ) {\n // The cheap epoch probe below reads an unverified response and cannot prove\n // that a security-critical re-wrap is current. Force the verified policy\n // load and a real same-level mutation; failures must reach the retry owner.\n input.runtime.util.log(\n `Container contents: re-sharing container ${input.containerState.container.id} with group ${input.subjectId} because an existing grant re-wrap is required`,\n );\n return { matchingGrant: null, projection };\n }\n\n if (input.subjectType === \"group\") {\n const pinnedHead = remoteState.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.subjectId,\n );\n const currentKeyEpoch = pinnedHead\n ? await resolveCurrentGroupKeyEpoch({\n expectedGroupName: input.expectedGroupName,\n groupId: input.subjectId,\n organizationId: remoteState.organizationId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n })\n : null;\n if (input.stillCurrent?.() === false) return null;\n if (\n !pinnedHead ||\n (currentKeyEpoch !== null &&\n groupGrantIsStale({\n currentKeyEpoch,\n referencedPrincipalHeads: remoteState.referencedPrincipalHeads,\n subjectId: input.subjectId,\n }))\n ) {\n input.runtime.util.log(\n `Container contents: re-sharing container ${input.containerState.container.id} with group ${input.subjectId} because its key epoch advanced past the pinned grant`,\n );\n return { matchingGrant: null, projection };\n }\n }\n\n return {\n matchingGrant: {\n accessEpoch: remoteState.epoch,\n accessStateHash: target.manifest.manifestHash,\n createdAt: readOptionalProjectionString(projection, \"createdAt\"),\n metadataDocumentId: remoteState.metadataDocumentId,\n referencedPrincipalHeads: remoteState.referencedPrincipalHeads,\n updatedAt: readOptionalProjectionString(projection, \"updatedAt\"),\n },\n projection,\n };\n}\n\nasync function prepareContainerStateGroupRewrapInternal(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n groupId: string;\n requireExistingGrant?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | { status: \"not-granted\" }\n | {\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n status: \"prepared\";\n }\n | null\n> {\n if (input.stillCurrent?.() === false) return null;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (!projection || input.stillCurrent?.() === false) {\n return null;\n }\n\n if (input.requireExistingGrant) {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (input.stillCurrent?.() === false) return null;\n const verifiedState = readContainerState(\n getTargetContainerContext(projection).manifest,\n );\n if (\n projection.containerId !== input.containerState.container.id ||\n projection.organizationId !==\n input.containerState.container.organizationId ||\n verifiedState.containerId !== input.containerState.container.id ||\n verifiedState.organizationId !==\n input.containerState.container.organizationId ||\n verifiedState.parentContainerId !==\n input.containerState.container.parentId\n ) {\n throw new Error(\n \"Prepared container group re-wrap target is inconsistent\",\n );\n }\n const hasGrant = verifiedState.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n );\n if (!hasGrant) {\n return { status: \"not-granted\" };\n }\n }\n\n const targetSecretKey =\n input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null;\n if (!targetSecretKey) {\n return null;\n }\n\n const target = getTargetContainerContext(projection);\n const keksByEpochId = await unwrapContainerKekPath({\n execSql: input.runtime.infra.execSql,\n projection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n secretKey: targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n ),\n });\n if (input.stillCurrent?.() === false) return null;\n const targetKek = keksByEpochId.get(target.kek.containerKeyEpochId);\n return targetKek\n ? {\n knownContainerKeks: new Map([\n [target.kek.containerKeyEpochId, targetKek],\n ]),\n status: \"prepared\",\n }\n : null;\n}\n\nexport function prepareContainerStateGroupRewrap(\n input: Parameters<typeof prepareContainerStateGroupRewrapInternal>[0],\n): ReturnType<typeof prepareContainerStateGroupRewrapInternal> {\n return nullOnProjectionVerificationCancellation(() =>\n prepareContainerStateGroupRewrapInternal(input),\n );\n}\n\nexport async function shareContainerState(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n persistence: ContainerContentsPersistence;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedContainerStateResult | null> {\n if (input.stillCurrent?.() === false) return null;\n // Before the projection load and the share request: a hint that lands during\n // either must keep the resulting projection out of the cache.\n const writerProjectionGeneration = projectionGeneration(input.containerState);\n const shareContext = await loadRemoteContainerShareContext({\n accessLevel: input.accessLevel,\n containerState: input.containerState,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n });\n if (!shareContext || input.stillCurrent?.() === false) {\n return null;\n }\n if (shareContext.matchingGrant) {\n input.runtime.util.log(\n `Container contents: skipped duplicate share for container ${input.containerState.container.id} with user ${input.recipientUserId}`,\n );\n return persistDuplicateContainerShare({\n containerState: input.containerState,\n grant: shareContext.matchingGrant,\n persistence: input.persistence,\n projection: shareContext.projection,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n }\n\n const shared = await shareRemoteContainer({\n accessLevel: input.accessLevel,\n containerId: input.containerState.container.id,\n previousProjection: shareContext.projection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n\n if (!shared) return null;\n if (input.stillCurrent?.() === false) return { status: \"confirmed\" };\n\n return persistSharedContainerState({\n containerState: input.containerState,\n persistence: input.persistence,\n runtime: input.runtime,\n shared,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n}\n\nexport async function shareContainerStateWithGroup(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistence: ContainerContentsPersistence;\n recipientGroupId: string;\n // When set, a re-share only re-wraps an already-granted group and never mints\n // a new grant. Used by organization access repair so a server cannot redirect\n // the operation onto a container the group is not entitled to. A prepared\n // re-wrap also supplies captured KEKs and must submit a real mutation.\n requireExistingGrant?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedContainerStateResult | null> {\n // A share chosen by name must carry that name so it can be bound to the\n // signed group policy. Only the grant-preserving re-wrap, which never mints\n // a grant, may run without one. Enforced here, in the workflow facade, so\n // every caller (not only the store) meets the invariant.\n if (!input.requireExistingGrant && input.expectedGroupName === undefined) {\n throw new Error(\"Container group share requires the chosen group name\");\n }\n if (input.stillCurrent?.() === false) return null;\n // Before the projection load and the share request: a hint that lands during\n // either must keep the resulting projection out of the cache.\n const writerProjectionGeneration = projectionGeneration(input.containerState);\n const shareContext = await loadRemoteContainerShareContext({\n accessLevel: input.accessLevel,\n containerState: input.containerState,\n expectedGroupName: input.expectedGroupName,\n forceExistingGrantRewrap:\n input.requireExistingGrant && input.knownContainerKeks !== undefined,\n requireExistingGrant: input.requireExistingGrant,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n });\n if (!shareContext || input.stillCurrent?.() === false) {\n return null;\n }\n if (shareContext.matchingGrant) {\n // A duplicate share mints nothing, but it must not report success for a\n // group the user did not choose. A matching grant is only found after the\n // key-epoch probe verified the group's policy with the chosen name bound,\n // so the name is already checked here.\n input.runtime.util.log(\n `Container contents: skipped duplicate share for container ${input.containerState.container.id} with group ${input.recipientGroupId}`,\n );\n return persistDuplicateContainerShare({\n containerState: input.containerState,\n grant: shareContext.matchingGrant,\n persistence: input.persistence,\n projection: shareContext.projection,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n }\n\n const shared = await shareRemoteContainerWithGroup({\n accessLevel: input.accessLevel,\n containerId: input.containerState.container.id,\n expectedGroupName: input.expectedGroupName,\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: shareContext.projection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n\n if (!shared) return null;\n if (input.stillCurrent?.() === false) return { status: \"confirmed\" };\n\n return persistSharedContainerState({\n containerState: input.containerState,\n persistence: input.persistence,\n runtime: input.runtime,\n shared,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,yBAAyB,EACzB,kBAAkB,GACnB,MAAM,+CAA+C,CAAC;AACvD,OAAO,EAAE,sBAAsB,EAAE,MAAM,8CAA8C,CAAC;AACtF,OAAO,EACL,wCAAwC,EAExC,+BAA+B,GAChC,MAAM,+CAA+C,CAAC;AAGvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AAElE,OAAO,EAAE,qCAAqC,EAAE,MAAM,oBAAoB,CAAC;AAC3E,OAAO,EAAE,oBAAoB,EAAE,6BAA6B,EAAE,MAAM,WAAW,CAAC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AAO,EAAE,KAAK,CAAC,OAAO;YACtB,YAAY,EAAE,KAAK,CAAC,YAAY;YAChC,0BAA0B;SAC3B,CAAC,CAAC;IACL,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,6BAA6B,CAAC;QACjD,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,WAAW,EAAE,KAAK,CAAC,cAAc,CAAC,SAAS,CAAC,EAAE;QAC9C,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,kBAAkB,EAAE,KAAK,CAAC,kBAAkB;QAC5C,kBAAkB,EAAE,YAAY,CAAC,UAAU;QAC3C,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;QACxC,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;QACxD,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,YAAY,EAAE,KAAK,CAAC,YAAY;KACjC,CAAC,CAAC;IAEH,IAAI,CAAC,MAAM;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,CAAC;IAErE,OAAO,2BAA2B,CAAC;QACjC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,MAAM;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,0BAA0B;KAC3B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type {\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport {\n getTargetContainerContext,\n readContainerState,\n} from \"../../../../data/containers/shared/projection\";\nimport { unwrapContainerKekPath } from \"../../../../data/documents/shared/projection\";\nimport {\n nullOnProjectionVerificationCancellation,\n type ProjectionUserKeyResolver,\n verifyContainerWriterProjection,\n} from \"../../../../data/keyingProjectionVerification\";\n\nimport type { ContainerContentsPersistence } from \"../../containerPersistence\";\nimport { projectionGeneration } from \"../../projectionGeneration\";\nimport type { ContainerState } from \"../../remoteHydration\";\nimport { loadContainerWriterProjectionForState } from \"../projectionCache\";\nimport { shareRemoteContainer, shareRemoteContainerWithGroup } from \"../remote\";\nimport type {\n ContainerWorkflowRuntime,\n SharedContainerStateResult,\n} from \"../types\";\nimport { resolveCurrentGroupKeyEpoch } from \"./groupShareEpoch\";\nimport {\n type MatchingRemoteContainerGrant,\n persistDuplicateContainerShare,\n persistSharedContainerState,\n} from \"./sharePersistence\";\n\ntype ContainerShareSubjectType = \"group\" | \"user\";\ntype ContainerShareAccessLevel = \"read\" | \"write\" | \"admin\";\n\ninterface RemoteContainerShareContext {\n matchingGrant: MatchingRemoteContainerGrant | null;\n projection: ContainerWriterProjectionResponse;\n}\n\nfunction readOptionalProjectionString(\n projection: ContainerWriterProjectionResponse,\n key: string,\n): string | null {\n const value = Reflect.get(projection, key);\n return typeof value === \"string\" && value.length > 0 ? value : null;\n}\n\n// A container's KEK is wrapped to a group's encapsulation key at a specific key\n// epoch, pinned into the manifest as a referenced principal head. When the group\n// rotates (org-admin add or any removal bumps the epoch and mints a fresh KEM\n// keypair), that wrap goes stale: members holding only the new epoch secret can\n// no longer unwrap it. A re-share to the same group at the same access level is\n// therefore NOT redundant when the pinned epoch trails the group's current head,\n// so it must not be deduped away. The current epoch comes from a network-fresh,\n// fully verified current policy guarded by durable local checkpoints.\nfunction groupGrantIsStale(input: {\n currentKeyEpoch: number;\n referencedPrincipalHeads: ReadonlyArray<ReferencedPrincipalStateResponse>;\n subjectId: string;\n}): boolean {\n const pinnedHead = (input.referencedPrincipalHeads ?? []).find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.subjectId,\n );\n if (!pinnedHead) {\n return true;\n }\n return pinnedHead.keyEpoch !== input.currentKeyEpoch;\n}\n\nfunction newGrantShareContext(\n input: {\n containerState: ContainerState;\n requireExistingGrant?: boolean | undefined;\n runtime: ContainerWorkflowRuntime;\n subjectId: string;\n subjectType: ContainerShareSubjectType;\n },\n projection: RemoteContainerShareContext[\"projection\"],\n): RemoteContainerShareContext | null {\n if (input.requireExistingGrant) {\n // Re-wrap-only callers must never mint a brand-new grant: the container's\n // system slot is server-supplied and could point at a container that does\n // not already grant this subject, so minting here would leak its contents.\n input.runtime.util.log(\n `Container contents: refused to create a new ${input.subjectType} grant for ${input.subjectId} on container ${input.containerState.container.id} because the re-share requires an existing grant`,\n );\n return null;\n }\n return { matchingGrant: null, projection };\n}\n\nasync function loadRemoteContainerShareContext(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n expectedGroupName?: string | undefined;\n forceExistingGrantRewrap?: boolean | undefined;\n requireExistingGrant?: boolean | undefined;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n subjectId: string;\n subjectType: ContainerShareSubjectType;\n}): Promise<RemoteContainerShareContext | null> {\n if (input.stillCurrent?.() === false) return null;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (!projection || input.stillCurrent?.() === false) {\n return null;\n }\n\n const target = getTargetContainerContext(projection);\n const remoteState = readContainerState(target.manifest);\n const hasMatchingGrant = remoteState.directGrants.some(\n (grant) =>\n grant.subjectType === input.subjectType &&\n grant.subjectId === input.subjectId &&\n grant.accessLevel === input.accessLevel,\n );\n if (!hasMatchingGrant) {\n return newGrantShareContext(input, projection);\n }\n\n if (\n input.subjectType === \"group\" &&\n input.requireExistingGrant &&\n input.forceExistingGrantRewrap\n ) {\n // The cheap epoch probe below reads an unverified response and cannot prove\n // that a security-critical re-wrap is current. Force the verified policy\n // load and a real same-level mutation; failures must reach the retry owner.\n input.runtime.util.log(\n `Container contents: re-sharing container ${input.containerState.container.id} with group ${input.subjectId} because an existing grant re-wrap is required`,\n );\n return { matchingGrant: null, projection };\n }\n\n if (input.subjectType === \"group\") {\n const pinnedHead = remoteState.referencedPrincipalHeads.find(\n (head) =>\n head.principalType === \"group\" && head.principalId === input.subjectId,\n );\n const currentKeyEpoch = pinnedHead\n ? await resolveCurrentGroupKeyEpoch({\n expectedGroupName: input.expectedGroupName,\n groupId: input.subjectId,\n organizationId: remoteState.organizationId,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n })\n : null;\n if (input.stillCurrent?.() === false) return null;\n if (\n !pinnedHead ||\n (currentKeyEpoch !== null &&\n groupGrantIsStale({\n currentKeyEpoch,\n referencedPrincipalHeads: remoteState.referencedPrincipalHeads,\n subjectId: input.subjectId,\n }))\n ) {\n input.runtime.util.log(\n `Container contents: re-sharing container ${input.containerState.container.id} with group ${input.subjectId} because its key epoch advanced past the pinned grant`,\n );\n return { matchingGrant: null, projection };\n }\n }\n\n return {\n matchingGrant: {\n accessEpoch: remoteState.epoch,\n accessStateHash: target.manifest.manifestHash,\n createdAt: readOptionalProjectionString(projection, \"createdAt\"),\n metadataDocumentId: remoteState.metadataDocumentId,\n referencedPrincipalHeads: remoteState.referencedPrincipalHeads,\n updatedAt: readOptionalProjectionString(projection, \"updatedAt\"),\n },\n projection,\n };\n}\n\nasync function prepareContainerStateGroupRewrapInternal(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n groupId: string;\n requireExistingGrant?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<\n | { status: \"not-granted\" }\n | {\n knownContainerKeks: ReadonlyMap<string, Uint8Array>;\n status: \"prepared\";\n }\n | null\n> {\n if (input.stillCurrent?.() === false) return null;\n const projection = await loadContainerWriterProjectionForState({\n containerState: input.containerState,\n runtime: input.runtime,\n });\n if (!projection || input.stillCurrent?.() === false) {\n return null;\n }\n\n if (input.requireExistingGrant) {\n await verifyContainerWriterProjection({\n execSql: input.runtime.infra.execSql,\n projection,\n resolveUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (input.stillCurrent?.() === false) return null;\n const verifiedState = readContainerState(\n getTargetContainerContext(projection).manifest,\n );\n if (\n projection.containerId !== input.containerState.container.id ||\n projection.organizationId !==\n input.containerState.container.organizationId ||\n verifiedState.containerId !== input.containerState.container.id ||\n verifiedState.organizationId !==\n input.containerState.container.organizationId ||\n verifiedState.parentContainerId !==\n input.containerState.container.parentId\n ) {\n throw new Error(\n \"Prepared container group re-wrap target is inconsistent\",\n );\n }\n const hasGrant = verifiedState.directGrants.some(\n (grant) =>\n grant.subjectType === \"group\" &&\n grant.subjectId === input.groupId &&\n grant.accessLevel === input.accessLevel,\n );\n if (!hasGrant) {\n return { status: \"not-granted\" };\n }\n }\n\n const targetSecretKey =\n input.runtime.crypto.encapsulationKeyPair?.secretKey ?? null;\n if (!targetSecretKey) {\n return null;\n }\n\n const target = getTargetContainerContext(projection);\n const keksByEpochId = await unwrapContainerKekPath({\n execSql: input.runtime.infra.execSql,\n projection,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n secretKey: targetSecretKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer(),\n });\n if (input.stillCurrent?.() === false) return null;\n const targetKek = keksByEpochId.get(target.kek.containerKeyEpochId);\n return targetKek\n ? {\n knownContainerKeks: new Map([\n [target.kek.containerKeyEpochId, targetKek],\n ]),\n status: \"prepared\",\n }\n : null;\n}\n\nexport function prepareContainerStateGroupRewrap(\n input: Parameters<typeof prepareContainerStateGroupRewrapInternal>[0],\n): ReturnType<typeof prepareContainerStateGroupRewrapInternal> {\n return nullOnProjectionVerificationCancellation(() =>\n prepareContainerStateGroupRewrapInternal(input),\n );\n}\n\nexport async function shareContainerState(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n persistence: ContainerContentsPersistence;\n recipientUserId: string;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedContainerStateResult | null> {\n if (input.stillCurrent?.() === false) return null;\n // Before the projection load and the share request: a hint that lands during\n // either must keep the resulting projection out of the cache.\n const writerProjectionGeneration = projectionGeneration(input.containerState);\n const shareContext = await loadRemoteContainerShareContext({\n accessLevel: input.accessLevel,\n containerState: input.containerState,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n subjectId: input.recipientUserId,\n subjectType: \"user\",\n });\n if (!shareContext || input.stillCurrent?.() === false) {\n return null;\n }\n if (shareContext.matchingGrant) {\n input.runtime.util.log(\n `Container contents: skipped duplicate share for container ${input.containerState.container.id} with user ${input.recipientUserId}`,\n );\n return persistDuplicateContainerShare({\n containerState: input.containerState,\n grant: shareContext.matchingGrant,\n persistence: input.persistence,\n projection: shareContext.projection,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n }\n\n const shared = await shareRemoteContainer({\n accessLevel: input.accessLevel,\n containerId: input.containerState.container.id,\n previousProjection: shareContext.projection,\n recipientUserId: input.recipientUserId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n\n if (!shared) return null;\n if (input.stillCurrent?.() === false) return { status: \"confirmed\" };\n\n return persistSharedContainerState({\n containerState: input.containerState,\n persistence: input.persistence,\n runtime: input.runtime,\n shared,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n}\n\nexport async function shareContainerStateWithGroup(input: {\n accessLevel: ContainerShareAccessLevel;\n containerState: ContainerState;\n expectedGroupName?: string | undefined;\n knownContainerKeks?: ReadonlyMap<string, Uint8Array> | undefined;\n persistence: ContainerContentsPersistence;\n recipientGroupId: string;\n // When set, a re-share only re-wraps an already-granted group and never mints\n // a new grant. Used by organization access repair so a server cannot redirect\n // the operation onto a container the group is not entitled to. A prepared\n // re-wrap also supplies captured KEKs and must submit a real mutation.\n requireExistingGrant?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n stillCurrent?: (() => boolean) | undefined;\n}): Promise<SharedContainerStateResult | null> {\n // A share chosen by name must carry that name so it can be bound to the\n // signed group policy. Only the grant-preserving re-wrap, which never mints\n // a grant, may run without one. Enforced here, in the workflow facade, so\n // every caller (not only the store) meets the invariant.\n if (!input.requireExistingGrant && input.expectedGroupName === undefined) {\n throw new Error(\"Container group share requires the chosen group name\");\n }\n if (input.stillCurrent?.() === false) return null;\n // Before the projection load and the share request: a hint that lands during\n // either must keep the resulting projection out of the cache.\n const writerProjectionGeneration = projectionGeneration(input.containerState);\n const shareContext = await loadRemoteContainerShareContext({\n accessLevel: input.accessLevel,\n containerState: input.containerState,\n expectedGroupName: input.expectedGroupName,\n forceExistingGrantRewrap:\n input.requireExistingGrant && input.knownContainerKeks !== undefined,\n requireExistingGrant: input.requireExistingGrant,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n subjectId: input.recipientGroupId,\n subjectType: \"group\",\n });\n if (!shareContext || input.stillCurrent?.() === false) {\n return null;\n }\n if (shareContext.matchingGrant) {\n // A duplicate share mints nothing, but it must not report success for a\n // group the user did not choose. A matching grant is only found after the\n // key-epoch probe verified the group's policy with the chosen name bound,\n // so the name is already checked here.\n input.runtime.util.log(\n `Container contents: skipped duplicate share for container ${input.containerState.container.id} with group ${input.recipientGroupId}`,\n );\n return persistDuplicateContainerShare({\n containerState: input.containerState,\n grant: shareContext.matchingGrant,\n persistence: input.persistence,\n projection: shareContext.projection,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n }\n\n const shared = await shareRemoteContainerWithGroup({\n accessLevel: input.accessLevel,\n containerId: input.containerState.container.id,\n expectedGroupName: input.expectedGroupName,\n knownContainerKeks: input.knownContainerKeks,\n previousProjection: shareContext.projection,\n recipientGroupId: input.recipientGroupId,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n runtime: input.runtime,\n stillCurrent: input.stillCurrent,\n });\n\n if (!shared) return null;\n if (input.stillCurrent?.() === false) return { status: \"confirmed\" };\n\n return persistSharedContainerState({\n containerState: input.containerState,\n persistence: input.persistence,\n runtime: input.runtime,\n shared,\n stillCurrent: input.stillCurrent,\n writerProjectionGeneration,\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerDeleteResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { DocumentRecord } from \"../../../data/persistence/documents/records\";\nimport type { ContainerMutationServiceApi } from \"../../containers\";\nimport type { createRemoteDocument } from \"../../documents\";\nimport type { shareRemoteContainerWithGroup } from \"../../organizations/groupShare\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerMoveIntentRecord,\n} from \"../containerPersistence\";\nimport type { createInitializedContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type {\n ContainerState,\n RemoteContainer as HydratedRemoteContainer,\n RemoteContainerHydrationHost,\n} from \"../remoteHydration/types\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerWorkflowApi = ContainerMutationServiceApi &\n Parameters<typeof shareRemoteContainerWithGroup>[0][\"apiClient\"] &\n Parameters<typeof createRemoteDocument>[0][\"apiClient\"] &\n Partial<PrincipalPolicyHistoryReader> &\n CurrentPrincipalPolicyReader & {\n deleteContainerResult(\n containerId: string,\n options?: {\n expectedPaymentRequiredOrganizationId?: string;\n reportErrors?: boolean;\n requiredAncestorId?: string | undefined;\n },\n ): Promise<\n | { data: ContainerDeleteResponse; ok: true }\n | {\n ok: false;\n report: () => void;\n status: number | null;\n }\n >;\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void;\n };\n\nexport interface ContainerWorkflowRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n readonly apiClient: ContainerWorkflowApi;\n}\n\nexport interface CreatedRemoteContainerState {\n accessManifestHash: string;\n /**\n * The metadata seed the create committed, settled by the caller instead of\n * a first metadata sync. Absent when the create carried no seed or fell back\n * to a plain create.\n */\n metadataSeed?:\n | { readonly commitLsn: string | null; readonly updateId: string }\n | undefined;\n /** The slot this client signed into the create; never the server's echo. */\n systemSlot: ContainerSystemSlot | null;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n organizationId: string;\n /** A created container is a child; the acknowledgement echoed this parent. */\n parentId: string;\n persistedMetadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n updatedAt: string;\n}\n\nexport interface SharedRemoteContainerState {\n accessEpoch: number;\n accessManifestHash: string;\n createdAt: string;\n metadataDocumentId: string;\n referencedPrincipalHeads: ReferencedPrincipalStateResponse[];\n updatedAt: string;\n writerProjection: ContainerWriterProjectionResponse | null;\n}\n\nexport interface SharedContainerState {\n container: ContainerState[\"container\"];\n record: ContainerState[\"record\"];\n}\n\nexport type SharedContainerStateResult =\n | { status: \"missing\" }\n | { status: \"confirmed\" }\n | (SharedContainerState & {\n status: \"identity-superseded\" | \"persisted\";\n });\n\nexport type RemoteContainer = HydratedRemoteContainer;\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createInitializedContainerMetadataDocument>\n>[\"doc\"];\n\nexport interface CreatedChildContainerState {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n shouldRequestSync: boolean;\n}\n\nexport interface ContainerIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n /**\n * Metadata update ids this device sent, so their own update echoes are\n * classified as self-authored (shared with the metadata sync).\n */\n locallyAcceptedMetadataUpdateIds?: Set<string> | undefined;\n /** Metadata document ids of folder creates in flight (shared with hints). */\n plannedMetadataDocumentIds?: Set<string> | undefined;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n /**\n * Verifies that a listed container is this device's pending create before it\n * is adopted and returns where it sits; `assertContainerCreateAdoptable`\n * unless a test replaces it.\n */\n verifyCreateAdoption?: (input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n }) => Promise<AdoptedContainerPlacement>;\n}\n\n/** Where a verified listed create committed, and where its container is now. */\nexport interface AdoptedContainerPlacement {\n /** The parent its signed epoch-1 `container.create` named. */\n readonly createdParentId: string;\n /** The verified head's parent; another writer may have moved it since. */\n readonly currentParentId: string;\n}\n\nexport type ContainerCreateIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerCreateIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\"\n>;\n\nexport interface ContainerCreateIntentSyncInput {\n host: ContainerCreateIntentSyncHost;\n /** A parent whose own create has not settled takes no child create. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerCreateIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerCreateIntentSyncState;\n}\n\nexport type ContainerMoveIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerMoveIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\" | \"updateSnapshot\"\n>;\n\n/** Later passes for moves the server accepted but no pass settled. */\nexport interface AcceptedMoveRetry {\n /** The server holds the move: schedule a replay to settle it. */\n arm: (intentId: string) => void;\n /** A replay failed; continue an accepted move's retries, if it has some. */\n resume: (intentId: string) => void;\n}\n\nexport interface ContainerMoveIntentSyncInput {\n host: ContainerMoveIntentSyncHost;\n isCurrent: () => boolean;\n /** A folder whose create has not settled takes no structural writes. */\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerMoveIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n acceptedMoveRetry: AcceptedMoveRetry;\n state: ContainerMoveIntentSyncState;\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"","sourcesContent":["import type { ContainerSystemSlot } from \"@tearleads/validators/containerSystemSlot\";\nimport type {\n ContainerDeleteResponse,\n ContainerWriterProjectionResponse,\n ReferencedPrincipalStateResponse,\n} from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { DocumentRecord } from \"../../../data/persistence/documents/records\";\nimport type { ContainerMutationServiceApi } from \"../../containers\";\nimport type { createRemoteDocument } from \"../../documents\";\nimport type { shareRemoteContainerWithGroup } from \"../../organizations/groupShare\";\nimport type { CurrentPrincipalPolicyReader } from \"../../principals/currentPrincipalPolicyReader\";\nimport type { PrincipalPolicyHistoryReader } from \"../../principals/principalPolicyHistoryReader\";\nimport type {\n ContainerContentsPersistence,\n ContainerCreateIntentRecord,\n ContainerMoveIntentRecord,\n} from \"../containerPersistence\";\nimport type { createInitializedContainerMetadataDocument } from \"../metadata/containerMetadataDocument\";\nimport type {\n ContainerState,\n RemoteContainer as HydratedRemoteContainer,\n RemoteContainerHydrationHost,\n} from \"../remoteHydration/types\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerWorkflowApi = ContainerMutationServiceApi &\n Parameters<typeof shareRemoteContainerWithGroup>[0][\"apiClient\"] &\n Parameters<typeof createRemoteDocument>[0][\"apiClient\"] &\n Partial<PrincipalPolicyHistoryReader> &\n CurrentPrincipalPolicyReader & {\n deleteContainerResult(\n containerId: string,\n options?: {\n expectedPaymentRequiredOrganizationId?: string;\n reportErrors?: boolean;\n requiredAncestorId?: string | undefined;\n },\n ): Promise<\n | { data: ContainerDeleteResponse; ok: true }\n | {\n ok: false;\n report: () => void;\n status: number | null;\n }\n >;\n primeContainerWriterProjection(\n containerId: string,\n projection: ContainerWriterProjectionResponse,\n ): void;\n };\n\nexport interface ContainerWorkflowRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n readonly apiClient: ContainerWorkflowApi;\n}\n\nexport interface CreatedRemoteContainerState {\n accessManifestHash: string;\n /**\n * The metadata seed the create committed, settled by the caller instead of\n * a first metadata sync. Absent when the create carried no seed or fell back\n * to a plain create.\n */\n metadataSeed?:\n | { readonly commitLsn: string | null; readonly updateId: string }\n | undefined;\n /** The slot this client signed into the create; never the server's echo. */\n systemSlot: ContainerSystemSlot | null;\n containerId: string;\n createdAt: string;\n metadataDocumentId: string;\n organizationId: string;\n /** A created container is a child; the acknowledgement echoed this parent. */\n parentId: string;\n persistedMetadataState: Pick<\n DocumentRecord,\n | \"documentId\"\n | \"contentKeyBundle\"\n | \"documentKekTargets\"\n | \"documentManifestBundle\"\n >;\n updatedAt: string;\n}\n\nexport interface SharedRemoteContainerState {\n accessEpoch: number;\n accessManifestHash: string;\n createdAt: string;\n metadataDocumentId: string;\n referencedPrincipalHeads: ReferencedPrincipalStateResponse[];\n updatedAt: string;\n writerProjection: ContainerWriterProjectionResponse | null;\n}\n\nexport interface SharedContainerState {\n container: ContainerState[\"container\"];\n record: ContainerState[\"record\"];\n}\n\nexport type SharedContainerStateResult =\n | { status: \"missing\" }\n | { status: \"confirmed\" }\n | (SharedContainerState & {\n status: \"identity-superseded\" | \"persisted\";\n });\n\nexport type RemoteContainer = HydratedRemoteContainer;\n\nexport type ContainerMetadataDocumentState = Awaited<\n ReturnType<typeof createInitializedContainerMetadataDocument>\n>[\"doc\"];\n\nexport interface CreatedChildContainerState {\n containerState: ContainerState;\n initialUpdate: Uint8Array;\n shouldRequestSync: boolean;\n}\n\nexport interface ContainerIntentSyncState {\n containersById: ReadonlyMap<string, ContainerState>;\n /**\n * Metadata update ids this device sent, so their own update echoes are\n * classified as self-authored (shared with the metadata sync).\n */\n locallyAcceptedMetadataUpdateIds?: Set<string> | undefined;\n /** Metadata document ids of folder creates in flight (shared with hints). */\n plannedMetadataDocumentIds?: Set<string> | undefined;\n persistence: ContainerContentsPersistence;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerWorkflowRuntime;\n /**\n * Verifies that a listed container is this device's pending create before it\n * is adopted and returns where it sits; `assertContainerCreateAdoptable`\n * unless a test replaces it.\n */\n verifyCreateAdoption?: (input: {\n readonly containerId: string;\n readonly expectedOrganizationId: string;\n }) => Promise<AdoptedContainerPlacement>;\n}\n\n/** Where a verified listed create committed, and where its container is now. */\nexport interface AdoptedContainerPlacement {\n /** The parent its signed epoch-1 `container.create` named. */\n readonly createdParentId: string;\n /** The verified head's parent; another writer may have moved it since. */\n readonly currentParentId: string;\n}\n\nexport type ContainerCreateIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerCreateIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\"\n>;\n\nexport interface ContainerCreateIntentSyncInput {\n host: ContainerCreateIntentSyncHost;\n /** A parent whose own create has not settled takes no child create. */\n isCreatePending: (containerId: string) => boolean;\n isCurrent: () => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerCreateIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n state: ContainerCreateIntentSyncState;\n}\n\nexport type ContainerMoveIntentSyncState = ContainerIntentSyncState;\n\nexport type ContainerMoveIntentSyncHost = Pick<\n RemoteContainerHydrationHost,\n \"persistContainerState\" | \"updateSnapshot\"\n>;\n\n/** Later passes for moves the server accepted but no pass settled. */\nexport interface AcceptedMoveRetry {\n /** The server holds the move: schedule a replay to settle it. */\n arm: (intentId: string) => void;\n /** A replay failed; continue an accepted move's retries, if it has some. */\n resume: (intentId: string) => void;\n}\n\nexport interface ContainerMoveIntentSyncInput {\n host: ContainerMoveIntentSyncHost;\n isCurrent: () => boolean;\n /** A folder whose create has not settled takes no structural writes. */\n isCreatePending: (containerId: string) => boolean;\n isRemoteSyncBlocked: (organizationId: string) => boolean;\n intent: ContainerMoveIntentRecord;\n requestRemoteReconciliation: (parentContainerId: string | null) => void;\n acceptedMoveRetry: AcceptedMoveRetry;\n state: ContainerMoveIntentSyncState;\n}\n"]}
@@ -1,7 +1,7 @@
1
1
  import { assertDocumentWriterProjectionConsistent, readLinkedContainerIdsFromDocumentManifest, } from "../../../data/documents/shared/projection/index.js";
2
2
  import { persistedDocumentCreateStateFromWriterProjection } from "../../../data/documents/shared/responses.js";
3
3
  import { createLinkSetAttachmentReuse, } from "../../documents/index.js";
4
- import { createPrincipalPolicyOperation, createRuntimePrincipalPolicyWarmer, } from "../../principals/runtimePolicyWarmer.js";
4
+ import { createPrincipalPolicyOperation, } from "../../principals/principalPolicyService.js";
5
5
  import { resolveContainerDocumentMoveUnlinkIds } from "../documentMove/documentMoveUnlinkIds.js";
6
6
  import { relinkRemoteContainerDocument, unlinkRemoteContainerDocument, } from "./index.js";
7
7
  // A cold-cache denial must keep its HTTP status: collapsing a 403 to null
@@ -39,7 +39,9 @@ async function containerDocumentAlreadyMovedResult(input) {
39
39
  execSql: input.runtime.infra.execSql,
40
40
  resolveProjectionUserKey: input.resolveProjectionUserKey,
41
41
  stillCurrent: input.isCurrent,
42
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(input.runtime, { operation: input.policyOperation }),
42
+ warmReferencedPrincipalPolicies: input.runtime.principalPolicies.createWarmer({
43
+ operation: input.policyOperation,
44
+ }),
43
45
  onVerifiedAuthorization: (authorization) => {
44
46
  verified.head = authorization.documentManifestByHash.get(input.writerProjection.documentManifest.manifestHash);
45
47
  },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,CAAC,CAAC;QACH,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QAC/C,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtB,wBAAwB,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;YACjD,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,4BAA4B,MAAM,kBAAkB,iBAAiB,8BAA8B,iBAAiB,EAAE,CACvH,CAAC;YACF,SAAS;QACX,CAAC;QAED,cAAc,GAAG,gBAAgB,CAAC;QAClC,wBAAwB,GAAG,gBAAgB,CAAC,kBAAkB,CAAC;IACjE,CAAC;IACD,OAAO,EAAE,wBAAwB,EAAE,cAAc,EAAE,wBAAwB,EAAE,CAAC;AAChF,CAAC","sourcesContent":["import type { VerifiedDocumentLinkSetManifest } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentWriterProjectionConsistent,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"../../../data/documents/shared/projection\";\nimport { persistedDocumentCreateStateFromWriterProjection } from \"../../../data/documents/shared/responses\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport {\n createLinkSetAttachmentReuse,\n type DocumentLinkSetFailureHandler,\n type LinkSetAttachmentReuse,\n type RelinkRemoteDocumentResult,\n} from \"../../documents\";\nimport {\n createPrincipalPolicyOperation,\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../principals/runtimePolicyWarmer\";\nimport { resolveContainerDocumentMoveUnlinkIds } from \"../documentMove/documentMoveUnlinkIds\";\nimport {\n type ContainerDocumentLinkApi,\n type ContainerDocumentLinkRuntime,\n type RemoteDocumentPersistedState,\n relinkRemoteContainerDocument,\n unlinkRemoteContainerDocument,\n} from \"./index\";\n\n// A cold-cache denial must keep its HTTP status: collapsing a 403 to null\n// would leave an access-denied move routinely retriable instead of parking\n// it for the access-restored signal (row 7).\nasync function fetchMoveWriterProjection(input: {\n documentId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n runtime: ContainerDocumentLinkRuntime;\n}): Promise<Awaited<\n ReturnType<ContainerDocumentLinkApi[\"getDocumentWriterProjection\"]>\n> | null> {\n const { apiClient } = input.runtime;\n const result = await apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (result.ok) {\n return result.data;\n }\n result.report();\n input.onFailure?.({ message: result.message, status: result.status });\n return null;\n}\n\ntype MoveRemoteContainerDocumentStatus = \"complete\" | \"partial\";\n\ninterface MoveRemoteContainerDocumentResult {\n accessEpoch: number | null;\n accessStateHash: string | null;\n linkedContainerIds: readonly string[];\n nextContainerId: string;\n remoteState: RemoteDocumentPersistedState | null;\n status: MoveRemoteContainerDocumentStatus;\n}\n\nfunction resolveActiveDocumentContainerId(\n linkedContainerIds: ReadonlyArray<string>,\n preferredContainerId: string,\n): string | null {\n if (linkedContainerIds.includes(preferredContainerId)) {\n return preferredContainerId;\n }\n\n return linkedContainerIds[0] ?? null;\n}\n\nfunction containerDocumentMoveResult(input: {\n document: RelinkRemoteDocumentResult;\n nextContainerId: string;\n status: MoveRemoteContainerDocumentStatus;\n}): MoveRemoteContainerDocumentResult {\n return {\n accessEpoch: input.document.plan.state.epoch,\n accessStateHash: input.document.response.manifestHash,\n linkedContainerIds: input.document.linkedContainerIds,\n nextContainerId: input.nextContainerId,\n remoteState: input.document.persistedState,\n status: input.status,\n };\n}\n\nasync function containerDocumentAlreadyMovedResult(input: {\n writerProjection: DocumentWriterProjectionResponse;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentLinkRuntime;\n isCurrent?: (() => boolean) | undefined;\n linkedContainerIds: readonly string[];\n nextContainerId: string;\n policyOperation: PrincipalPolicyOperation;\n status: MoveRemoteContainerDocumentStatus;\n}): Promise<MoveRemoteContainerDocumentResult> {\n const verified: { head?: VerifiedDocumentLinkSetManifest | undefined } = {};\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n execSql: input.runtime.infra.execSql,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.isCurrent,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n input.runtime,\n { operation: input.policyOperation },\n ),\n onVerifiedAuthorization: (authorization) => {\n verified.head = authorization.documentManifestByHash.get(\n input.writerProjection.documentManifest.manifestHash,\n );\n },\n });\n if (!verified.head)\n throw new Error(\"Move replay lacks a verified document head\");\n return {\n accessEpoch: verified.head.state.epoch,\n accessStateHash: verified.head.manifestHash,\n linkedContainerIds: input.linkedContainerIds,\n nextContainerId: input.nextContainerId,\n remoteState: persistedDocumentCreateStateFromWriterProjection(\n input.writerProjection,\n ),\n status: input.status,\n };\n}\n\nasync function linkRemoteContainerDocument(input: {\n attachmentReuse: LinkSetAttachmentReuse;\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"link\",\n });\n}\n\n/** The move target (unless link-only) and any extra links, each once. */\nfunction moveLinkTargets(input: {\n readonly additionalLinkContainerIds?: readonly string[] | undefined;\n readonly linkOnly?: boolean | undefined;\n readonly targetContainerId: string;\n}): Set<string> {\n return new Set([\n ...(input.linkOnly ? [] : [input.targetContainerId]),\n ...(input.additionalLinkContainerIds ?? []),\n ]);\n}\n\nexport async function moveRemoteContainerDocument(input: {\n linkOnly?: boolean | undefined;\n additionalLinkContainerIds?: readonly string[] | undefined;\n removedLinkContainerIds?: readonly string[] | undefined;\n currentContainerId: string;\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n replaceLinkedContainers?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<MoveRemoteContainerDocumentResult | null> {\n const {\n documentId,\n noteId,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n if (input.isCurrent?.() === false) return null;\n // One move workflow is one policy operation: its link and unlink legs share\n // a directory discovery. Each leg's commit still refuses a stale view. Its\n // legs also list the document's attachments once (see `attachmentReuse`).\n const policyOperation = createPrincipalPolicyOperation();\n const attachmentReuse = createLinkSetAttachmentReuse();\n const writerProjection = await fetchMoveWriterProjection({\n documentId,\n onFailure: input.onFailure,\n runtime,\n });\n if (!writerProjection || input.isCurrent?.() === false) {\n return null;\n }\n if (writerProjection.documentId !== documentId)\n throw new Error(\"Move replay document id mismatch\");\n const initialLinkedContainerIds =\n readLinkedContainerIdsFromDocumentManifest(writerProjection);\n\n let latestLinkedContainerIds: readonly string[] = initialLinkedContainerIds;\n let latestDocument: RelinkRemoteDocumentResult | null = null;\n for (const linkTarget of moveLinkTargets(input)) {\n if (latestLinkedContainerIds.includes(linkTarget)) continue;\n const linkedDocument = await linkRemoteContainerDocument({\n attachmentReuse,\n documentId,\n isCurrent: input.isCurrent,\n noteId,\n onFailure: input.onFailure,\n policyOperation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId: linkTarget,\n });\n if (!linkedDocument || input.isCurrent?.() === false) {\n return null;\n }\n\n latestDocument = linkedDocument;\n latestLinkedContainerIds = linkedDocument.linkedContainerIds;\n }\n\n const unlinkContainerIds = resolveContainerDocumentMoveUnlinkIds({\n ...input,\n linkedContainerIds: latestLinkedContainerIds,\n });\n\n const unlinked = await unlinkMovedDocumentSources({\n ...input,\n attachmentReuse,\n latestDocument,\n latestLinkedContainerIds,\n policyOperation,\n unlinkContainerIds,\n });\n if (!unlinked) return null;\n latestDocument = unlinked.latestDocument;\n latestLinkedContainerIds = unlinked.latestLinkedContainerIds;\n\n const nextContainerId = resolveActiveDocumentContainerId(\n latestLinkedContainerIds,\n targetContainerId,\n );\n if (!nextContainerId) {\n return null;\n }\n\n const status =\n unlinked.failedUnlinkContainerIds.length > 0 ? \"partial\" : \"complete\";\n return latestDocument\n ? containerDocumentMoveResult({\n document: latestDocument,\n nextContainerId,\n status,\n })\n : containerDocumentAlreadyMovedResult({\n writerProjection,\n resolveProjectionUserKey,\n runtime,\n isCurrent: input.isCurrent,\n linkedContainerIds: latestLinkedContainerIds,\n nextContainerId,\n policyOperation,\n status,\n });\n}\n\n// The unlink half of a move: every source is attempted even when an earlier\n// one fails, so one dead source cannot strand the others; a failed unlink\n// leaves the move \"partial\" for the queue to retry.\nasync function unlinkMovedDocumentSources(input: {\n attachmentReuse: LinkSetAttachmentReuse;\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n latestDocument: RelinkRemoteDocumentResult | null;\n latestLinkedContainerIds: readonly string[];\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n unlinkContainerIds: readonly string[];\n}): Promise<{\n failedUnlinkContainerIds: readonly string[];\n latestDocument: RelinkRemoteDocumentResult | null;\n latestLinkedContainerIds: readonly string[];\n} | null> {\n const { noteId, runtime, targetContainerId } = input;\n let { latestDocument, latestLinkedContainerIds } = input;\n const failedUnlinkContainerIds: string[] = [];\n for (const unlinkContainerId of input.unlinkContainerIds) {\n if (input.isCurrent?.() === false) return null;\n const unlinkedDocument = await unlinkRemoteContainerDocument({\n attachmentReuse: input.attachmentReuse,\n documentId: input.documentId,\n isCurrent: input.isCurrent,\n noteId,\n onFailure: input.onFailure,\n policyOperation: input.policyOperation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n runtime,\n targetContainerId: unlinkContainerId,\n });\n if (input.isCurrent?.() === false) return null;\n if (!unlinkedDocument) {\n failedUnlinkContainerIds.push(unlinkContainerId);\n runtime.util.log(\n `Container contents: note ${noteId} was linked to ${targetContainerId} but failed to unlink from ${unlinkContainerId}`,\n );\n continue;\n }\n\n latestDocument = unlinkedDocument;\n latestLinkedContainerIds = unlinkedDocument.linkedContainerIds;\n }\n return { failedUnlinkContainerIds, latestDocument, latestLinkedContainerIds };\n}\n"]}
1
+ {"version":3,"file":"documentLinksMove.js","sourceRoot":"","sources":["documentLinksMove.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,wCAAwC,EACxC,0CAA0C,GAC3C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAAE,gDAAgD,EAAE,MAAM,0CAA0C,CAAC;AAE5G,OAAO,EACL,4BAA4B,GAI7B,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,8BAA8B,GAE/B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAAE,qCAAqC,EAAE,MAAM,uCAAuC,CAAC;AAC9F,OAAO,EAIL,6BAA6B,EAC7B,6BAA6B,GAC9B,MAAM,SAAS,CAAC;AAEjB,0EAA0E;AAC1E,2EAA2E;AAC3E,6CAA6C;AAC7C,KAAK,UAAU,yBAAyB,CAAC,KAIxC;IAGC,MAAM,EAAE,SAAS,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC;IACpC,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,iCAAiC,CAC9D,KAAK,CAAC,UAAU,EAChB,EAAE,YAAY,EAAE,KAAK,EAAE,CACxB,CAAC;IACF,IAAI,MAAM,CAAC,EAAE,EAAE,CAAC;QACd,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;IACD,MAAM,CAAC,MAAM,EAAE,CAAC;IAChB,KAAK,CAAC,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC;IACtE,OAAO,IAAI,CAAC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AU;YAC5B,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,MAAM;YACN,SAAS,EAAE,KAAK,CAAC,SAAS;YAC1B,eAAe,EAAE,KAAK,CAAC,eAAe;YACtC,wBAAwB,EAAE,KAAK,CAAC,wBAAwB;YACxD,gBAAgB,EAAE,KAAK,CAAC,gBAAgB;YACxC,OAAO;YACP,iBAAiB,EAAE,iBAAiB;SACrC,CAAC,CAAC;QACH,IAAI,KAAK,CAAC,SAAS,EAAE,EAAE,KAAK,KAAK;YAAE,OAAO,IAAI,CAAC;QAC/C,IAAI,CAAC,gBAAgB,EAAE,CAAC;YACtB,wBAAwB,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;YACjD,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,4BAA4B,MAAM,kBAAkB,iBAAiB,8BAA8B,iBAAiB,EAAE,CACvH,CAAC;YACF,SAAS;QACX,CAAC;QAED,cAAc,GAAG,gBAAgB,CAAC;QAClC,wBAAwB,GAAG,gBAAgB,CAAC,kBAAkB,CAAC;IACjE,CAAC;IACD,OAAO,EAAE,wBAAwB,EAAE,cAAc,EAAE,wBAAwB,EAAE,CAAC;AAChF,CAAC","sourcesContent":["import type { VerifiedDocumentLinkSetManifest } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n assertDocumentWriterProjectionConsistent,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"../../../data/documents/shared/projection\";\nimport { persistedDocumentCreateStateFromWriterProjection } from \"../../../data/documents/shared/responses\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport {\n createLinkSetAttachmentReuse,\n type DocumentLinkSetFailureHandler,\n type LinkSetAttachmentReuse,\n type RelinkRemoteDocumentResult,\n} from \"../../documents\";\nimport {\n createPrincipalPolicyOperation,\n type PrincipalPolicyOperation,\n} from \"../../principals/principalPolicyService\";\nimport { resolveContainerDocumentMoveUnlinkIds } from \"../documentMove/documentMoveUnlinkIds\";\nimport {\n type ContainerDocumentLinkApi,\n type ContainerDocumentLinkRuntime,\n type RemoteDocumentPersistedState,\n relinkRemoteContainerDocument,\n unlinkRemoteContainerDocument,\n} from \"./index\";\n\n// A cold-cache denial must keep its HTTP status: collapsing a 403 to null\n// would leave an access-denied move routinely retriable instead of parking\n// it for the access-restored signal (row 7).\nasync function fetchMoveWriterProjection(input: {\n documentId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n runtime: ContainerDocumentLinkRuntime;\n}): Promise<Awaited<\n ReturnType<ContainerDocumentLinkApi[\"getDocumentWriterProjection\"]>\n> | null> {\n const { apiClient } = input.runtime;\n const result = await apiClient.getDocumentWriterProjectionResult(\n input.documentId,\n { reportErrors: false },\n );\n if (result.ok) {\n return result.data;\n }\n result.report();\n input.onFailure?.({ message: result.message, status: result.status });\n return null;\n}\n\ntype MoveRemoteContainerDocumentStatus = \"complete\" | \"partial\";\n\ninterface MoveRemoteContainerDocumentResult {\n accessEpoch: number | null;\n accessStateHash: string | null;\n linkedContainerIds: readonly string[];\n nextContainerId: string;\n remoteState: RemoteDocumentPersistedState | null;\n status: MoveRemoteContainerDocumentStatus;\n}\n\nfunction resolveActiveDocumentContainerId(\n linkedContainerIds: ReadonlyArray<string>,\n preferredContainerId: string,\n): string | null {\n if (linkedContainerIds.includes(preferredContainerId)) {\n return preferredContainerId;\n }\n\n return linkedContainerIds[0] ?? null;\n}\n\nfunction containerDocumentMoveResult(input: {\n document: RelinkRemoteDocumentResult;\n nextContainerId: string;\n status: MoveRemoteContainerDocumentStatus;\n}): MoveRemoteContainerDocumentResult {\n return {\n accessEpoch: input.document.plan.state.epoch,\n accessStateHash: input.document.response.manifestHash,\n linkedContainerIds: input.document.linkedContainerIds,\n nextContainerId: input.nextContainerId,\n remoteState: input.document.persistedState,\n status: input.status,\n };\n}\n\nasync function containerDocumentAlreadyMovedResult(input: {\n writerProjection: DocumentWriterProjectionResponse;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentLinkRuntime;\n isCurrent?: (() => boolean) | undefined;\n linkedContainerIds: readonly string[];\n nextContainerId: string;\n policyOperation: PrincipalPolicyOperation;\n status: MoveRemoteContainerDocumentStatus;\n}): Promise<MoveRemoteContainerDocumentResult> {\n const verified: { head?: VerifiedDocumentLinkSetManifest | undefined } = {};\n await assertDocumentWriterProjectionConsistent(input.writerProjection, {\n execSql: input.runtime.infra.execSql,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n stillCurrent: input.isCurrent,\n warmReferencedPrincipalPolicies:\n input.runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n }),\n onVerifiedAuthorization: (authorization) => {\n verified.head = authorization.documentManifestByHash.get(\n input.writerProjection.documentManifest.manifestHash,\n );\n },\n });\n if (!verified.head)\n throw new Error(\"Move replay lacks a verified document head\");\n return {\n accessEpoch: verified.head.state.epoch,\n accessStateHash: verified.head.manifestHash,\n linkedContainerIds: input.linkedContainerIds,\n nextContainerId: input.nextContainerId,\n remoteState: persistedDocumentCreateStateFromWriterProjection(\n input.writerProjection,\n ),\n status: input.status,\n };\n}\n\nasync function linkRemoteContainerDocument(input: {\n attachmentReuse: LinkSetAttachmentReuse;\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"link\",\n });\n}\n\n/** The move target (unless link-only) and any extra links, each once. */\nfunction moveLinkTargets(input: {\n readonly additionalLinkContainerIds?: readonly string[] | undefined;\n readonly linkOnly?: boolean | undefined;\n readonly targetContainerId: string;\n}): Set<string> {\n return new Set([\n ...(input.linkOnly ? [] : [input.targetContainerId]),\n ...(input.additionalLinkContainerIds ?? []),\n ]);\n}\n\nexport async function moveRemoteContainerDocument(input: {\n linkOnly?: boolean | undefined;\n additionalLinkContainerIds?: readonly string[] | undefined;\n removedLinkContainerIds?: readonly string[] | undefined;\n currentContainerId: string;\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n replaceLinkedContainers?: boolean | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<MoveRemoteContainerDocumentResult | null> {\n const {\n documentId,\n noteId,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n if (input.isCurrent?.() === false) return null;\n // One move workflow is one policy operation: its link and unlink legs share\n // a directory discovery. Each leg's commit still refuses a stale view. Its\n // legs also list the document's attachments once (see `attachmentReuse`).\n const policyOperation = createPrincipalPolicyOperation();\n const attachmentReuse = createLinkSetAttachmentReuse();\n const writerProjection = await fetchMoveWriterProjection({\n documentId,\n onFailure: input.onFailure,\n runtime,\n });\n if (!writerProjection || input.isCurrent?.() === false) {\n return null;\n }\n if (writerProjection.documentId !== documentId)\n throw new Error(\"Move replay document id mismatch\");\n const initialLinkedContainerIds =\n readLinkedContainerIdsFromDocumentManifest(writerProjection);\n\n let latestLinkedContainerIds: readonly string[] = initialLinkedContainerIds;\n let latestDocument: RelinkRemoteDocumentResult | null = null;\n for (const linkTarget of moveLinkTargets(input)) {\n if (latestLinkedContainerIds.includes(linkTarget)) continue;\n const linkedDocument = await linkRemoteContainerDocument({\n attachmentReuse,\n documentId,\n isCurrent: input.isCurrent,\n noteId,\n onFailure: input.onFailure,\n policyOperation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId: linkTarget,\n });\n if (!linkedDocument || input.isCurrent?.() === false) {\n return null;\n }\n\n latestDocument = linkedDocument;\n latestLinkedContainerIds = linkedDocument.linkedContainerIds;\n }\n\n const unlinkContainerIds = resolveContainerDocumentMoveUnlinkIds({\n ...input,\n linkedContainerIds: latestLinkedContainerIds,\n });\n\n const unlinked = await unlinkMovedDocumentSources({\n ...input,\n attachmentReuse,\n latestDocument,\n latestLinkedContainerIds,\n policyOperation,\n unlinkContainerIds,\n });\n if (!unlinked) return null;\n latestDocument = unlinked.latestDocument;\n latestLinkedContainerIds = unlinked.latestLinkedContainerIds;\n\n const nextContainerId = resolveActiveDocumentContainerId(\n latestLinkedContainerIds,\n targetContainerId,\n );\n if (!nextContainerId) {\n return null;\n }\n\n const status =\n unlinked.failedUnlinkContainerIds.length > 0 ? \"partial\" : \"complete\";\n return latestDocument\n ? containerDocumentMoveResult({\n document: latestDocument,\n nextContainerId,\n status,\n })\n : containerDocumentAlreadyMovedResult({\n writerProjection,\n resolveProjectionUserKey,\n runtime,\n isCurrent: input.isCurrent,\n linkedContainerIds: latestLinkedContainerIds,\n nextContainerId,\n policyOperation,\n status,\n });\n}\n\n// The unlink half of a move: every source is attempted even when an earlier\n// one fails, so one dead source cannot strand the others; a failed unlink\n// leaves the move \"partial\" for the queue to retry.\nasync function unlinkMovedDocumentSources(input: {\n attachmentReuse: LinkSetAttachmentReuse;\n documentId: string;\n isCurrent?: (() => boolean) | undefined;\n latestDocument: RelinkRemoteDocumentResult | null;\n latestLinkedContainerIds: readonly string[];\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n unlinkContainerIds: readonly string[];\n}): Promise<{\n failedUnlinkContainerIds: readonly string[];\n latestDocument: RelinkRemoteDocumentResult | null;\n latestLinkedContainerIds: readonly string[];\n} | null> {\n const { noteId, runtime, targetContainerId } = input;\n let { latestDocument, latestLinkedContainerIds } = input;\n const failedUnlinkContainerIds: string[] = [];\n for (const unlinkContainerId of input.unlinkContainerIds) {\n if (input.isCurrent?.() === false) return null;\n const unlinkedDocument = await unlinkRemoteContainerDocument({\n attachmentReuse: input.attachmentReuse,\n documentId: input.documentId,\n isCurrent: input.isCurrent,\n noteId,\n onFailure: input.onFailure,\n policyOperation: input.policyOperation,\n resolveProjectionUserKey: input.resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n runtime,\n targetContainerId: unlinkContainerId,\n });\n if (input.isCurrent?.() === false) return null;\n if (!unlinkedDocument) {\n failedUnlinkContainerIds.push(unlinkContainerId);\n runtime.util.log(\n `Container contents: note ${noteId} was linked to ${targetContainerId} but failed to unlink from ${unlinkContainerId}`,\n );\n continue;\n }\n\n latestDocument = unlinkedDocument;\n latestLinkedContainerIds = unlinkedDocument.linkedContainerIds;\n }\n return { failedUnlinkContainerIds, latestDocument, latestLinkedContainerIds };\n}\n"]}
@@ -3,7 +3,6 @@ import { DocumentContainerProjectionRepository } from "../../../data/persistence
3
3
  import { errorMessage } from "../../../data/shared/errorMessage.js";
4
4
  import { isDatabaseUnavailableError } from "../../../data/sync/databaseUnavailable.js";
5
5
  import { RemoteDocumentService, resolveDocumentCreateAuthor, } from "../../documents/index.js";
6
- import { createRuntimePrincipalPolicyWarmer, } from "../../principals/runtimePolicyWarmer.js";
7
6
  /**
8
7
  * Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.
9
8
  * The caller's string-only log line stays the fallback for a host without
@@ -57,7 +56,9 @@ export async function relinkRemoteContainerDocument(input) {
57
56
  rotationSnapshot: input.rotationSnapshot,
58
57
  stillCurrent: input.isCurrent,
59
58
  targetContainerId,
60
- warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(runtime, { operation: input.policyOperation }),
59
+ warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({
60
+ operation: input.policyOperation,
61
+ }),
61
62
  });
62
63
  if (!result) {
63
64
  runtime.util.log(`Container contents: failed to ${operation} note ${noteId} ${operation === "link" ? "to" : "from"} container ${targetContainerId}`);
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.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,oBAAoB,CAAC,UAAU,EAAE,MAAM,CAAC,kBAAkB,EAAE;YAC5D,YAAY,EAAE,KAAK,CAAC,SAAS;SAC9B,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAChB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,uCAAuC,CAC3C,KAAK,EACL,OAAO,CAAC,IAAI,CAAC,sBAAsB,EACnC;YACE,QAAQ,EAAE,UAAU;YACpB,UAAU,EAAE,UAAU;YACtB,SAAS,EAAE,YAAY,SAAS,EAAE;SACnC,CACF,CAAC;QACF,MAAM,OAAO,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,iCAAiC,SAAS,SAAS,MAAM,IAAI,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,cAAc,iBAAiB,KAAK,OAAO,EAAE,CAC/I,CAAC;QACF,sEAAsE;QACtE,4EAA4E;QAC5E,oEAAoE;QACpE,iCAAiC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACvD,KAAK,CAAC,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7C,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CAAC,KAanD;IACC,OAAO,6BAA6B,CAAC;QACnC,GAAG,KAAK;QACR,SAAS,EAAE,QAAQ;KACpB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { DocumentContainerProjectionRepository } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport { isDatabaseUnavailableError } from \"../../../data/sync/databaseUnavailable\";\nimport {\n type DocumentLinkSetFailureHandler,\n type LinkSetAttachmentReuse,\n type RelinkRemoteDocumentResult,\n RemoteDocumentService,\n type RemoteDocumentServiceApi,\n resolveDocumentCreateAuthor,\n} from \"../../documents\";\nimport type { SubtreePurgeRoot } from \"../../documents/purge/subtreePurgeScope\";\nimport {\n createRuntimePrincipalPolicyWarmer,\n type PrincipalPolicyOperation,\n} from \"../../principals/runtimePolicyWarmer\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerDocumentLinkApi = RemoteDocumentServiceApi;\ntype ContainerDocumentLinkOperation = Parameters<\n RemoteDocumentService[\"relinkRemoteDocument\"]\n>[0][\"operation\"];\ntype RemoteDocumentPersistedState =\n RelinkRemoteDocumentResult[\"persistedState\"];\n\nexport interface ContainerDocumentLinkRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: ContainerDocumentLinkApi &\n Pick<\n ContainerContentsWorkflowRuntime[\"apiClient\"],\n \"getPrincipalPolicyPages\" | \"getProjectionPolicyHistoryPages\"\n >;\n}\n\nexport type { RemoteDocumentPersistedState };\n\n/**\n * Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.\n * The caller's string-only log line stays the fallback for a host without\n * `logError`, so this never logs a second copy of the same failure.\n */\nfunction reportDocumentLinkMutationFailure(\n util: ContainerDocumentLinkRuntime[\"util\"],\n error: unknown,\n): void {\n // `ApiClient` returns `RequestFailure` objects instead of throwing, so\n // offline and 403/404/409 already left through the `!result` branch: a status\n // filter here would be dead code. Only a database lost mid-flight stays quiet.\n if (!util.logError || isDatabaseUnavailableError(error)) return;\n try {\n // A host logger that throws or rejects must not replace the null result or\n // skip the failure handler below.\n void Promise.resolve(\n util.logError(\"Container contents: document link mutation failed\", error),\n ).catch(() => undefined);\n } catch {\n // Hosts may throw synchronously or return a rejected promise.\n }\n}\n\nexport async function relinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: ContainerDocumentLinkOperation;\n /** A workflow root's token; each leg otherwise discovers on its own. */\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const {\n documentId,\n noteId,\n operation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n const author = resolveDocumentCreateAuthor(runtime);\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n const execSql = runtime.infra.execSql;\n if (input.isCurrent?.() === false) return null;\n if (!author || !targetSecretKey) {\n runtime.util.log(\n \"Container contents: document mutation skipped because the local key context is unavailable\",\n );\n input.onFailure?.({\n message: \"the local key context is unavailable\",\n status: null,\n });\n return null;\n }\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: targetSecretKey,\n execSql,\n });\n\n try {\n const result = await remoteDocuments.relinkRemoteDocument({\n attachmentReuse: input.attachmentReuse,\n beforeSubmit: input.beforeSubmit,\n author,\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n onFailure: input.onFailure,\n operation,\n resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n stillCurrent: input.isCurrent,\n targetContainerId,\n warmReferencedPrincipalPolicies: createRuntimePrincipalPolicyWarmer(\n runtime,\n { operation: input.policyOperation },\n ),\n });\n if (!result) {\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}`,\n );\n return null;\n }\n if (input.isCurrent?.() === false) return null;\n\n await new DocumentContainerProjectionRepository(\n execSql,\n ).replaceDocumentLinks(documentId, result.linkedContainerIds, {\n stillCurrent: input.isCurrent,\n });\n\n return result;\n } catch (error) {\n await reportAndRethrowKeyingVerificationError(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: `document.${operation}`,\n },\n );\n const message = errorMessage(error);\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}: ${message}`,\n );\n // After the keying rethrow above, so a verification failure keeps its\n // security incident instead of being reported twice, and before the failure\n // handler, so a throwing caller callback cannot swallow the report.\n reportDocumentLinkMutationFailure(runtime.util, error);\n input.onFailure?.({ message, status: null });\n return null;\n }\n}\n\nexport async function unlinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"unlink\",\n });\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uCAAuC,EAAE,MAAM,kDAAkD,CAAC;AAC3G,OAAO,EAAE,qCAAqC,EAAE,MAAM,qFAAqF,CAAC;AAC5I,OAAO,EAAE,YAAY,EAAE,MAAM,mCAAmC,CAAC;AACjE,OAAO,EAAE,0BAA0B,EAAE,MAAM,wCAAwC,CAAC;AACpF,OAAO,EAIL,qBAAqB,EAErB,2BAA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,SAAS,EAAE,YAAY,SAAS,EAAE;SACnC,CACF,CAAC;QACF,MAAM,OAAO,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;QACpC,OAAO,CAAC,IAAI,CAAC,GAAG,CACd,iCAAiC,SAAS,SAAS,MAAM,IAAI,SAAS,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,cAAc,iBAAiB,KAAK,OAAO,EAAE,CAC/I,CAAC;QACF,sEAAsE;QACtE,4EAA4E;QAC5E,oEAAoE;QACpE,iCAAiC,CAAC,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QACvD,KAAK,CAAC,SAAS,EAAE,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QAC7C,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CAAC,KAanD;IACC,OAAO,6BAA6B,CAAC;QACnC,GAAG,KAAK;QACR,SAAS,EAAE,QAAQ;KACpB,CAAC,CAAC;AACL,CAAC","sourcesContent":["import type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport { reportAndRethrowKeyingVerificationError } from \"../../../data/keyingProjectionVerification/error\";\nimport { DocumentContainerProjectionRepository } from \"../../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nimport { errorMessage } from \"../../../data/shared/errorMessage\";\nimport { isDatabaseUnavailableError } from \"../../../data/sync/databaseUnavailable\";\nimport {\n type DocumentLinkSetFailureHandler,\n type LinkSetAttachmentReuse,\n type RelinkRemoteDocumentResult,\n RemoteDocumentService,\n type RemoteDocumentServiceApi,\n resolveDocumentCreateAuthor,\n} from \"../../documents\";\nimport type { SubtreePurgeRoot } from \"../../documents/purge/subtreePurgeScope\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport type { ContainerContentsWorkflowRuntime } from \"../runtime\";\n\nexport type ContainerDocumentLinkApi = RemoteDocumentServiceApi;\ntype ContainerDocumentLinkOperation = Parameters<\n RemoteDocumentService[\"relinkRemoteDocument\"]\n>[0][\"operation\"];\ntype RemoteDocumentPersistedState =\n RelinkRemoteDocumentResult[\"persistedState\"];\n\nexport interface ContainerDocumentLinkRuntime\n extends Pick<\n ContainerContentsWorkflowRuntime,\n | \"auth\"\n | \"crypto\"\n | \"infra\"\n | \"principalPolicies\"\n | \"resolveTrustedUserIdentity\"\n | \"state\"\n | \"util\"\n > {\n apiClient: ContainerDocumentLinkApi;\n}\n\nexport type { RemoteDocumentPersistedState };\n\n/**\n * Hand a link/unlink/move/purge failure to host diagnostics as a real `Error`.\n * The caller's string-only log line stays the fallback for a host without\n * `logError`, so this never logs a second copy of the same failure.\n */\nfunction reportDocumentLinkMutationFailure(\n util: ContainerDocumentLinkRuntime[\"util\"],\n error: unknown,\n): void {\n // `ApiClient` returns `RequestFailure` objects instead of throwing, so\n // offline and 403/404/409 already left through the `!result` branch: a status\n // filter here would be dead code. Only a database lost mid-flight stays quiet.\n if (!util.logError || isDatabaseUnavailableError(error)) return;\n try {\n // A host logger that throws or rejects must not replace the null result or\n // skip the failure handler below.\n void Promise.resolve(\n util.logError(\"Container contents: document link mutation failed\", error),\n ).catch(() => undefined);\n } catch {\n // Hosts may throw synchronously or return a rejected promise.\n }\n}\n\nexport async function relinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n operation: ContainerDocumentLinkOperation;\n /** A workflow root's token; each leg otherwise discovers on its own. */\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot?: Uint8Array | undefined;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n const {\n documentId,\n noteId,\n operation,\n resolveProjectionUserKey,\n runtime,\n targetContainerId,\n } = input;\n const author = resolveDocumentCreateAuthor(runtime);\n const targetSecretKey = runtime.crypto.encapsulationKeyPair?.secretKey;\n const execSql = runtime.infra.execSql;\n if (input.isCurrent?.() === false) return null;\n if (!author || !targetSecretKey) {\n runtime.util.log(\n \"Container contents: document mutation skipped because the local key context is unavailable\",\n );\n input.onFailure?.({\n message: \"the local key context is unavailable\",\n status: null,\n });\n return null;\n }\n const remoteDocuments = new RemoteDocumentService({\n api: runtime.apiClient,\n encapsulationSecretKey: targetSecretKey,\n execSql,\n });\n\n try {\n const result = await remoteDocuments.relinkRemoteDocument({\n attachmentReuse: input.attachmentReuse,\n beforeSubmit: input.beforeSubmit,\n author,\n documentId,\n expectedSubtreeRoot: input.expectedSubtreeRoot,\n onFailure: input.onFailure,\n operation,\n resolveProjectionUserKey,\n rotationSnapshot: input.rotationSnapshot,\n stillCurrent: input.isCurrent,\n targetContainerId,\n warmReferencedPrincipalPolicies: runtime.principalPolicies.createWarmer({\n operation: input.policyOperation,\n }),\n });\n if (!result) {\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}`,\n );\n return null;\n }\n if (input.isCurrent?.() === false) return null;\n\n await new DocumentContainerProjectionRepository(\n execSql,\n ).replaceDocumentLinks(documentId, result.linkedContainerIds, {\n stillCurrent: input.isCurrent,\n });\n\n return result;\n } catch (error) {\n await reportAndRethrowKeyingVerificationError(\n error,\n runtime.util.reportSecurityIncident,\n {\n objectId: documentId,\n objectKind: \"document\",\n operation: `document.${operation}`,\n },\n );\n const message = errorMessage(error);\n runtime.util.log(\n `Container contents: failed to ${operation} note ${noteId} ${operation === \"link\" ? \"to\" : \"from\"} container ${targetContainerId}: ${message}`,\n );\n // After the keying rethrow above, so a verification failure keeps its\n // security incident instead of being reported twice, and before the failure\n // handler, so a throwing caller callback cannot swallow the report.\n reportDocumentLinkMutationFailure(runtime.util, error);\n input.onFailure?.({ message, status: null });\n return null;\n }\n}\n\nexport async function unlinkRemoteContainerDocument(input: {\n attachmentReuse?: LinkSetAttachmentReuse | undefined;\n beforeSubmit?: (() => Promise<boolean>) | undefined;\n documentId: string;\n expectedSubtreeRoot?: SubtreePurgeRoot | undefined;\n isCurrent?: (() => boolean) | undefined;\n noteId: string;\n onFailure?: DocumentLinkSetFailureHandler | undefined;\n policyOperation?: PrincipalPolicyOperation | undefined;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n rotationSnapshot: Uint8Array;\n runtime: ContainerDocumentLinkRuntime;\n targetContainerId: string;\n}): Promise<RelinkRemoteDocumentResult | null> {\n return relinkRemoteContainerDocument({\n ...input,\n operation: \"unlink\",\n });\n}\n"]}
@@ -13,7 +13,7 @@ export { type ContainerMetadataDocument, createInitializedContainerMetadataDocum
13
13
  export { listPendingWrites, type PendingWriteQueueItem, type PendingWriteQueueItemStatus, type PendingWriteQueueObjectKind, type PendingWriteQueueOperation, type PendingWriteQueueOperationKind, type PendingWriteQueueOperationStatus, } from "./pendingWrites/index.js";
14
14
  export { type ContainerContentsProjectionUserKeyResolver, createContainerContentsDocumentProjectionUserKeyResolver, createContainerContentsProjectionUserKeyResolver, didContainerContentsProjectionKeyRuntimeChange, } from "./projectionKeys.js";
15
15
  export type { RecoveryFolder } from "./recovery/folderRecovery.js";
16
- export { type ContainerContentsRootAdopter, type ContainerContentsRootAdoptionInput, type ContainerContentsStoreWorkflowRuntime, type ContainerContentsWorkflowRuntime, type ContainerContentsWorkflowRuntimeAuth, type ContainerContentsWorkflowRuntimeCrypto, type ContainerContentsWorkflowRuntimeGroups, type ContainerContentsWorkflowRuntimeInfra, type ContainerContentsWorkflowRuntimeInput, type ContainerContentsWorkflowRuntimeInputGroups, type ContainerContentsWorkflowRuntimeState, type ContainerContentsWorkflowRuntimeUtil, createContainerContentsDocumentsRuntime, createContainerContentsStoreWorkflowRuntime, createContainerContentsWorkflowRuntime, } from "./runtime.js";
16
+ export { type ContainerContentsRootAdopter, type ContainerContentsRootAdoptionInput, type ContainerContentsStoreWorkflowRuntime, type ContainerContentsWorkflowRuntime, type ContainerContentsWorkflowRuntimeAuth, type ContainerContentsWorkflowRuntimeCrypto, type ContainerContentsWorkflowRuntimeGroups, type ContainerContentsWorkflowRuntimeInfra, type ContainerContentsWorkflowRuntimeInput, type ContainerContentsWorkflowRuntimeInputGroups, type ContainerContentsWorkflowRuntimeSnapshot, type ContainerContentsWorkflowRuntimeState, type ContainerContentsWorkflowRuntimeUtil, createContainerContentsDocumentsRuntime, createContainerContentsStoreWorkflowRuntime, createContainerContentsStoreWorkflowRuntimeFromSnapshot, createContainerContentsWorkflowRuntime, createContainerContentsWorkflowRuntimeFromSnapshot, } from "./runtime.js";
17
17
  export type { ContainerDocumentObjectSyncState, ContainerDocumentObjectSyncStatus, } from "./syncState.js";
18
18
  export { createContainerDocumentObjectSyncState, syncedContainerDocumentObjectSyncState, } from "./syncState.js";
19
19
  export { type ContainerSystemSlotDefinition, deriveContainerSystemSlot, } from "./systemSlot.js";
@@ -11,7 +11,7 @@ export { hasContainerMetadataDocumentUpdateEvent, persistContainerMetadataStateF
11
11
  export { createInitializedContainerMetadataDocument, getDefaultContainerName, readContainerMetadataValue, writeContainerMetadataValue, } from "./metadata/containerMetadataDocument.js";
12
12
  export { listPendingWrites, } from "./pendingWrites/index.js";
13
13
  export { createContainerContentsDocumentProjectionUserKeyResolver, createContainerContentsProjectionUserKeyResolver, didContainerContentsProjectionKeyRuntimeChange, } from "./projectionKeys.js";
14
- export { createContainerContentsDocumentsRuntime, createContainerContentsStoreWorkflowRuntime, createContainerContentsWorkflowRuntime, } from "./runtime.js";
14
+ export { createContainerContentsDocumentsRuntime, createContainerContentsStoreWorkflowRuntime, createContainerContentsStoreWorkflowRuntimeFromSnapshot, createContainerContentsWorkflowRuntime, createContainerContentsWorkflowRuntimeFromSnapshot, } from "./runtime.js";
15
15
  export { createContainerDocumentObjectSyncState, syncedContainerDocumentObjectSyncState, } from "./syncState.js";
16
16
  export { deriveContainerSystemSlot, } from "./systemSlot.js";
17
17
  export { purgeLocalContainerDocument, purgeRemoteContainerDocument, } from "./tombstones/documentPurge.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,kFAAkF,CAAC;AACzI,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,6BAA6B,GAC9B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAEL,gCAAgC,EAChC,+BAA+B,EAC/B,6BAA6B,EAC7B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EASL,yCAAyC,GAC1C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,0BAA0B,EAG1B,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,GAEnB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EASL,YAAY,GACb,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAQL,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAQL,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,uCAAuC,EACvC,wCAAwC,EACxC,uCAAuC,EACvC,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,EAEL,0CAA0C,EAC1C,uBAAuB,EACvB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,iBAAiB,GAOlB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,wDAAwD,EACxD,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAaL,uCAAuC,EACvC,2CAA2C,EAC3C,sCAAsC,GACvC,MAAM,WAAW,CAAC;AAKnB,OAAO,EACL,sCAAsC,EACtC,sCAAsC,GACvC,MAAM,aAAa,CAAC;AACrB,OAAO,EAEL,yBAAyB,GAC1B,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC","sourcesContent":["export { DocumentContainerProjectionRepository } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"./attribution/documentAttributionRanges\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n defaultContainerContentsPersistence,\n} from \"./containerPersistence\";\nexport {\n type ContainerDocumentLinkInput,\n type ContainerDocumentQueries,\n type ContainerDocumentSidebarRow,\n type ContainerDocumentTombstone,\n type ContainerItemRow,\n type ContainerItemSort,\n type ContainerItemSortDirection,\n type ContainerItemSortKey,\n createContainerDocumentQueriesFromRuntime,\n} from \"./documentQueries\";\nexport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n type MergeDocumentSummary,\n moveDocumentLink,\n moveLocalDocumentLink,\n removeDocumentLink,\n type SetLinkedContainerIdsForDocument,\n} from \"./documentQueries/documentStructure\";\nexport type { PendingDownloadQueueItem } from \"./documentQueries/pendingDownloads\";\nexport {\n type BlobInfo,\n type BlobInfoAttachmentKind,\n type BlobInfoDocumentReference,\n type BlobInfoInput,\n type BlobInfoList,\n type BlobInfoSort,\n type BlobInfoSortDirection,\n type BlobInfoSortKey,\n listBlobInfo,\n} from \"./info/blobInfo\";\nexport {\n type ContainerInfo,\n type ContainerInfoGrant,\n type ContainerInfoGrantRow,\n type ContainerInfoPathEntry,\n type ContainerInfoRemoteMode,\n type ContainerInfoSecurityDetails,\n type ContainerShareAccessLevel,\n loadContainerInfo,\n} from \"./info/containerInfo\";\nexport {\n type DocumentInfo,\n type DocumentInfoAttachment,\n type DocumentInfoAuthorizingContainerPath,\n type DocumentInfoLocalDetails,\n type DocumentInfoRemoteAttachmentBinding,\n type DocumentInfoRemoteDetails,\n type DocumentInfoRemoteMode,\n loadDocumentInfo,\n} from \"./info/documentInfo\";\nexport {\n type ContainerMetadataPatch,\n hasContainerMetadataDocumentUpdateEvent,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n syncContainerMetadataState,\n} from \"./metadata\";\nexport {\n type ContainerMetadataDocument,\n createInitializedContainerMetadataDocument,\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"./metadata/containerMetadataDocument\";\nexport {\n listPendingWrites,\n type PendingWriteQueueItem,\n type PendingWriteQueueItemStatus,\n type PendingWriteQueueObjectKind,\n type PendingWriteQueueOperation,\n type PendingWriteQueueOperationKind,\n type PendingWriteQueueOperationStatus,\n} from \"./pendingWrites\";\nexport {\n type ContainerContentsProjectionUserKeyResolver,\n createContainerContentsDocumentProjectionUserKeyResolver,\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport type { RecoveryFolder } from \"./recovery/folderRecovery\";\nexport {\n type ContainerContentsRootAdopter,\n type ContainerContentsRootAdoptionInput,\n type ContainerContentsStoreWorkflowRuntime,\n type ContainerContentsWorkflowRuntime,\n type ContainerContentsWorkflowRuntimeAuth,\n type ContainerContentsWorkflowRuntimeCrypto,\n type ContainerContentsWorkflowRuntimeGroups,\n type ContainerContentsWorkflowRuntimeInfra,\n type ContainerContentsWorkflowRuntimeInput,\n type ContainerContentsWorkflowRuntimeInputGroups,\n type ContainerContentsWorkflowRuntimeState,\n type ContainerContentsWorkflowRuntimeUtil,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsWorkflowRuntime,\n} from \"./runtime\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"./syncState\";\nexport {\n createContainerDocumentObjectSyncState,\n syncedContainerDocumentObjectSyncState,\n} from \"./syncState\";\nexport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"./systemSlot\";\nexport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"./tombstones/documentPurge\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qCAAqC,EAAE,MAAM,kFAAkF,CAAC;AACzI,OAAO,EACL,0BAA0B,EAC1B,0BAA0B,GAC3B,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAGL,6BAA6B,GAC9B,MAAM,yCAAyC,CAAC;AACjD,OAAO,EAEL,gCAAgC,EAChC,+BAA+B,EAC/B,6BAA6B,EAC7B,mCAAmC,GACpC,MAAM,wBAAwB,CAAC;AAChC,OAAO,EASL,yCAAyC,GAC1C,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,oBAAoB,EACpB,eAAe,EACf,qBAAqB,EACrB,0BAA0B,EAG1B,gBAAgB,EAChB,qBAAqB,EACrB,kBAAkB,GAEnB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EASL,YAAY,GACb,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAQL,iBAAiB,GAClB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAQL,gBAAgB,GACjB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAEL,uCAAuC,EACvC,wCAAwC,EACxC,uCAAuC,EACvC,0BAA0B,GAC3B,MAAM,YAAY,CAAC;AACpB,OAAO,EAEL,0CAA0C,EAC1C,uBAAuB,EACvB,0BAA0B,EAC1B,2BAA2B,GAC5B,MAAM,sCAAsC,CAAC;AAC9C,OAAO,EACL,iBAAiB,GAOlB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,wDAAwD,EACxD,gDAAgD,EAChD,8CAA8C,GAC/C,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EAcL,uCAAuC,EACvC,2CAA2C,EAC3C,uDAAuD,EACvD,sCAAsC,EACtC,kDAAkD,GACnD,MAAM,WAAW,CAAC;AAKnB,OAAO,EACL,sCAAsC,EACtC,sCAAsC,GACvC,MAAM,aAAa,CAAC;AACrB,OAAO,EAEL,yBAAyB,GAC1B,MAAM,cAAc,CAAC;AACtB,OAAO,EACL,2BAA2B,EAC3B,4BAA4B,GAC7B,MAAM,4BAA4B,CAAC","sourcesContent":["export { DocumentContainerProjectionRepository } from \"../../data/persistence/container-contents/documentContainerProjectionPersistence\";\nexport {\n didRegainSyncPrerequisites,\n isDatabaseUnavailableError,\n} from \"../../data/sync/syncCoordinator\";\nexport {\n type DocumentAttributionRangesInput,\n type DocumentAttributionRangesPage,\n loadDocumentAttributionRanges,\n} from \"./attribution/documentAttributionRanges\";\nexport {\n type ContainerSyncWatermarkLane,\n ContainerSyncWatermarkRepository,\n createContainerContentsSyncLane,\n createContainerParentSyncLane,\n defaultContainerContentsPersistence,\n} from \"./containerPersistence\";\nexport {\n type ContainerDocumentLinkInput,\n type ContainerDocumentQueries,\n type ContainerDocumentSidebarRow,\n type ContainerDocumentTombstone,\n type ContainerItemRow,\n type ContainerItemSort,\n type ContainerItemSortDirection,\n type ContainerItemSortKey,\n createContainerDocumentQueriesFromRuntime,\n} from \"./documentQueries\";\nexport {\n activateDocumentLink,\n addDocumentLink,\n canMutateDocumentLink,\n canMutateLocalDocumentLink,\n type DocumentStructuralMutationHost,\n type MergeDocumentSummary,\n moveDocumentLink,\n moveLocalDocumentLink,\n removeDocumentLink,\n type SetLinkedContainerIdsForDocument,\n} from \"./documentQueries/documentStructure\";\nexport type { PendingDownloadQueueItem } from \"./documentQueries/pendingDownloads\";\nexport {\n type BlobInfo,\n type BlobInfoAttachmentKind,\n type BlobInfoDocumentReference,\n type BlobInfoInput,\n type BlobInfoList,\n type BlobInfoSort,\n type BlobInfoSortDirection,\n type BlobInfoSortKey,\n listBlobInfo,\n} from \"./info/blobInfo\";\nexport {\n type ContainerInfo,\n type ContainerInfoGrant,\n type ContainerInfoGrantRow,\n type ContainerInfoPathEntry,\n type ContainerInfoRemoteMode,\n type ContainerInfoSecurityDetails,\n type ContainerShareAccessLevel,\n loadContainerInfo,\n} from \"./info/containerInfo\";\nexport {\n type DocumentInfo,\n type DocumentInfoAttachment,\n type DocumentInfoAuthorizingContainerPath,\n type DocumentInfoLocalDetails,\n type DocumentInfoRemoteAttachmentBinding,\n type DocumentInfoRemoteDetails,\n type DocumentInfoRemoteMode,\n loadDocumentInfo,\n} from \"./info/documentInfo\";\nexport {\n type ContainerMetadataPatch,\n hasContainerMetadataDocumentUpdateEvent,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n syncContainerMetadataState,\n} from \"./metadata\";\nexport {\n type ContainerMetadataDocument,\n createInitializedContainerMetadataDocument,\n getDefaultContainerName,\n readContainerMetadataValue,\n writeContainerMetadataValue,\n} from \"./metadata/containerMetadataDocument\";\nexport {\n listPendingWrites,\n type PendingWriteQueueItem,\n type PendingWriteQueueItemStatus,\n type PendingWriteQueueObjectKind,\n type PendingWriteQueueOperation,\n type PendingWriteQueueOperationKind,\n type PendingWriteQueueOperationStatus,\n} from \"./pendingWrites\";\nexport {\n type ContainerContentsProjectionUserKeyResolver,\n createContainerContentsDocumentProjectionUserKeyResolver,\n createContainerContentsProjectionUserKeyResolver,\n didContainerContentsProjectionKeyRuntimeChange,\n} from \"./projectionKeys\";\nexport type { RecoveryFolder } from \"./recovery/folderRecovery\";\nexport {\n type ContainerContentsRootAdopter,\n type ContainerContentsRootAdoptionInput,\n type ContainerContentsStoreWorkflowRuntime,\n type ContainerContentsWorkflowRuntime,\n type ContainerContentsWorkflowRuntimeAuth,\n type ContainerContentsWorkflowRuntimeCrypto,\n type ContainerContentsWorkflowRuntimeGroups,\n type ContainerContentsWorkflowRuntimeInfra,\n type ContainerContentsWorkflowRuntimeInput,\n type ContainerContentsWorkflowRuntimeInputGroups,\n type ContainerContentsWorkflowRuntimeSnapshot,\n type ContainerContentsWorkflowRuntimeState,\n type ContainerContentsWorkflowRuntimeUtil,\n createContainerContentsDocumentsRuntime,\n createContainerContentsStoreWorkflowRuntime,\n createContainerContentsStoreWorkflowRuntimeFromSnapshot,\n createContainerContentsWorkflowRuntime,\n createContainerContentsWorkflowRuntimeFromSnapshot,\n} from \"./runtime\";\nexport type {\n ContainerDocumentObjectSyncState,\n ContainerDocumentObjectSyncStatus,\n} from \"./syncState\";\nexport {\n createContainerDocumentObjectSyncState,\n syncedContainerDocumentObjectSyncState,\n} from \"./syncState\";\nexport {\n type ContainerSystemSlotDefinition,\n deriveContainerSystemSlot,\n} from \"./systemSlot\";\nexport {\n purgeLocalContainerDocument,\n purgeRemoteContainerDocument,\n} from \"./tombstones/documentPurge\";\n"]}
@@ -1,6 +1,6 @@
1
1
  import type { ProjectionUserKeyResolver } from "../../../data/keyingProjectionVerification/index.js";
2
2
  import type { ContainerContentsPersistence } from "../../../data/persistence/container-contents/containerContentsPersistence.js";
3
- import type { PrincipalPolicyOperation } from "../../principals/runtimePolicyWarmer.js";
3
+ import type { PrincipalPolicyOperation } from "../../principals/principalPolicyService.js";
4
4
  import { type ContainerMetadataSyncAttempt, type ContainerMetadataSyncRuntime } from "./metadataRemoteSync.js";
5
5
  export { hasContainerMetadataDocumentUpdateEvent, listContainerMetadataDocumentUpdateIds, } from "./metadataEvents.js";
6
6
  export { installContainerMetadataRecord, persistContainerMetadataStateFromRuntime, renameContainerMetadataStateFromRuntime, setContainerIconMetadataStateFromRuntime, } from "./metadataPersistence.js";
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CA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AE,CAAC;QACf,2CAA2C,CACzC,KAAK,CAAC,wBAAwB,EAC9B,KAAK,CAAC,aAAa,EACnB,EAAE,CACH,CAAC;QACF,aAAa,CAAC,wBAAwB,GAAG,IAAI,CAAC;QAC9C,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC3B,CAAC;IACD,aAAa,CAAC,SAAS,GAAG,SAAS,CAAC,SAAS,CAAC;IAC9C,8BAA8B,CAAC,aAAa,EAAE,SAAS,CAAC,MAAM,CAAC,CAAC;IAChE,IAAI,SAAS,CAAC,0BAA0B,EAAE,CAAC;QACzC,oEAAoE;QACpE,2EAA2E;QAC3E,6CAA6C;QAC7C,2CAA2C,CACzC,KAAK,CAAC,wBAAwB,EAC9B,KAAK,CAAC,aAAa,EACnB,EAAE,CACH,CAAC;QACF,aAAa,CAAC,wBAAwB,GAAG,IAAI,CAAC;IAChD,CAAC;IAED,OAAO;QACL,GAAG,SAAS;QACZ,yBAAyB,EAAE,sCAAsC,CAAC;YAChE,SAAS;YACT,kBAAkB,EAAE,GAAG,EAAE,CACvB,mCAAmC,CAAC,aAAa,EAAE,WAAW,CAAC;SAClE,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import {\n encodeVersionVector,\n exportFullHistorySnapshot,\n} from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { ContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { settleOutgoingPassAndDecideReArm } from \"../../../data/sync/outgoingUpdateSettlement\";\nimport {\n readPullContinuation,\n shouldClearDocumentSyncFailureAfterPass,\n} from \"../../documents\";\nimport type { PrincipalPolicyOperation } from \"../../principals/runtimePolicyWarmer\";\nimport { applyIncomingContainerMetadataUpdates } from \"./metadataIncomingUpdateIsolation\";\nimport {\n currentMetadataPullContinuation,\n hasCurrentContainerMetadataReadState,\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\nimport {\n type ContainerMetadataSyncAttempt,\n type ContainerMetadataSyncRuntime,\n syncRemoteContainerMetadata,\n} from \"./metadataRemoteSync\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"./metadataStateIsolation\";\nimport { shouldRequestContainerMetadataFollowup } from \"./metadataSyncFollowup\";\n\nexport {\n hasContainerMetadataDocumentUpdateEvent,\n listContainerMetadataDocumentUpdateIds,\n} from \"./metadataEvents\";\nexport {\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n setContainerIconMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\n\nimport { invalidateContainerMetadataPullContinuation } from \"./metadataPullContinuationInvalidation\";\nimport {\n cleanupContainerMetadataRegistrationsOnFailure,\n discardUnacceptedContainerMetadataUpdateIds,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nimport type {\n ContainerMetadataState,\n MissingContainerMetadataState,\n SyncedContainerMetadataState,\n} from \"./metadataTypes\";\n\nexport {\n cleanupContainerMetadataRegistrationsOnFailure,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nexport type { ContainerMetadataPatch } from \"./metadataTypes\";\n\nexport function settleContainerMetadataOutgoingPass(\n metadataState: ContainerMetadataState,\n attempt: ContainerMetadataSyncAttempt,\n): boolean {\n const shouldReArmOutgoing = settleOutgoingPassAndDecideReArm(metadataState, {\n exhaustedPendingUpdateCount: attempt.synced.exhaustedPendingUpdateCount,\n outgoingUpdateCount: attempt.outgoingUpdateCount,\n rekeyedUpdateCount: attempt.synced.rekeyedPendingUpdateIds.length,\n settledUpdateCount: attempt.synced.settledPendingUpdateIds.length,\n acceptedRecoveryBaseline: attempt.synced.acceptedRecoveryBaseline,\n });\n return (\n attempt.synced.hasDeferredPendingUpdates ||\n shouldReArmOutgoing ||\n attempt.synced.hasIncompletePull\n );\n}\n\nfunction documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection: DocumentWriterProjectionResponse,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): boolean {\n return (\n writerProjection.contentKeyBundle.contentKeyEpoch ===\n synced.plan.sourceContentKeyBundle.contentKeyEpoch &&\n writerProjection.contentKeyBundle.linkSetManifestHash ===\n synced.plan.sourceContentKeyBundle.linkSetManifestHash &&\n writerProjection.contentKeyBundle.targetHash ===\n synced.plan.sourceContentKeyBundle.targetHash &&\n writerProjection.documentKekTargets.linkSetManifestHash ===\n synced.plan.documentKekTargets.linkSetManifestHash &&\n writerProjection.documentKekTargets.documentKeyTargetHash ===\n synced.plan.documentKekTargets.documentKeyTargetHash\n );\n}\n\nfunction resolveSyncedContainerMetadataWriterProjection(\n metadataState: ContainerMetadataState,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): DocumentWriterProjectionResponse | null {\n const writerProjection =\n synced.writerProjection ??\n (metadataState.metadataWriterProjection?.documentId ===\n synced.plan.documentId\n ? metadataState.metadataWriterProjection\n : null);\n return writerProjection &&\n documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection,\n synced,\n )\n ? writerProjection\n : null;\n}\n\n/**\n * Heals a stale metadata content-key bundle by rotating to a fresh content\n * key anchored by this full-history snapshot.\n */\nfunction metadataRotationSnapshotProvider(\n metadataState: ContainerMetadataState,\n): () => Promise<Uint8Array | null> {\n return async () => exportFullHistorySnapshot(metadataState.doc);\n}\n\ninterface SyncContainerMetadataStateInput {\n forceReadSync?: boolean | undefined;\n isCurrent: () => boolean;\n /**\n * Register sent ids before the network await so early self echoes cannot arm\n * a redundant read-sync. Shared with {@link listContainerMetadataDocumentUpdateIds}.\n */\n locallyAcceptedUpdateIds?: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n /** The sync pass's operation; its policy reads share one directory view. */\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerMetadataSyncRuntime;\n targetSecretKey: Uint8Array;\n}\n\nasync function requestContainerMetadataSync(input: {\n documentId: string;\n metadataState: ContainerMetadataState;\n pendingUpdates: readonly PendingUpdateRecord[];\n sentUpdateIds: string[];\n syncInput: SyncContainerMetadataStateInput;\n}): Promise<ContainerMetadataSyncAttempt | null> {\n const { metadataState, sentUpdateIds, syncInput } = input;\n const { isCurrent, persistence, runtime } = syncInput;\n return cleanupContainerMetadataRegistrationsOnFailure(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n () =>\n syncRemoteContainerMetadata({\n buildRotationSnapshot: metadataRotationSnapshotProvider(metadataState),\n containerId: metadataState.container.id,\n currentDocument: metadataState.doc,\n documentId: input.documentId,\n isCurrent,\n lastCommitLsn: metadataState.record.lastCommitLsn,\n localVersionVector: encodeVersionVector(metadataState.doc),\n onOutgoingUpdatesMaterialized: (updateIds) => {\n if (isCurrent()) {\n preRegisterMaterializedContainerMetadataUpdateIds(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n updateIds,\n );\n }\n },\n onPullContinuationInvalidated: (continuation) =>\n invalidateContainerMetadataPullContinuation({\n continuation,\n isCurrent,\n metadataState,\n persistence,\n runtime,\n }),\n pendingUpdates: input.pendingUpdates,\n persistedState: metadataState.record,\n policyOperation: syncInput.policyOperation,\n pullContinuation:\n currentMetadataPullContinuation(metadataState) ?? undefined,\n rekeyPendingUpdate: persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: syncInput.resolveProjectionUserKey,\n runtime,\n targetSecretKey: syncInput.targetSecretKey,\n writerProjection:\n metadataState.metadataWriterProjection?.documentId ===\n input.documentId\n ? metadataState.metadataWriterProjection\n : undefined,\n }),\n );\n}\n\nexport async function syncContainerMetadataState(\n input: SyncContainerMetadataStateInput,\n): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { persistence, runtime } = input;\n const liveMetadataState = input.metadataState;\n const { isCurrent } = input;\n if (!isCurrent()) {\n return null;\n }\n const { documentId } = liveMetadataState.record;\n if (!documentId) {\n return null;\n }\n const execSql = runtime.infra.execSql;\n\n const pendingUpdates = await persistence.listPendingUpdates(\n execSql,\n liveMetadataState.container.id,\n );\n if (!isCurrent()) {\n return null;\n }\n if (\n pendingUpdates.length === 0 &&\n currentMetadataPullContinuation(liveMetadataState) === null &&\n !liveMetadataState.record.pullContinuationRecoveryRequired &&\n !input.forceReadSync &&\n hasCurrentContainerMetadataReadState(liveMetadataState.record)\n ) {\n return null;\n }\n const metadataState =\n await createDetachedContainerMetadataState(liveMetadataState);\n if (!isCurrent()) {\n return null;\n }\n\n const sentUpdateIds: string[] = [];\n\n const syncAttempt = await requestContainerMetadataSync({\n documentId,\n metadataState,\n pendingUpdates,\n sentUpdateIds,\n syncInput: input,\n });\n if (!syncAttempt) {\n return null;\n }\n if (!isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n sentUpdateIds,\n [],\n );\n return null;\n }\n const finalized = await finalizeContainerMetadataSync({\n documentId,\n isCurrent,\n locallyAcceptedUpdateIds: input.locallyAcceptedUpdateIds,\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n persistence,\n runtime,\n sentUpdateIds,\n syncAttempt,\n });\n if (!isCurrent() || !finalized) {\n return null;\n }\n if (!(\"missing\" in finalized)) {\n installDetachedContainerMetadataState(liveMetadataState, metadataState, {\n preserveConcurrentMetadataEdit: true,\n });\n }\n return finalized;\n}\n\nasync function finalizeContainerMetadataSync(input: {\n documentId: string;\n isCurrent: () => boolean;\n locallyAcceptedUpdateIds: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n runtime: ContainerMetadataSyncRuntime;\n sentUpdateIds: readonly string[];\n syncAttempt: ContainerMetadataSyncAttempt;\n}): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { metadataState, syncAttempt } = input;\n const { outgoingUpdateCount, synced } = syncAttempt;\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n // An id sent but not accepted will never be echoed. Accepted ids stay\n // registered until their realtime echo consumes them.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n synced.response.acceptedOutgoingUpdateIds,\n );\n metadataState.metadataWriterProjection =\n resolveSyncedContainerMetadataWriterProjection(metadataState, synced);\n if (synced.decryptedUpdates.length > 0) {\n applyIncomingContainerMetadataUpdates(metadataState.doc, synced);\n }\n const persisted = await persistContainerMetadataStateFromRuntime({\n acceptedPendingUpdateIds: synced.settledPendingUpdateIds,\n clearSyncFailure: shouldClearDocumentSyncFailureAfterPass(\n synced,\n outgoingUpdateCount,\n ),\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation ?? null,\n record: syncAttempt.requestRecord,\n },\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n patch: {\n ...synced.persistedState,\n documentId: input.documentId,\n lastCommitLsn:\n synced.response.commitLsn ?? metadataState.record.lastCommitLsn ?? null,\n metadataDocumentId: input.documentId,\n pullContinuation: readPullContinuation(synced.response),\n },\n persistence: input.persistence,\n runtime: input.runtime,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n if (!persisted) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n return { missing: true };\n }\n metadataState.container = persisted.container;\n installContainerMetadataRecord(metadataState, persisted.record);\n if (persisted.pullContinuationSuperseded) {\n // The response's accepted IDs were not durably settled. Treat every\n // pre-registration as unapplied so an early echo cannot hide work that the\n // forced follow-up still needs to reconcile.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n }\n\n return {\n ...persisted,\n shouldRequestFollowupSync: shouldRequestContainerMetadataFollowup({\n persisted,\n settleOutgoingPass: () =>\n settleContainerMetadataOutgoingPass(metadataState, syncAttempt),\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,yBAAyB,GAC1B,MAAM,iBAAiB,CAAC;AAKzB,OAAO,EAAE,gCAAgC,EAAE,MAAM,6CAA6C,CAAC;AAC/F,OAAO,EACL,oBAAoB,EACpB,uCAAuC,GACxC,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,qCAAqC,EAAE,MAAM,mCAAmC,CAAC;AAC1F,OAAO,EACL,+BAA+B,EAC/B,oCAAoC,EACpC,8BAA8B,EAC9B,wCAAwC,GACzC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAGL,2BAA2B,GAC5B,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,oCAAoC,EACpC,qCAAqC,GACtC,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,sCAAsC,EAAE,MAAM,wBAAwB,CAAC;AAEhF,OAAO,EACL,uCAAuC,EACvC,sCAAsC,GACvC,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EACL,8BAA8B,EAC9B,wCAAwC,EACxC,uCAAuC,EACvC,wCAAwC,GACzC,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,2CAA2C,EAAE,MAAM,wCAAwC,CAAC;AACrG,OAAO,EACL,8CAA8C,EAC9C,2CAA2C,EAC3C,iDAAiD,GAClD,MAAM,6BAA6B,CAAC;AAOrC,OAAO,EACL,8CAA8C,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,\n} from \"@tearleads/loro\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport type { ProjectionUserKeyResolver } from \"../../../data/keyingProjectionVerification\";\nimport type { ContainerContentsPersistence } from \"../../../data/persistence/container-contents/containerContentsPersistence\";\nimport type { PendingUpdateRecord } from \"../../../data/persistence/documents/records\";\nimport { settleOutgoingPassAndDecideReArm } from \"../../../data/sync/outgoingUpdateSettlement\";\nimport {\n readPullContinuation,\n shouldClearDocumentSyncFailureAfterPass,\n} from \"../../documents\";\nimport type { PrincipalPolicyOperation } from \"../../principals/principalPolicyService\";\nimport { applyIncomingContainerMetadataUpdates } from \"./metadataIncomingUpdateIsolation\";\nimport {\n currentMetadataPullContinuation,\n hasCurrentContainerMetadataReadState,\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\nimport {\n type ContainerMetadataSyncAttempt,\n type ContainerMetadataSyncRuntime,\n syncRemoteContainerMetadata,\n} from \"./metadataRemoteSync\";\nimport {\n createDetachedContainerMetadataState,\n installDetachedContainerMetadataState,\n} from \"./metadataStateIsolation\";\nimport { shouldRequestContainerMetadataFollowup } from \"./metadataSyncFollowup\";\n\nexport {\n hasContainerMetadataDocumentUpdateEvent,\n listContainerMetadataDocumentUpdateIds,\n} from \"./metadataEvents\";\nexport {\n installContainerMetadataRecord,\n persistContainerMetadataStateFromRuntime,\n renameContainerMetadataStateFromRuntime,\n setContainerIconMetadataStateFromRuntime,\n} from \"./metadataPersistence\";\n\nimport { invalidateContainerMetadataPullContinuation } from \"./metadataPullContinuationInvalidation\";\nimport {\n cleanupContainerMetadataRegistrationsOnFailure,\n discardUnacceptedContainerMetadataUpdateIds,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nimport type {\n ContainerMetadataState,\n MissingContainerMetadataState,\n SyncedContainerMetadataState,\n} from \"./metadataTypes\";\n\nexport {\n cleanupContainerMetadataRegistrationsOnFailure,\n preRegisterMaterializedContainerMetadataUpdateIds,\n} from \"./metadataSyncRegistrations\";\nexport type { ContainerMetadataPatch } from \"./metadataTypes\";\n\nexport function settleContainerMetadataOutgoingPass(\n metadataState: ContainerMetadataState,\n attempt: ContainerMetadataSyncAttempt,\n): boolean {\n const shouldReArmOutgoing = settleOutgoingPassAndDecideReArm(metadataState, {\n exhaustedPendingUpdateCount: attempt.synced.exhaustedPendingUpdateCount,\n outgoingUpdateCount: attempt.outgoingUpdateCount,\n rekeyedUpdateCount: attempt.synced.rekeyedPendingUpdateIds.length,\n settledUpdateCount: attempt.synced.settledPendingUpdateIds.length,\n acceptedRecoveryBaseline: attempt.synced.acceptedRecoveryBaseline,\n });\n return (\n attempt.synced.hasDeferredPendingUpdates ||\n shouldReArmOutgoing ||\n attempt.synced.hasIncompletePull\n );\n}\n\nfunction documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection: DocumentWriterProjectionResponse,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): boolean {\n return (\n writerProjection.contentKeyBundle.contentKeyEpoch ===\n synced.plan.sourceContentKeyBundle.contentKeyEpoch &&\n writerProjection.contentKeyBundle.linkSetManifestHash ===\n synced.plan.sourceContentKeyBundle.linkSetManifestHash &&\n writerProjection.contentKeyBundle.targetHash ===\n synced.plan.sourceContentKeyBundle.targetHash &&\n writerProjection.documentKekTargets.linkSetManifestHash ===\n synced.plan.documentKekTargets.linkSetManifestHash &&\n writerProjection.documentKekTargets.documentKeyTargetHash ===\n synced.plan.documentKekTargets.documentKeyTargetHash\n );\n}\n\nfunction resolveSyncedContainerMetadataWriterProjection(\n metadataState: ContainerMetadataState,\n synced: ContainerMetadataSyncAttempt[\"synced\"],\n): DocumentWriterProjectionResponse | null {\n const writerProjection =\n synced.writerProjection ??\n (metadataState.metadataWriterProjection?.documentId ===\n synced.plan.documentId\n ? metadataState.metadataWriterProjection\n : null);\n return writerProjection &&\n documentWriterProjectionMatchesMetadataSyncResponse(\n writerProjection,\n synced,\n )\n ? writerProjection\n : null;\n}\n\n/**\n * Heals a stale metadata content-key bundle by rotating to a fresh content\n * key anchored by this full-history snapshot.\n */\nfunction metadataRotationSnapshotProvider(\n metadataState: ContainerMetadataState,\n): () => Promise<Uint8Array | null> {\n return async () => exportFullHistorySnapshot(metadataState.doc);\n}\n\ninterface SyncContainerMetadataStateInput {\n forceReadSync?: boolean | undefined;\n isCurrent: () => boolean;\n /**\n * Register sent ids before the network await so early self echoes cannot arm\n * a redundant read-sync. Shared with {@link listContainerMetadataDocumentUpdateIds}.\n */\n locallyAcceptedUpdateIds?: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n /** The sync pass's operation; its policy reads share one directory view. */\n policyOperation: PrincipalPolicyOperation;\n resolveProjectionUserKey: ProjectionUserKeyResolver;\n runtime: ContainerMetadataSyncRuntime;\n targetSecretKey: Uint8Array;\n}\n\nasync function requestContainerMetadataSync(input: {\n documentId: string;\n metadataState: ContainerMetadataState;\n pendingUpdates: readonly PendingUpdateRecord[];\n sentUpdateIds: string[];\n syncInput: SyncContainerMetadataStateInput;\n}): Promise<ContainerMetadataSyncAttempt | null> {\n const { metadataState, sentUpdateIds, syncInput } = input;\n const { isCurrent, persistence, runtime } = syncInput;\n return cleanupContainerMetadataRegistrationsOnFailure(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n () =>\n syncRemoteContainerMetadata({\n buildRotationSnapshot: metadataRotationSnapshotProvider(metadataState),\n containerId: metadataState.container.id,\n currentDocument: metadataState.doc,\n documentId: input.documentId,\n isCurrent,\n lastCommitLsn: metadataState.record.lastCommitLsn,\n localVersionVector: encodeVersionVector(metadataState.doc),\n onOutgoingUpdatesMaterialized: (updateIds) => {\n if (isCurrent()) {\n preRegisterMaterializedContainerMetadataUpdateIds(\n syncInput.locallyAcceptedUpdateIds,\n sentUpdateIds,\n updateIds,\n );\n }\n },\n onPullContinuationInvalidated: (continuation) =>\n invalidateContainerMetadataPullContinuation({\n continuation,\n isCurrent,\n metadataState,\n persistence,\n runtime,\n }),\n pendingUpdates: input.pendingUpdates,\n persistedState: metadataState.record,\n policyOperation: syncInput.policyOperation,\n pullContinuation:\n currentMetadataPullContinuation(metadataState) ?? undefined,\n rekeyPendingUpdate: persistence.rekeyPendingUpdate,\n resolveProjectionUserKey: syncInput.resolveProjectionUserKey,\n runtime,\n targetSecretKey: syncInput.targetSecretKey,\n writerProjection:\n metadataState.metadataWriterProjection?.documentId ===\n input.documentId\n ? metadataState.metadataWriterProjection\n : undefined,\n }),\n );\n}\n\nexport async function syncContainerMetadataState(\n input: SyncContainerMetadataStateInput,\n): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { persistence, runtime } = input;\n const liveMetadataState = input.metadataState;\n const { isCurrent } = input;\n if (!isCurrent()) {\n return null;\n }\n const { documentId } = liveMetadataState.record;\n if (!documentId) {\n return null;\n }\n const execSql = runtime.infra.execSql;\n\n const pendingUpdates = await persistence.listPendingUpdates(\n execSql,\n liveMetadataState.container.id,\n );\n if (!isCurrent()) {\n return null;\n }\n if (\n pendingUpdates.length === 0 &&\n currentMetadataPullContinuation(liveMetadataState) === null &&\n !liveMetadataState.record.pullContinuationRecoveryRequired &&\n !input.forceReadSync &&\n hasCurrentContainerMetadataReadState(liveMetadataState.record)\n ) {\n return null;\n }\n const metadataState =\n await createDetachedContainerMetadataState(liveMetadataState);\n if (!isCurrent()) {\n return null;\n }\n\n const sentUpdateIds: string[] = [];\n\n const syncAttempt = await requestContainerMetadataSync({\n documentId,\n metadataState,\n pendingUpdates,\n sentUpdateIds,\n syncInput: input,\n });\n if (!syncAttempt) {\n return null;\n }\n if (!isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n sentUpdateIds,\n [],\n );\n return null;\n }\n const finalized = await finalizeContainerMetadataSync({\n documentId,\n isCurrent,\n locallyAcceptedUpdateIds: input.locallyAcceptedUpdateIds,\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n persistence,\n runtime,\n sentUpdateIds,\n syncAttempt,\n });\n if (!isCurrent() || !finalized) {\n return null;\n }\n if (!(\"missing\" in finalized)) {\n installDetachedContainerMetadataState(liveMetadataState, metadataState, {\n preserveConcurrentMetadataEdit: true,\n });\n }\n return finalized;\n}\n\nasync function finalizeContainerMetadataSync(input: {\n documentId: string;\n isCurrent: () => boolean;\n locallyAcceptedUpdateIds: Set<string> | undefined;\n metadataState: ContainerMetadataState;\n onDurableStateNeedsReload?: (() => void) | undefined;\n persistence: ContainerContentsPersistence;\n runtime: ContainerMetadataSyncRuntime;\n sentUpdateIds: readonly string[];\n syncAttempt: ContainerMetadataSyncAttempt;\n}): Promise<\n SyncedContainerMetadataState | MissingContainerMetadataState | null\n> {\n const { metadataState, syncAttempt } = input;\n const { outgoingUpdateCount, synced } = syncAttempt;\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n // An id sent but not accepted will never be echoed. Accepted ids stay\n // registered until their realtime echo consumes them.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n synced.response.acceptedOutgoingUpdateIds,\n );\n metadataState.metadataWriterProjection =\n resolveSyncedContainerMetadataWriterProjection(metadataState, synced);\n if (synced.decryptedUpdates.length > 0) {\n applyIncomingContainerMetadataUpdates(metadataState.doc, synced);\n }\n const persisted = await persistContainerMetadataStateFromRuntime({\n acceptedPendingUpdateIds: synced.settledPendingUpdateIds,\n clearSyncFailure: shouldClearDocumentSyncFailureAfterPass(\n synced,\n outgoingUpdateCount,\n ),\n expectedSyncState: {\n pullContinuation: syncAttempt.consumedPullContinuation ?? null,\n record: syncAttempt.requestRecord,\n },\n metadataState,\n onDurableStateNeedsReload: input.onDurableStateNeedsReload,\n patch: {\n ...synced.persistedState,\n documentId: input.documentId,\n lastCommitLsn:\n synced.response.commitLsn ?? metadataState.record.lastCommitLsn ?? null,\n metadataDocumentId: input.documentId,\n pullContinuation: readPullContinuation(synced.response),\n },\n persistence: input.persistence,\n runtime: input.runtime,\n stillCurrent: input.isCurrent,\n });\n if (!input.isCurrent()) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n return null;\n }\n if (!persisted) {\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n return { missing: true };\n }\n metadataState.container = persisted.container;\n installContainerMetadataRecord(metadataState, persisted.record);\n if (persisted.pullContinuationSuperseded) {\n // The response's accepted IDs were not durably settled. Treat every\n // pre-registration as unapplied so an early echo cannot hide work that the\n // forced follow-up still needs to reconcile.\n discardUnacceptedContainerMetadataUpdateIds(\n input.locallyAcceptedUpdateIds,\n input.sentUpdateIds,\n [],\n );\n metadataState.metadataWriterProjection = null;\n }\n\n return {\n ...persisted,\n shouldRequestFollowupSync: shouldRequestContainerMetadataFollowup({\n persisted,\n settleOutgoingPass: () =>\n settleContainerMetadataOutgoingPass(metadataState, syncAttempt),\n }),\n };\n}\n"]}