@tearleads/client-sdk 0.1.79 → 0.1.81

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 (177) hide show
  1. package/client/deviceFirst/index.d.ts +1 -1
  2. package/client/deviceFirst/index.js +1 -1
  3. package/client/deviceFirst/index.js.map +1 -1
  4. package/client/runtime/principalMutationApi.js +1 -1
  5. package/client/runtime/principalMutationApi.js.map +1 -1
  6. package/client/runtime/principalMutationDispatch.js +1 -1
  7. package/client/runtime/principalMutationDispatch.js.map +1 -1
  8. package/client/runtime/rootContainerAdoption.js.map +1 -1
  9. package/client/runtime/workflowRuntime.d.ts +1 -1
  10. package/client/runtime/workflowRuntime.js.map +1 -1
  11. package/client/session/sessionPurgeRecovery.js +1 -1
  12. package/client/session/sessionPurgeRecovery.js.map +1 -1
  13. package/data/blobs/attachments/projection.js +2 -3
  14. package/data/blobs/attachments/projection.js.map +1 -1
  15. package/data/documents/documentConstants.d.ts +1 -0
  16. package/data/documents/documentConstants.js +1 -0
  17. package/data/documents/documentConstants.js.map +1 -1
  18. package/data/documents/shared/containerKek/containerKekEntryVerification.d.ts +3 -0
  19. package/data/documents/shared/containerKek/index.d.ts +5 -0
  20. package/data/documents/shared/containerKek/index.js +9 -0
  21. package/data/documents/shared/containerKek/index.js.map +1 -0
  22. package/data/documents/shared/projection/index.d.ts +1 -1
  23. package/data/documents/shared/projection/index.js +1 -1
  24. package/data/documents/shared/projection/index.js.map +1 -1
  25. package/data/documents/shared/sync/syncResponseAuthorization.js +1 -1
  26. package/data/documents/shared/sync/syncResponseAuthorization.js.map +1 -1
  27. package/data/keyingProjectionVerification/container/containerCreateManifest.d.ts +12 -0
  28. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +16 -0
  29. package/data/keyingProjectionVerification/index.d.ts +5 -0
  30. package/data/keyingProjectionVerification/index.js +6 -1
  31. package/data/keyingProjectionVerification/index.js.map +1 -1
  32. package/data/keyingProjectionVerification/principalPolicy/mergeProjectionPolicyEvidence.d.ts +3 -0
  33. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +1 -1
  34. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  35. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCheckpointSelection.d.ts +6 -0
  36. package/data/{persistence → keyingProjectionVerification}/principalPolicy/principalPolicyCheckpointSelection.js +1 -1
  37. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCheckpointSelection.js.map +1 -0
  38. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.d.ts +24 -0
  39. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +1 -1
  40. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  41. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js +1 -1
  42. package/data/keyingProjectionVerification/principalPolicy/resolvedPrincipalPolicy.js.map +1 -1
  43. package/data/persistence/container-contents/documentPlacement.js +1 -1
  44. package/data/persistence/container-contents/documentPlacement.js.map +1 -1
  45. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js +1 -1
  46. package/data/persistence/documents/containerDocumentTombstoneHoldsPersistence.js.map +1 -1
  47. package/data/persistence/documents/documentsPersistence.d.ts +1 -1
  48. package/data/persistence/documents/documentsPersistence.js +2 -3
  49. package/data/persistence/documents/documentsPersistence.js.map +1 -1
  50. package/data/persistence/documents/internal/containerDocumentTombstones.js +1 -1
  51. package/data/persistence/documents/internal/containerDocumentTombstones.js.map +1 -1
  52. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js +1 -1
  53. package/data/persistence/documents/internal/createDocumentWithHistoryCheckpoint.js.map +1 -1
  54. package/data/persistence/documents/internal/documentDeletionPersistence.js +1 -1
  55. package/data/persistence/documents/internal/documentDeletionPersistence.js.map +1 -1
  56. package/data/persistence/documents/internal/documentMutationPersistence.js +1 -1
  57. package/data/persistence/documents/internal/documentMutationPersistence.js.map +1 -1
  58. package/data/persistence/documents/internal/documentProjectionRows.js +1 -2
  59. package/data/persistence/documents/internal/documentProjectionRows.js.map +1 -1
  60. package/data/persistence/documents/internal/documentPullContinuationPersistence.js +1 -1
  61. package/data/persistence/documents/internal/documentPullContinuationPersistence.js.map +1 -1
  62. package/data/persistence/documents/internal/documentRows.js +1 -2
  63. package/data/persistence/documents/internal/documentRows.js.map +1 -1
  64. package/data/persistence/documents/internal/orphanSideRows.js +1 -1
  65. package/data/persistence/documents/internal/orphanSideRows.js.map +1 -1
  66. package/data/persistence/documents/internal/pendingCreateAdoption.js +1 -1
  67. package/data/persistence/documents/internal/pendingCreateAdoption.js.map +1 -1
  68. package/data/persistence/documents/internal/rowQueryPersistence.js +1 -1
  69. package/data/persistence/documents/internal/rowQueryPersistence.js.map +1 -1
  70. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js +11 -51
  71. package/data/persistence/keyingCheckpoints/keyingCheckpointAdvancePersistence.js.map +1 -1
  72. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.d.ts +1 -30
  73. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js +4 -85
  74. package/data/persistence/keyingCheckpoints/locallyAcknowledgedCheckpointPersistence.js.map +1 -1
  75. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js +88 -0
  76. package/data/persistence/principalPolicy/locallyAcknowledgedPrincipalPolicyPersistence.js.map +1 -0
  77. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js +53 -0
  78. package/data/persistence/principalPolicy/verifiedPrincipalPolicyBundlePersistence.js.map +1 -0
  79. package/package.json +1 -1
  80. package/stores/local-projection/localProjectionStore.d.ts +1 -1
  81. package/stores/local-projection/localProjectionStore.js +1 -1
  82. package/stores/local-projection/localProjectionStore.js.map +1 -1
  83. package/stores/local-projection/registry.d.ts +1 -1
  84. package/stores/local-projection/registry.js.map +1 -1
  85. package/stores/local-projection/types.d.ts +1 -1
  86. package/stores/local-projection/types.js.map +1 -1
  87. package/workflows/blobs/hydration/decrypt.js +1 -2
  88. package/workflows/blobs/hydration/decrypt.js.map +1 -1
  89. package/workflows/blobs/hydration/hydrate.d.ts +1 -1
  90. package/workflows/blobs/hydration/hydrate.js.map +1 -1
  91. package/workflows/container-contents/container-state/create/createAdoption.js +1 -2
  92. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  93. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +1 -1
  94. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  95. package/workflows/container-contents/info/documentInfo.js +1 -1
  96. package/workflows/container-contents/info/documentInfo.js.map +1 -1
  97. package/workflows/container-contents/metadata/index.js +1 -2
  98. package/workflows/container-contents/metadata/index.js.map +1 -1
  99. package/workflows/container-contents/metadata/metadataMutationPreparation.js +1 -1
  100. package/workflows/container-contents/metadata/metadataMutationPreparation.js.map +1 -1
  101. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js +1 -1
  102. package/workflows/container-contents/metadata/metadataPullContinuationInvalidation.js.map +1 -1
  103. package/workflows/container-contents/metadata/metadataSyncErrors.js +1 -1
  104. package/workflows/container-contents/metadata/metadataSyncErrors.js.map +1 -1
  105. package/workflows/container-contents/metadata/metadataSyncSettlement.d.ts +1 -1
  106. package/workflows/container-contents/metadata/metadataSyncSettlement.js.map +1 -1
  107. package/workflows/container-contents/metadata/metadataTypes.d.ts +1 -1
  108. package/workflows/container-contents/metadata/metadataTypes.js.map +1 -1
  109. package/workflows/container-contents/pendingWrites/index.js +1 -1
  110. package/workflows/container-contents/pendingWrites/index.js.map +1 -1
  111. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +1 -3
  112. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  113. package/workflows/containers/child/create/index.js +1 -1
  114. package/workflows/containers/child/create/index.js.map +1 -1
  115. package/workflows/containers/child/move/moveRotation.js +1 -1
  116. package/workflows/containers/child/move/moveRotation.js.map +1 -1
  117. package/workflows/containers/child/move/moveWraps.js +1 -1
  118. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  119. package/workflows/containers/child/rekey/rekeyProjection.js +1 -1
  120. package/workflows/containers/child/rekey/rekeyProjection.js.map +1 -1
  121. package/workflows/containers/child/rotation/rotationContext.js +1 -2
  122. package/workflows/containers/child/rotation/rotationContext.js.map +1 -1
  123. package/workflows/containers/child/share/shareAncestorRepair.js +1 -2
  124. package/workflows/containers/child/share/shareAncestorRepair.js.map +1 -1
  125. package/workflows/containers/index.d.ts +2 -3
  126. package/workflows/containers/index.js +1 -2
  127. package/workflows/containers/index.js.map +1 -1
  128. package/workflows/containers/writeRefusal.js +1 -1
  129. package/workflows/containers/writeRefusal.js.map +1 -1
  130. package/workflows/documents/linkSet/linkSetProjectionSeed.js +1 -1
  131. package/workflows/documents/linkSet/linkSetProjectionSeed.js.map +1 -1
  132. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js +1 -1
  133. package/workflows/documents/syncRekeys/syncAutomaticContainerRekeys.js.map +1 -1
  134. package/workflows/organizations/groupMetadata/groupMetadataAccess.js +1 -1
  135. package/workflows/organizations/groupMetadata/groupMetadataAccess.js.map +1 -1
  136. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js +2 -2
  137. package/workflows/organizations/groupPolicy/groupPolicyMutationContext.js.map +1 -1
  138. package/workflows/organizations/groups/deleteOrganizationGroup.js +1 -1
  139. package/workflows/organizations/groups/deleteOrganizationGroup.js.map +1 -1
  140. package/workflows/organizations/groups/organizationGroupDirectory.js +1 -1
  141. package/workflows/organizations/groups/organizationGroupDirectory.js.map +1 -1
  142. package/workflows/organizations/provisioning/createOrganization.d.ts +1 -1
  143. package/workflows/organizations/provisioning/createOrganization.js +1 -1
  144. package/workflows/organizations/provisioning/createOrganization.js.map +1 -1
  145. package/workflows/organizations/provisioning/organizationProvisioningAttempt.d.ts +1 -1
  146. package/workflows/organizations/provisioning/organizationProvisioningAttempt.js.map +1 -1
  147. package/workflows/organizations/readModel/listLocalOrganizations.js +1 -1
  148. package/workflows/organizations/readModel/listLocalOrganizations.js.map +1 -1
  149. package/workflows/principals/externalAdminPolicy.js +1 -1
  150. package/workflows/principals/externalAdminPolicy.js.map +1 -1
  151. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js +1 -1
  152. package/workflows/principals/policyCache/principalPolicyCacheAdvance.js.map +1 -1
  153. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js +1 -1
  154. package/workflows/principals/policyCache/principalPolicyOrganizationScope.js.map +1 -1
  155. package/workflows/registration/index.d.ts +2 -1
  156. package/workflows/registration/index.js +2 -1
  157. package/workflows/registration/index.js.map +1 -1
  158. package/workflows/registration/organizationProvisioning.d.ts +39 -0
  159. package/workflows/registration/organizationProvisioning.js +211 -0
  160. package/workflows/registration/organizationProvisioning.js.map +1 -0
  161. package/workflows/registration/organizationProvisioningArtifacts.d.ts +2 -3
  162. package/workflows/registration/organizationProvisioningArtifacts.js.map +1 -1
  163. package/workflows/registration/provisioningBootstrapBuilders.d.ts +3 -3
  164. package/workflows/registration/provisioningBootstrapBuilders.js +3 -4
  165. package/workflows/registration/provisioningBootstrapBuilders.js.map +1 -1
  166. package/workflows/registration/registerIdentity.d.ts +2 -39
  167. package/workflows/registration/registerIdentity.js +2 -207
  168. package/workflows/registration/registerIdentity.js.map +1 -1
  169. package/workflows/registration/registrationPrincipalPolicyPersistence.js +1 -1
  170. package/workflows/registration/registrationPrincipalPolicyPersistence.js.map +1 -1
  171. package/workflows/sync/remoteResetPlans.js +2 -2
  172. package/workflows/sync/remoteResetPlans.js.map +1 -1
  173. package/data/persistence/documents/internal/constants.d.ts +0 -1
  174. package/data/persistence/documents/internal/constants.js +0 -2
  175. package/data/persistence/documents/internal/constants.js.map +0 -1
  176. package/data/persistence/principalKeys/principalGrantRetirementPersistence.d.ts +0 -9
  177. package/data/persistence/principalPolicy/principalPolicyCheckpointSelection.js.map +0 -1
@@ -4,7 +4,7 @@ import { type DocumentWriterProjectionAuthorization, type PrincipalPolicyCache }
4
4
  import type { ExecSql } from "../../../sqlite/sqlSchema.js";
5
5
  export { unwrapContainerKekPath } from "../containerKek/containerKekPath.js";
6
6
  export { ContainerKekHistoryUnavailableError } from "../containerKek/containerKekPathHistory.js";
7
- export { buildRotatedDocumentContentKeyBundle, collectContainerKeksForDocumentSync, DocumentContentKeyUnavailableError, DocumentHistoryUnavailableError, unwrapDocumentContentKeyFromBundle, unwrapDocumentContentKeyFromWriterProjection, unwrapDocumentContentKeyTarget, wrapDocumentContentKeyForCreate, } from "./projectionContentKeys.js";
7
+ export { buildRotatedDocumentContentKeyBundle, collectContainerKeksForDocumentSync, DocumentContentKeyUnavailableError, DocumentHistoryUnavailableError, unwrapContentKeyTargetForKind, unwrapDocumentContentKeyFromBundle, unwrapDocumentContentKeyFromWriterProjection, unwrapDocumentContentKeyTarget, wrapDocumentContentKeyForCreate, } from "./projectionContentKeys.js";
8
8
  export { authorizingContainerPathRefs, authorizingContainerPathRefsForLinkSet, containerPathRefs, currentDocumentTargets, deriveDocumentCreateTargets, deriveDocumentTargetFromProjection, mergeTargetEnvelopes, readLinkedContainerIdsFromDocumentManifest, verifiedDocumentWrapTargets, } from "./projectionTargets.js";
9
9
  import type { ProjectionVerificationOptions } from "../types.js";
10
10
  declare function assertDocumentWriterProjectionConsistentInternal(writerProjection: DocumentWriterProjectionResponse, input: ProjectionVerificationOptions & {
@@ -6,7 +6,7 @@ import { assertDocumentManifestBundleConsistent, normalizeDocumentKekTargetRespo
6
6
  import { currentDocumentTargets, deriveDocumentTargetFromProjection, readLinkedContainerIdsFromDocumentManifest, } from "./projectionTargets.js";
7
7
  export { unwrapContainerKekPath } from "../containerKek/containerKekPath.js";
8
8
  export { ContainerKekHistoryUnavailableError } from "../containerKek/containerKekPathHistory.js";
9
- export { buildRotatedDocumentContentKeyBundle, collectContainerKeksForDocumentSync, DocumentContentKeyUnavailableError, DocumentHistoryUnavailableError, unwrapDocumentContentKeyFromBundle, unwrapDocumentContentKeyFromWriterProjection, unwrapDocumentContentKeyTarget, wrapDocumentContentKeyForCreate, } from "./projectionContentKeys.js";
9
+ export { buildRotatedDocumentContentKeyBundle, collectContainerKeksForDocumentSync, DocumentContentKeyUnavailableError, DocumentHistoryUnavailableError, unwrapContentKeyTargetForKind, unwrapDocumentContentKeyFromBundle, unwrapDocumentContentKeyFromWriterProjection, unwrapDocumentContentKeyTarget, wrapDocumentContentKeyForCreate, } from "./projectionContentKeys.js";
10
10
  export { authorizingContainerPathRefs, authorizingContainerPathRefsForLinkSet, containerPathRefs, currentDocumentTargets, deriveDocumentCreateTargets, deriveDocumentTargetFromProjection, mergeTargetEnvelopes, readLinkedContainerIdsFromDocumentManifest, verifiedDocumentWrapTargets, } from "./projectionTargets.js";
11
11
  import { resolveProjectionVerifier } from "../types.js";
12
12
  function assertSortedStringsEqual(left, right, message) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAGL,2CAA2C,GAC5C,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AAClG,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,OAAO,EACL,sCAAsC,EACtC,kCAAkC,EAClC,mBAAmB,EACnB,uBAAuB,EACvB,SAAS,EACT,mBAAmB,GACpB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,sBAAsB,EACtB,kCAAkC,EAClC,0CAA0C,GAC3C,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,sBAAsB,EAAE,MAAM,kCAAkC,CAAC;AAC1E,OAAO,EAAE,mCAAmC,EAAE,MAAM,yCAAyC,CAAC;AAC9F,OAAO,EACL,oCAAoC,EACpC,mCAAmC,EACnC,kCAAkC,EAClC,+BAA+B,EAC/B,kCAA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C,gBAAgB,CAAC,kBAAkB,CAAC;QACzE,CAAC,CAAC,sBAAsB,CAAC,gBAAgB,CAAC,CAAC;IAC7C,MAAM,mBAAmB,GACvB,MAAM,mCAAmC,CAAC,OAAO,CAAC,CAAC;IACrD,IACE,mBAAmB;QACnB,gBAAgB,CAAC,kBAAkB,CAAC,qBAAqB,EACzD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IAC7E,CAAC;IAED,0CAA0C,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAC;IACtE,mDAAmD,CAAC;QAClD,OAAO;QACP,gBAAgB;KACjB,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,GAAG,KAA0E;IAE7E,IAAI,CAAC;QACH,OAAO,MAAM,gDAAgD,CAAC,GAAG,KAAK,CAAC,CAAC;IAC1E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n type DocumentWriterProjectionAuthorization,\n type PrincipalPolicyCache,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../keyingProjectionVerification\";\nimport { throwKeyingVerificationShapeFailure } from \"../../../keyingProjectionVerification/error\";\nimport { errorMessage } from \"../../../shared/errorMessage\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n assertDocumentManifestBundleConsistent,\n normalizeDocumentKekTargetResponse,\n sortDocumentTargets,\n targetEnvelopeReference,\n targetKey,\n uniqueSortedStrings,\n} from \"../readers\";\nimport {\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"./projectionTargets\";\n\nexport { unwrapContainerKekPath } from \"../containerKek/containerKekPath\";\nexport { ContainerKekHistoryUnavailableError } from \"../containerKek/containerKekPathHistory\";\nexport {\n buildRotatedDocumentContentKeyBundle,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapDocumentContentKeyFromBundle,\n unwrapDocumentContentKeyFromWriterProjection,\n unwrapDocumentContentKeyTarget,\n wrapDocumentContentKeyForCreate,\n} from \"./projectionContentKeys\";\nexport {\n authorizingContainerPathRefs,\n authorizingContainerPathRefsForLinkSet,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentCreateTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n verifiedDocumentWrapTargets,\n} from \"./projectionTargets\";\n\nimport type { ProjectionVerificationOptions } from \"../types\";\nimport { resolveProjectionVerifier } from \"../types\";\n\nfunction assertSortedStringsEqual(\n left: readonly string[],\n right: readonly string[],\n message: string,\n): void {\n if (\n left.length !== right.length ||\n left.some((value, index) => value !== right[index])\n ) {\n throw new Error(message);\n }\n}\n\nfunction assertAuthorizingContainerPathsMatchDocumentTargets(input: {\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}): void {\n if (input.writerProjection.authorizingContainerPaths.length === 0) {\n throw new Error(\"Document writer projection authorization paths missing\");\n }\n\n const targetKeys = new Set(input.targets.map(targetKey));\n for (const [\n index,\n projection,\n ] of input.writerProjection.authorizingContainerPaths.entries()) {\n let projectionTarget: DocumentContentKeyTarget;\n try {\n projectionTarget = deriveDocumentTargetFromProjection(projection);\n } catch (error) {\n throw new Error(\n `Document writer projection authorization path[${index}] is invalid: ${errorMessage(error)}`,\n );\n }\n\n if (targetKeys.has(targetKey(projectionTarget))) {\n continue;\n }\n\n // Bind server-supplied KEK paths to committed document targets before\n // using any unwrapped path KEK for document content-key material.\n throw new Error(\n `Document writer projection authorization path[${index}] is not a document target`,\n );\n }\n}\n\nfunction assertDocumentTargetsCoverLinkedContainers(\n targets: readonly DocumentContentKeyTarget[],\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n // One target per linked container: a second epoch for the same container\n // would let a re-wrap land on a KEK a revoked member still holds.\n if (\n new Set(targets.map((target) => target.containerId)).size !== targets.length\n ) {\n throw new Error(\n \"Document writer projection targets name a linked container more than once\",\n );\n }\n assertSortedStringsEqual(\n uniqueSortedStrings(targets.map((target) => target.containerId)),\n readLinkedContainerIdsFromDocumentManifest(writerProjection),\n \"Document writer projection targets do not match linked containers\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerManifestHashes,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerManifestHash)),\n \"Document writer projection target manifest summary mismatch\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerKeyEpochIds,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerKeyEpochId)),\n \"Document writer projection target KEK summary mismatch\",\n );\n}\n\nasync function assertProjectionContentKeyBundleConsistent(\n writerProjection: DocumentWriterProjectionResponse,\n staleContentKeyBundle: boolean,\n): Promise<void> {\n const { manifestHash } = writerProjection.documentManifest;\n if (writerProjection.contentKeyBundle.linkSetManifestHash !== manifestHash) {\n // A stale bundle may lag the link-set head, but it must still descend\n // from this document's manifest chain.\n if (\n !staleContentKeyBundle ||\n !writerProjection.documentManifestHistory.some(\n (bundle) =>\n bundle.manifestHash ===\n writerProjection.contentKeyBundle.linkSetManifestHash,\n )\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n }\n\n if (!staleContentKeyBundle) {\n if (\n writerProjection.documentKekTargets.documentKeyTargetHash !==\n writerProjection.contentKeyBundle.targetHash\n ) {\n throw new Error(\"Document writer projection target hash mismatch\");\n }\n return;\n }\n\n // The stale bundle cannot match the current targets; pin it to its own\n // canonical hash instead so a tampered envelope set still fails closed.\n const staleBundleTargetHash = await computeDocumentContentKeyTargetHash(\n sortDocumentTargets(\n writerProjection.contentKeyBundle.targets.map(targetEnvelopeReference),\n ),\n );\n if (staleBundleTargetHash !== writerProjection.contentKeyBundle.targetHash) {\n throw new Error(\n \"Document writer projection stale bundle target hash is not canonical\",\n );\n }\n}\n\nasync function assertDocumentWriterProjectionConsistentInternal(\n writerProjection: DocumentWriterProjectionResponse,\n input: ProjectionVerificationOptions & {\n /**\n * Accept a projection whose content-key bundle is marked stale (wrapped\n * to superseded KEK targets after e.g. a revoke rotation). Document sync\n * opts in to heal the bundle. Attachment reads opt in because their DEK\n * is independent and opens through verified retained container KEKs.\n */\n allowStaleContentKeyBundle?: boolean | undefined;\n execSql?: ExecSql | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n onVerifiedAuthorization?:\n | ((authorization: DocumentWriterProjectionAuthorization) => void)\n | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n stillCurrent?: (() => boolean) | undefined;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n },\n): Promise<DocumentContentKeyTarget[]> {\n const resolveProjectionUserKey = resolveProjectionVerifier(\n input,\n \"Document writer projection\",\n );\n if (\n input.trustedLocalProjection !== true &&\n resolveProjectionUserKey !== null\n ) {\n const authorization = await verifyDocumentWriterProjectionAuthorization({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: writerProjection,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n input.onVerifiedAuthorization?.(authorization);\n }\n\n const staleContentKeyBundle = writerProjection.contentKeyBundleStale === true;\n if (staleContentKeyBundle && input.allowStaleContentKeyBundle !== true) {\n throw new Error(\"Document writer projection content-key bundle is stale\");\n }\n\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: writerProjection.documentManifest,\n label: \"Document writer projection manifest\",\n });\n const { documentId } = manifestIdentity;\n if (\n writerProjection.documentId !== documentId ||\n writerProjection.documentKekTargets.documentId !== documentId ||\n writerProjection.contentKeyBundle.documentId !== documentId\n ) {\n throw new Error(\"Document writer projection document id mismatch\");\n }\n if (\n writerProjection.documentKekTargets.linkSetManifestHash !==\n writerProjection.documentManifest.manifestHash\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n await assertProjectionContentKeyBundleConsistent(\n writerProjection,\n staleContentKeyBundle,\n );\n\n const targets = staleContentKeyBundle\n ? normalizeDocumentKekTargetResponse(writerProjection.documentKekTargets)\n : currentDocumentTargets(writerProjection);\n const canonicalTargetHash =\n await computeDocumentContentKeyTargetHash(targets);\n if (\n canonicalTargetHash !==\n writerProjection.documentKekTargets.documentKeyTargetHash\n ) {\n throw new Error(\"Document writer projection target hash is not canonical\");\n }\n\n assertDocumentTargetsCoverLinkedContainers(targets, writerProjection);\n assertAuthorizingContainerPathsMatchDocumentTargets({\n targets,\n writerProjection,\n });\n\n return targets;\n}\n\nexport async function assertDocumentWriterProjectionConsistent(\n ...input: Parameters<typeof assertDocumentWriterProjectionConsistentInternal>\n): ReturnType<typeof assertDocumentWriterProjectionConsistentInternal> {\n try {\n return await assertDocumentWriterProjectionConsistentInternal(...input);\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,mCAAmC,EAAE,MAAM,mBAAmB,CAAC;AAExE,OAAO,EAGL,2CAA2C,GAC5C,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EAAE,mCAAmC,EAAE,MAAM,6CAA6C,CAAC;AAClG,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,OAAO,EACL,sCAAsC,EACtC,kCAAkC,EAClC,mBAAmB,EACnB,uBAAuB,EACvB,SAAS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,CAAC,iDAAiD,CAAC,CAAC;IACrE,CAAC;IACD,IACE,gBAAgB,CAAC,kBAAkB,CAAC,mBAAmB;QACvD,gBAAgB,CAAC,gBAAgB,CAAC,YAAY,EAC9C,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,CAAC;IACD,MAAM,0CAA0C,CAC9C,gBAAgB,EAChB,qBAAqB,CACtB,CAAC;IAEF,MAAM,OAAO,GAAG,qBAAqB;QACnC,CAAC,CAAC,kCAAkC,CAAC,gBAAgB,CAAC,kBAAkB,CAAC;QACzE,CAAC,CAAC,sBAAsB,CAAC,gBAAgB,CAAC,CAAC;IAC7C,MAAM,mBAAmB,GACvB,MAAM,mCAAmC,CAAC,OAAO,CAAC,CAAC;IACrD,IACE,mBAAmB;QACnB,gBAAgB,CAAC,kBAAkB,CAAC,qBAAqB,EACzD,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IAC7E,CAAC;IAED,0CAA0C,CAAC,OAAO,EAAE,gBAAgB,CAAC,CAAC;IACtE,mDAAmD,CAAC;QAClD,OAAO;QACP,gBAAgB;KACjB,CAAC,CAAC;IAEH,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,wCAAwC,CAC5D,GAAG,KAA0E;IAE7E,IAAI,CAAC;QACH,OAAO,MAAM,gDAAgD,CAAC,GAAG,KAAK,CAAC,CAAC;IAC1E,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n DocumentContentKeyTarget,\n VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport { computeDocumentContentKeyTargetHash } from \"@tearleads/crypto\";\nimport type { DocumentWriterProjectionResponse } from \"@tearleads/validators/response\";\nimport {\n type DocumentWriterProjectionAuthorization,\n type PrincipalPolicyCache,\n verifyDocumentWriterProjectionAuthorization,\n} from \"../../../keyingProjectionVerification\";\nimport { throwKeyingVerificationShapeFailure } from \"../../../keyingProjectionVerification/error\";\nimport { errorMessage } from \"../../../shared/errorMessage\";\nimport type { ExecSql } from \"../../../sqlite/sqlSchema\";\nimport {\n assertDocumentManifestBundleConsistent,\n normalizeDocumentKekTargetResponse,\n sortDocumentTargets,\n targetEnvelopeReference,\n targetKey,\n uniqueSortedStrings,\n} from \"../readers\";\nimport {\n currentDocumentTargets,\n deriveDocumentTargetFromProjection,\n readLinkedContainerIdsFromDocumentManifest,\n} from \"./projectionTargets\";\n\nexport { unwrapContainerKekPath } from \"../containerKek/containerKekPath\";\nexport { ContainerKekHistoryUnavailableError } from \"../containerKek/containerKekPathHistory\";\nexport {\n buildRotatedDocumentContentKeyBundle,\n collectContainerKeksForDocumentSync,\n DocumentContentKeyUnavailableError,\n DocumentHistoryUnavailableError,\n unwrapContentKeyTargetForKind,\n unwrapDocumentContentKeyFromBundle,\n unwrapDocumentContentKeyFromWriterProjection,\n unwrapDocumentContentKeyTarget,\n wrapDocumentContentKeyForCreate,\n} from \"./projectionContentKeys\";\nexport {\n authorizingContainerPathRefs,\n authorizingContainerPathRefsForLinkSet,\n containerPathRefs,\n currentDocumentTargets,\n deriveDocumentCreateTargets,\n deriveDocumentTargetFromProjection,\n mergeTargetEnvelopes,\n readLinkedContainerIdsFromDocumentManifest,\n verifiedDocumentWrapTargets,\n} from \"./projectionTargets\";\n\nimport type { ProjectionVerificationOptions } from \"../types\";\nimport { resolveProjectionVerifier } from \"../types\";\n\nfunction assertSortedStringsEqual(\n left: readonly string[],\n right: readonly string[],\n message: string,\n): void {\n if (\n left.length !== right.length ||\n left.some((value, index) => value !== right[index])\n ) {\n throw new Error(message);\n }\n}\n\nfunction assertAuthorizingContainerPathsMatchDocumentTargets(input: {\n targets: readonly DocumentContentKeyTarget[];\n writerProjection: DocumentWriterProjectionResponse;\n}): void {\n if (input.writerProjection.authorizingContainerPaths.length === 0) {\n throw new Error(\"Document writer projection authorization paths missing\");\n }\n\n const targetKeys = new Set(input.targets.map(targetKey));\n for (const [\n index,\n projection,\n ] of input.writerProjection.authorizingContainerPaths.entries()) {\n let projectionTarget: DocumentContentKeyTarget;\n try {\n projectionTarget = deriveDocumentTargetFromProjection(projection);\n } catch (error) {\n throw new Error(\n `Document writer projection authorization path[${index}] is invalid: ${errorMessage(error)}`,\n );\n }\n\n if (targetKeys.has(targetKey(projectionTarget))) {\n continue;\n }\n\n // Bind server-supplied KEK paths to committed document targets before\n // using any unwrapped path KEK for document content-key material.\n throw new Error(\n `Document writer projection authorization path[${index}] is not a document target`,\n );\n }\n}\n\nfunction assertDocumentTargetsCoverLinkedContainers(\n targets: readonly DocumentContentKeyTarget[],\n writerProjection: DocumentWriterProjectionResponse,\n): void {\n // One target per linked container: a second epoch for the same container\n // would let a re-wrap land on a KEK a revoked member still holds.\n if (\n new Set(targets.map((target) => target.containerId)).size !== targets.length\n ) {\n throw new Error(\n \"Document writer projection targets name a linked container more than once\",\n );\n }\n assertSortedStringsEqual(\n uniqueSortedStrings(targets.map((target) => target.containerId)),\n readLinkedContainerIdsFromDocumentManifest(writerProjection),\n \"Document writer projection targets do not match linked containers\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerManifestHashes,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerManifestHash)),\n \"Document writer projection target manifest summary mismatch\",\n );\n assertSortedStringsEqual(\n uniqueSortedStrings(\n writerProjection.documentKekTargets.linkedContainerKeyEpochIds,\n ),\n uniqueSortedStrings(targets.map((target) => target.containerKeyEpochId)),\n \"Document writer projection target KEK summary mismatch\",\n );\n}\n\nasync function assertProjectionContentKeyBundleConsistent(\n writerProjection: DocumentWriterProjectionResponse,\n staleContentKeyBundle: boolean,\n): Promise<void> {\n const { manifestHash } = writerProjection.documentManifest;\n if (writerProjection.contentKeyBundle.linkSetManifestHash !== manifestHash) {\n // A stale bundle may lag the link-set head, but it must still descend\n // from this document's manifest chain.\n if (\n !staleContentKeyBundle ||\n !writerProjection.documentManifestHistory.some(\n (bundle) =>\n bundle.manifestHash ===\n writerProjection.contentKeyBundle.linkSetManifestHash,\n )\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n }\n\n if (!staleContentKeyBundle) {\n if (\n writerProjection.documentKekTargets.documentKeyTargetHash !==\n writerProjection.contentKeyBundle.targetHash\n ) {\n throw new Error(\"Document writer projection target hash mismatch\");\n }\n return;\n }\n\n // The stale bundle cannot match the current targets; pin it to its own\n // canonical hash instead so a tampered envelope set still fails closed.\n const staleBundleTargetHash = await computeDocumentContentKeyTargetHash(\n sortDocumentTargets(\n writerProjection.contentKeyBundle.targets.map(targetEnvelopeReference),\n ),\n );\n if (staleBundleTargetHash !== writerProjection.contentKeyBundle.targetHash) {\n throw new Error(\n \"Document writer projection stale bundle target hash is not canonical\",\n );\n }\n}\n\nasync function assertDocumentWriterProjectionConsistentInternal(\n writerProjection: DocumentWriterProjectionResponse,\n input: ProjectionVerificationOptions & {\n /**\n * Accept a projection whose content-key bundle is marked stale (wrapped\n * to superseded KEK targets after e.g. a revoke rotation). Document sync\n * opts in to heal the bundle. Attachment reads opt in because their DEK\n * is independent and opens through verified retained container KEKs.\n */\n allowStaleContentKeyBundle?: boolean | undefined;\n execSql?: ExecSql | undefined;\n persistVerificationCheckpoints?: boolean | undefined;\n onVerifiedAuthorization?:\n | ((authorization: DocumentWriterProjectionAuthorization) => void)\n | undefined;\n principalPolicyCache?: PrincipalPolicyCache | undefined;\n stillCurrent?: (() => boolean) | undefined;\n verifiedByHash?: Map<string, VerifiedContainerAccessManifest> | undefined;\n },\n): Promise<DocumentContentKeyTarget[]> {\n const resolveProjectionUserKey = resolveProjectionVerifier(\n input,\n \"Document writer projection\",\n );\n if (\n input.trustedLocalProjection !== true &&\n resolveProjectionUserKey !== null\n ) {\n const authorization = await verifyDocumentWriterProjectionAuthorization({\n execSql: input.execSql,\n persistVerificationCheckpoints: input.persistVerificationCheckpoints,\n principalPolicyCache: input.principalPolicyCache,\n projection: writerProjection,\n resolveUserKey: resolveProjectionUserKey,\n stillCurrent: input.stillCurrent,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n input.onVerifiedAuthorization?.(authorization);\n }\n\n const staleContentKeyBundle = writerProjection.contentKeyBundleStale === true;\n if (staleContentKeyBundle && input.allowStaleContentKeyBundle !== true) {\n throw new Error(\"Document writer projection content-key bundle is stale\");\n }\n\n const manifestIdentity = await assertDocumentManifestBundleConsistent({\n bundle: writerProjection.documentManifest,\n label: \"Document writer projection manifest\",\n });\n const { documentId } = manifestIdentity;\n if (\n writerProjection.documentId !== documentId ||\n writerProjection.documentKekTargets.documentId !== documentId ||\n writerProjection.contentKeyBundle.documentId !== documentId\n ) {\n throw new Error(\"Document writer projection document id mismatch\");\n }\n if (\n writerProjection.documentKekTargets.linkSetManifestHash !==\n writerProjection.documentManifest.manifestHash\n ) {\n throw new Error(\"Document writer projection link manifest mismatch\");\n }\n await assertProjectionContentKeyBundleConsistent(\n writerProjection,\n staleContentKeyBundle,\n );\n\n const targets = staleContentKeyBundle\n ? normalizeDocumentKekTargetResponse(writerProjection.documentKekTargets)\n : currentDocumentTargets(writerProjection);\n const canonicalTargetHash =\n await computeDocumentContentKeyTargetHash(targets);\n if (\n canonicalTargetHash !==\n writerProjection.documentKekTargets.documentKeyTargetHash\n ) {\n throw new Error(\"Document writer projection target hash is not canonical\");\n }\n\n assertDocumentTargetsCoverLinkedContainers(targets, writerProjection);\n assertAuthorizingContainerPathsMatchDocumentTargets({\n targets,\n writerProjection,\n });\n\n return targets;\n}\n\nexport async function assertDocumentWriterProjectionConsistent(\n ...input: Parameters<typeof assertDocumentWriterProjectionConsistentInternal>\n): ReturnType<typeof assertDocumentWriterProjectionConsistentInternal> {\n try {\n return await assertDocumentWriterProjectionConsistentInternal(...input);\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { computeDocumentContentKeyTargetHash, makeVerifiedDocumentKekTargets, } from "../../../../internal/crypto/index.js";
2
- import { resolveEventContainerPaths } from "../../../keyingProjectionVerification/document/documentDependencyPaths.js";
2
+ import { resolveEventContainerPaths } from "../../../keyingProjectionVerification/index.js";
3
3
  import { sortDocumentTargets } from "../readers.js";
4
4
  export async function documentWriteAuthorizationForHeader(input) {
5
5
  const source = input.plan.documentWriterAuthorization;
@@ -1 +1 @@
1
- {"version":3,"file":"syncResponseAuthorization.js","sourceRoot":"","sources":["syncResponseAuthorization.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mCAAmC,EAEnC,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,wEAAwE,CAAC;AACpH,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAGjD,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAWzD;IACC,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC;IACtD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,IAAI,KAAK,CAAC,yBAAyB,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;IACD,MAAM,gBAAgB,GAAG,MAAM,CAAC,sBAAsB,CAAC,GAAG,CACxD,KAAK,CAAC,YAAY,CACnB,CAAC;IACF,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,gBAAgB,CAAC,UAAU,KAAK,KAAK,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChE,MAAM,IAAI,KAAK,CACb,uEAAuE,CACxE,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,mBAAmB,CAAC,KAAK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AAC,mBAAmB,KAAK,MAAM,CAAC,mBAAmB,EAC7D,CAAC;YACD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;QACJ,CAAC;IACH,CAAC;IACD,MAAM,yBAAyB,GAAG,wBAAwB,CAAC;IAC3D,MAAM,kBAAkB,GAAG,8BAA8B,CAAC;QACxD,UAAU,EAAE,KAAK,CAAC,gBAAgB,CAAC,UAAU;QAC7C,qBAAqB,EAAE,KAAK,CAAC,UAAU;QACvC,0BAA0B,EAAE,OAAO,CAAC,GAAG,CACrC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CACvC;QACD,6BAA6B,EAAE,OAAO,CAAC,GAAG,CACxC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,qBAAqB,CACzC;QACD,mBAAmB,EAAE,KAAK,CAAC,YAAY;QACvC,OAAO;KACR,CAAC,CAAC;IACH,OAAO;QACL,yBAAyB;QACzB,kBAAkB;QAClB,gBAAgB;QAChB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;KAC5C,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeDocumentContentKeyTargetHash,\n type DocumentContentKeyTarget,\n makeVerifiedDocumentKekTargets,\n} from \"@tearleads/crypto\";\nimport type { DocumentSyncResponse } from \"@tearleads/validators/response\";\nimport { resolveEventContainerPaths } from \"../../../keyingProjectionVerification/document/documentDependencyPaths\";\nimport { sortDocumentTargets } from \"../readers\";\nimport type { DocumentSyncPlan } from \"../types\";\n\nexport async function documentWriteAuthorizationForHeader(input: {\n readonly allowMissingAuthorization: boolean;\n readonly dependencyManifestHashes: readonly string[];\n readonly authorizationTargets: readonly DocumentContentKeyTarget[];\n readonly contentKeyBundle: DocumentSyncResponse[\"contentKeyBundle\"];\n readonly manifestHash: string;\n readonly plan: Pick<\n DocumentSyncPlan,\n \"documentId\" | \"organizationId\" | \"documentWriterAuthorization\"\n >;\n readonly targetHash: string;\n}) {\n const source = input.plan.documentWriterAuthorization;\n if (!source) {\n if (input.allowMissingAuthorization) {\n return null;\n }\n throw new Error(\n \"Document sync response lacks verified writer-authorization material\",\n );\n }\n const documentManifest = source.documentManifestByHash.get(\n input.manifestHash,\n );\n if (!documentManifest) {\n throw new Error(\n \"Document sync response write manifest is not in verified history\",\n );\n }\n if (input.contentKeyBundle.documentId !== input.plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle belongs to another document\",\n );\n }\n\n const targets = sortDocumentTargets(input.authorizationTargets);\n if (\n (await computeDocumentContentKeyTargetHash(targets)) !== input.targetHash\n ) {\n throw new Error(\"Document sync response write targets are not canonical\");\n }\n const linkedContainerIds = new Set(documentManifest.state.linkedContainerIds);\n if (\n targets.length !== linkedContainerIds.size ||\n targets.some((target) => !linkedContainerIds.has(target.containerId))\n ) {\n throw new Error(\n \"Document sync response write targets do not match the signed link set\",\n );\n }\n\n const { dependencyContainerPaths } = resolveEventContainerPaths({\n containerPathByManifestHash: source.containerPathByManifestHash,\n dependencyManifestHashes: input.dependencyManifestHashes,\n });\n // A writer needs one committed target, and can be unable to read another\n // linked container. Validate the targets that are cited without inventing\n // paths for uncited targets or dropping signed ancestor evidence.\n for (const target of targets) {\n const path = dependencyContainerPaths.find(\n (candidate) =>\n candidate.at(-1)?.manifestHash === target.containerManifestHash,\n );\n if (!path) continue;\n const leaf = path.at(-1);\n if (\n !leaf ||\n leaf.state.containerId !== target.containerId ||\n leaf.state.organizationId !== input.plan.organizationId ||\n leaf.state.containerKeyEpochId !== target.containerKeyEpochId\n ) {\n throw new Error(\n \"Document sync response write target lacks a verified container path\",\n );\n }\n }\n const authorizingContainerPaths = dependencyContainerPaths;\n const documentKekTargets = makeVerifiedDocumentKekTargets({\n documentId: input.contentKeyBundle.documentId,\n documentKeyTargetHash: input.targetHash,\n linkedContainerKeyEpochIds: targets.map(\n (target) => target.containerKeyEpochId,\n ),\n linkedContainerManifestHashes: targets.map(\n (target) => target.containerManifestHash,\n ),\n linkSetManifestHash: input.manifestHash,\n targets,\n });\n return {\n authorizingContainerPaths,\n documentKekTargets,\n documentManifest,\n principalPolicies: source.principalPolicies,\n };\n}\n"]}
1
+ {"version":3,"file":"syncResponseAuthorization.js","sourceRoot":"","sources":["syncResponseAuthorization.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mCAAmC,EAEnC,8BAA8B,GAC/B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAGjD,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,KAWzD;IACC,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC;IACtD,IAAI,CAAC,MAAM,EAAE,CAAC;QACZ,IAAI,KAAK,CAAC,yBAAyB,EAAE,CAAC;YACpC,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,IAAI,KAAK,CACb,qEAAqE,CACtE,CAAC;IACJ,CAAC;IACD,MAAM,gBAAgB,GAAG,MAAM,CAAC,sBAAsB,CAAC,GAAG,CACxD,KAAK,CAAC,YAAY,CACnB,CAAC;IACF,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CACb,kEAAkE,CACnE,CAAC;IACJ,CAAC;IACD,IAAI,KAAK,CAAC,gBAAgB,CAAC,UAAU,KAAK,KAAK,CAAC,IAAI,CAAC,UAAU,EAAE,CAAC;QAChE,MAAM,IAAI,KAAK,CACb,uEAAuE,CACxE,CAAC;IACJ,CAAC;IAED,MAAM,OAAO,GAAG,mBAAmB,CAAC,KAAK,CAAC,oBAAoB,CAAC,CAAC;IAChE,IACE,CAAC,MAAM,mCAAmC,CAAC,OAAO,CAAC,CAAC,KAAK,KAAK,CAAC,UAAU,EACzE,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,wDAAwD,CAAC,CAAC;IAC5E,CAAC;IACD,MAAM,kBAAkB,GAAG,IAAI,GAAG,CA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E,KAAK,CAAC,gBAAgB,CAAC,UAAU;QAC7C,qBAAqB,EAAE,KAAK,CAAC,UAAU;QACvC,0BAA0B,EAAE,OAAO,CAAC,GAAG,CACrC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,mBAAmB,CACvC;QACD,6BAA6B,EAAE,OAAO,CAAC,GAAG,CACxC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,qBAAqB,CACzC;QACD,mBAAmB,EAAE,KAAK,CAAC,YAAY;QACvC,OAAO;KACR,CAAC,CAAC;IACH,OAAO;QACL,yBAAyB;QACzB,kBAAkB;QAClB,gBAAgB;QAChB,iBAAiB,EAAE,MAAM,CAAC,iBAAiB;KAC5C,CAAC;AACJ,CAAC","sourcesContent":["import {\n computeDocumentContentKeyTargetHash,\n type DocumentContentKeyTarget,\n makeVerifiedDocumentKekTargets,\n} from \"@tearleads/crypto\";\nimport type { DocumentSyncResponse } from \"@tearleads/validators/response\";\nimport { resolveEventContainerPaths } from \"../../../keyingProjectionVerification\";\nimport { sortDocumentTargets } from \"../readers\";\nimport type { DocumentSyncPlan } from \"../types\";\n\nexport async function documentWriteAuthorizationForHeader(input: {\n readonly allowMissingAuthorization: boolean;\n readonly dependencyManifestHashes: readonly string[];\n readonly authorizationTargets: readonly DocumentContentKeyTarget[];\n readonly contentKeyBundle: DocumentSyncResponse[\"contentKeyBundle\"];\n readonly manifestHash: string;\n readonly plan: Pick<\n DocumentSyncPlan,\n \"documentId\" | \"organizationId\" | \"documentWriterAuthorization\"\n >;\n readonly targetHash: string;\n}) {\n const source = input.plan.documentWriterAuthorization;\n if (!source) {\n if (input.allowMissingAuthorization) {\n return null;\n }\n throw new Error(\n \"Document sync response lacks verified writer-authorization material\",\n );\n }\n const documentManifest = source.documentManifestByHash.get(\n input.manifestHash,\n );\n if (!documentManifest) {\n throw new Error(\n \"Document sync response write manifest is not in verified history\",\n );\n }\n if (input.contentKeyBundle.documentId !== input.plan.documentId) {\n throw new Error(\n \"Document sync response content-key bundle belongs to another document\",\n );\n }\n\n const targets = sortDocumentTargets(input.authorizationTargets);\n if (\n (await computeDocumentContentKeyTargetHash(targets)) !== input.targetHash\n ) {\n throw new Error(\"Document sync response write targets are not canonical\");\n }\n const linkedContainerIds = new Set(documentManifest.state.linkedContainerIds);\n if (\n targets.length !== linkedContainerIds.size ||\n targets.some((target) => !linkedContainerIds.has(target.containerId))\n ) {\n throw new Error(\n \"Document sync response write targets do not match the signed link set\",\n );\n }\n\n const { dependencyContainerPaths } = resolveEventContainerPaths({\n containerPathByManifestHash: source.containerPathByManifestHash,\n dependencyManifestHashes: input.dependencyManifestHashes,\n });\n // A writer needs one committed target, and can be unable to read another\n // linked container. Validate the targets that are cited without inventing\n // paths for uncited targets or dropping signed ancestor evidence.\n for (const target of targets) {\n const path = dependencyContainerPaths.find(\n (candidate) =>\n candidate.at(-1)?.manifestHash === target.containerManifestHash,\n );\n if (!path) continue;\n const leaf = path.at(-1);\n if (\n !leaf ||\n leaf.state.containerId !== target.containerId ||\n leaf.state.organizationId !== input.plan.organizationId ||\n leaf.state.containerKeyEpochId !== target.containerKeyEpochId\n ) {\n throw new Error(\n \"Document sync response write target lacks a verified container path\",\n );\n }\n }\n const authorizingContainerPaths = dependencyContainerPaths;\n const documentKekTargets = makeVerifiedDocumentKekTargets({\n documentId: input.contentKeyBundle.documentId,\n documentKeyTargetHash: input.targetHash,\n linkedContainerKeyEpochIds: targets.map(\n (target) => target.containerKeyEpochId,\n ),\n linkedContainerManifestHashes: targets.map(\n (target) => target.containerManifestHash,\n ),\n linkSetManifestHash: input.manifestHash,\n targets,\n });\n return {\n authorizingContainerPaths,\n documentKekTargets,\n documentManifest,\n principalPolicies: source.principalPolicies,\n };\n}\n"]}
@@ -0,0 +1,12 @@
1
+ import { type VerifiedContainerAccessManifest } from "../../../internal/crypto/index.js";
2
+ /**
3
+ * Walk a verified head back to its epoch-1 `container.create`. Head
4
+ * verification already verified every predecessor it cites (a head is only
5
+ * accepted once its previous manifest verified), so the lineage is present in
6
+ * `verifiedByHash`; a gap means the served projection was incomplete.
7
+ */
8
+ export declare function verifiedContainerCreateManifest(input: {
9
+ readonly head: VerifiedContainerAccessManifest;
10
+ readonly label: string;
11
+ readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;
12
+ }): VerifiedContainerAccessManifest;
@@ -0,0 +1,16 @@
1
+ import type { VerifiedContainerAccessManifest } from "../../../internal/crypto/index.js";
2
+ import type { ContainerWriterProjectionResponse } from "../../../internal/validators/response/index.js";
3
+ import type { ExecSql } from "../../sqlite/sqlSchema.js";
4
+ import type { ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
5
+ /** Authenticate immutable destination roles without advancing write-authority pins. */
6
+ export declare function verifyContainerDestinationProjection(input: {
7
+ readonly execSql: ExecSql;
8
+ readonly projection: ContainerWriterProjectionResponse;
9
+ readonly resolveUserKey: ProjectionUserKeyResolver;
10
+ readonly stillCurrent?: (() => boolean) | undefined;
11
+ readonly warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
12
+ }): Promise<{
13
+ readonly path: VerifiedContainerAccessManifest[];
14
+ /** Every manifest verified on the way, including each head's lineage. */
15
+ readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;
16
+ }>;
@@ -4,6 +4,11 @@ export { readAccessEvent, readRecordString, readRequiredRecordValue, } from "./r
4
4
  export type { PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer, } from "./types.js";
5
5
  export { isProjectionVerificationCancelledError, nullOnProjectionVerificationCancellation, } from "./types.js";
6
6
  export declare function requireProjectionUserKeyResolver(resolveProjectionUserKey: ProjectionUserKeyResolver | null | undefined, label: string): ProjectionUserKeyResolver;
7
+ export { verifiedContainerCreateManifest } from "./container/containerCreateManifest.js";
8
+ export { verifyContainerDestinationProjection } from "./container/containerDestinationVerification.js";
7
9
  export { collectContainerWriterProjectionPrincipalPolicies, verifyContainerWriterProjection, } from "./container/containerProjectionVerification.js";
8
10
  export { type DocumentWriterProjectionAuthorization, verifyDocumentWriterProjection, verifyDocumentWriterProjectionAuthorization, } from "./document/documentProjectionVerification.js";
9
11
  export { verifyDocumentPurgeProof, verifyDocumentPurgeProofBaseline, } from "./documentPurge/documentPurgeProofVerification.js";
12
+ export { mergeProjectionPolicyEvidence } from "./principalPolicy/mergeProjectionPolicyEvidence.js";
13
+ export { principalPolicyHeadMeetsCheckpoint } from "./principalPolicy/principalPolicyCheckpointSelection.js";
14
+ export { isPrincipalPolicyNotCachedError } from "./principalPolicy/principalPolicyVerification.js";
@@ -1,4 +1,4 @@
1
- import { requireTrustedUserIdentityResolver } from "../trustedUserIdentity/requiredResolver.js";
1
+ import { requireTrustedUserIdentityResolver } from "../trustedUserIdentity/index.js";
2
2
  export { resolveEventContainerPaths } from "./document/documentDependencyPaths.js";
3
3
  export { readAccessEvent, readRecordString, readRequiredRecordValue, } from "./readers.js";
4
4
  export { isProjectionVerificationCancelledError, nullOnProjectionVerificationCancellation, } from "./types.js";
@@ -10,7 +10,12 @@ export function requireProjectionUserKeyResolver(resolveProjectionUserKey, label
10
10
  // provides the untrusted-shape and wrong-user guards (with identity caching).
11
11
  return requireTrustedUserIdentityResolver(resolveProjectionUserKey);
12
12
  }
13
+ export { verifiedContainerCreateManifest } from "./container/containerCreateManifest.js";
14
+ export { verifyContainerDestinationProjection } from "./container/containerDestinationVerification.js";
13
15
  export { collectContainerWriterProjectionPrincipalPolicies, verifyContainerWriterProjection, } from "./container/containerProjectionVerification.js";
14
16
  export { verifyDocumentWriterProjection, verifyDocumentWriterProjectionAuthorization, } from "./document/documentProjectionVerification.js";
15
17
  export { verifyDocumentPurgeProof, verifyDocumentPurgeProofBaseline, } from "./documentPurge/documentPurgeProofVerification.js";
18
+ export { mergeProjectionPolicyEvidence } from "./principalPolicy/mergeProjectionPolicyEvidence.js";
19
+ export { principalPolicyHeadMeetsCheckpoint } from "./principalPolicy/principalPolicyCheckpointSelection.js";
20
+ export { isPrincipalPolicyNotCachedError } from "./principalPolicy/principalPolicyVerification.js";
16
21
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,yCAAyC,CAAC;AAG7F,OAAO,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,WAAW,CAAC;AAOnB,OAAO,EACL,sCAAsC,EACtC,wCAAwC,GACzC,MAAM,SAAS,CAAC;AAEjB,MAAM,UAAU,gCAAgC,CAC9C,wBAAsE,EACtE,KAAa;IAEb,IAAI,CAAC,wBAAwB,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,uCAAuC,CAAC,CAAC;IACnE,CAAC;IAED,sEAAsE;IACtE,8EAA8E;IAC9E,OAAO,kCAAkC,CAAC,wBAAwB,CAAC,CAAC;AACtE,CAAC;AAED,OAAO,EACL,iDAAiD,EACjD,+BAA+B,GAChC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAEL,8BAA8B,EAC9B,2CAA2C,GAC5C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,gDAAgD,CAAC","sourcesContent":["import { requireTrustedUserIdentityResolver } from \"../trustedUserIdentity/requiredResolver\";\nimport type { ProjectionUserKeyResolver } from \"./types\";\n\nexport { resolveEventContainerPaths } from \"./document/documentDependencyPaths\";\nexport {\n readAccessEvent,\n readRecordString,\n readRequiredRecordValue,\n} from \"./readers\";\n\nexport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nexport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n} from \"./types\";\n\nexport function requireProjectionUserKeyResolver(\n resolveProjectionUserKey: ProjectionUserKeyResolver | null | undefined,\n label: string,\n): ProjectionUserKeyResolver {\n if (!resolveProjectionUserKey) {\n throw new Error(`${label} requires projection key verification`);\n }\n\n // A ProjectionUserKey is a TrustedUserIdentity, so the shared adapter\n // provides the untrusted-shape and wrong-user guards (with identity caching).\n return requireTrustedUserIdentityResolver(resolveProjectionUserKey);\n}\n\nexport {\n collectContainerWriterProjectionPrincipalPolicies,\n verifyContainerWriterProjection,\n} from \"./container/containerProjectionVerification\";\nexport {\n type DocumentWriterProjectionAuthorization,\n verifyDocumentWriterProjection,\n verifyDocumentWriterProjectionAuthorization,\n} from \"./document/documentProjectionVerification\";\nexport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n} from \"./documentPurge/documentPurgeProofVerification\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wBAAwB,CAAC;AAG5E,OAAO,EAAE,0BAA0B,EAAE,MAAM,oCAAoC,CAAC;AAChF,OAAO,EACL,eAAe,EACf,gBAAgB,EAChB,uBAAuB,GACxB,MAAM,WAAW,CAAC;AAOnB,OAAO,EACL,sCAAsC,EACtC,wCAAwC,GACzC,MAAM,SAAS,CAAC;AAEjB,MAAM,UAAU,gCAAgC,CAC9C,wBAAsE,EACtE,KAAa;IAEb,IAAI,CAAC,wBAAwB,EAAE,CAAC;QAC9B,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,uCAAuC,CAAC,CAAC;IACnE,CAAC;IAED,sEAAsE;IACtE,8EAA8E;IAC9E,OAAO,kCAAkC,CAAC,wBAAwB,CAAC,CAAC;AACtE,CAAC;AAED,OAAO,EAAE,+BAA+B,EAAE,MAAM,qCAAqC,CAAC;AACtF,OAAO,EAAE,oCAAoC,EAAE,MAAM,8CAA8C,CAAC;AACpG,OAAO,EACL,iDAAiD,EACjD,+BAA+B,GAChC,MAAM,6CAA6C,CAAC;AACrD,OAAO,EAEL,8BAA8B,EAC9B,2CAA2C,GAC5C,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,wBAAwB,EACxB,gCAAgC,GACjC,MAAM,gDAAgD,CAAC;AACxD,OAAO,EAAE,6BAA6B,EAAE,MAAM,iDAAiD,CAAC;AAChG,OAAO,EAAE,kCAAkC,EAAE,MAAM,sDAAsD,CAAC;AAC1G,OAAO,EAAE,+BAA+B,EAAE,MAAM,+CAA+C,CAAC","sourcesContent":["import { requireTrustedUserIdentityResolver } from \"../trustedUserIdentity\";\nimport type { ProjectionUserKeyResolver } from \"./types\";\n\nexport { resolveEventContainerPaths } from \"./document/documentDependencyPaths\";\nexport {\n readAccessEvent,\n readRecordString,\n readRequiredRecordValue,\n} from \"./readers\";\n\nexport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"./types\";\nexport {\n isProjectionVerificationCancelledError,\n nullOnProjectionVerificationCancellation,\n} from \"./types\";\n\nexport function requireProjectionUserKeyResolver(\n resolveProjectionUserKey: ProjectionUserKeyResolver | null | undefined,\n label: string,\n): ProjectionUserKeyResolver {\n if (!resolveProjectionUserKey) {\n throw new Error(`${label} requires projection key verification`);\n }\n\n // A ProjectionUserKey is a TrustedUserIdentity, so the shared adapter\n // provides the untrusted-shape and wrong-user guards (with identity caching).\n return requireTrustedUserIdentityResolver(resolveProjectionUserKey);\n}\n\nexport { verifiedContainerCreateManifest } from \"./container/containerCreateManifest\";\nexport { verifyContainerDestinationProjection } from \"./container/containerDestinationVerification\";\nexport {\n collectContainerWriterProjectionPrincipalPolicies,\n verifyContainerWriterProjection,\n} from \"./container/containerProjectionVerification\";\nexport {\n type DocumentWriterProjectionAuthorization,\n verifyDocumentWriterProjection,\n verifyDocumentWriterProjectionAuthorization,\n} from \"./document/documentProjectionVerification\";\nexport {\n verifyDocumentPurgeProof,\n verifyDocumentPurgeProofBaseline,\n} from \"./documentPurge/documentPurgeProofVerification\";\nexport { mergeProjectionPolicyEvidence } from \"./principalPolicy/mergeProjectionPolicyEvidence\";\nexport { principalPolicyHeadMeetsCheckpoint } from \"./principalPolicy/principalPolicyCheckpointSelection\";\nexport { isPrincipalPolicyNotCachedError } from \"./principalPolicy/principalPolicyVerification\";\n"]}
@@ -0,0 +1,3 @@
1
+ import type { ProjectionPolicyEvidenceResponse } from "../../../internal/validators/response/index.js";
2
+ /** Combine proof material when locally composing projections; verification follows. */
3
+ export declare function mergeProjectionPolicyEvidence(evidence: readonly ProjectionPolicyEvidenceResponse[]): ProjectionPolicyEvidenceResponse;
@@ -1,9 +1,9 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { loadPrincipalPolicyCheckpoint } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
- import { verifiedPrincipalPolicyMeetsCheckpoint } from "../../persistence/principalPolicy/principalPolicyCheckpointSelection.js";
4
3
  import { loadPrincipalPolicyBundleForReference } from "../../persistence/principalPolicy/principalPolicyReferencePersistence.js";
5
4
  import { principalPolicyEvidenceEntries, } from "../../principals/principalPolicyEvidence.js";
6
5
  import { principalStateMatchesReference } from "../../principals/principalPolicyStates.js";
6
+ import { verifiedPrincipalPolicyMeetsCheckpoint } from "./principalPolicyCheckpointSelection.js";
7
7
  /**
8
8
  * Cache key for a referenced principal policy. The in-memory principal-policy
9
9
  * cache is populated and read from several call sites; they must agree on this
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyCache.js","sourceRoot":"","sources":["principalPolicyCache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EAAE,sCAAsC,EAAE,MAAM,sEAAsE,CAAC;AAC9H,OAAO,EAAE,qCAAqC,EAAE,MAAM,uEAAuE,CAAC;AAC9H,OAAO,EAEL,8BAA8B,GAC/B,MAAM,0CAA0C,CAAC;AA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C,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACnC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,SAAS,EAAwC,EAAE,CAAC,SAAS,KAAK,IAAI,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"../../persistence/principalPolicy/principalPolicyCheckpointSelection\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport { principalStateMatchesReference } from \"../../principals/principalPolicyStates\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\n\n/**\n * Cache key for a referenced principal policy. The in-memory principal-policy\n * cache is populated and read from several call sites; they must agree on this\n * format byte-for-byte or a populated entry looks uncached (extra warm fetches)\n * — so this is the single source of truth, imported rather than re-declared.\n */\nexport function referencedPrincipalPolicyKey(\n reference: ReferencedPrincipalHead,\n): string {\n return JSON.stringify([\n reference.principalType,\n reference.principalId,\n reference.version,\n reference.stateHash,\n reference.keyEpoch,\n reference.keyFingerprint,\n ]);\n}\n\n/**\n * Dedupes references by their exact head identity, keyed with\n * {@link referencedPrincipalPolicyKey} so every consumer agrees on what\n * \"the same reference\" means. Later duplicates win, preserving each\n * caller's original last-wins behavior.\n */\nexport function dedupeReferencedPrincipalStates<\n TReference extends ReferencedPrincipalHead,\n>(references: ReadonlyArray<TReference>): TReference[] {\n const referencesByState = new Map<string, TReference>();\n for (const reference of references) {\n referencesByState.set(referencedPrincipalPolicyKey(reference), reference);\n }\n return Array.from(referencesByState.values());\n}\n\nexport function principalPolicyCacheForVerifiedPolicies(\n policies: readonly PrincipalPolicyCurrentEvidence[],\n): Map<string, PrincipalPolicyCurrentEvidence> {\n const cache = new Map<string, PrincipalPolicyCurrentEvidence>();\n for (const policy of policies) {\n const states = principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.state,\n );\n for (const state of states) {\n cache.set(\n referencedPrincipalPolicyKey({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash: state.stateHash,\n keyFingerprint: state.keyFingerprint,\n }),\n policy,\n );\n }\n }\n return cache;\n}\n\nexport function verifiedPrincipalPolicyContainsReference(\n policy: PrincipalPolicyCurrentEvidence,\n reference: ReferencedPrincipalHead,\n): boolean {\n const states = principalPolicyEvidenceEntries(policy).map(\n ({ state }) => state,\n );\n return states.some((state) =>\n principalStateMatchesReference(state, reference),\n );\n}\n\n// Identify which referenced policies are absent from both the in-memory cache\n// and local storage, so the warmer fetches only what is genuinely missing.\nexport async function filterUncachedPrincipalPolicyReferences(input: {\n execSql: ExecSql;\n principalPolicyCache: ReadonlyMap<string, PrincipalPolicyCurrentEvidence>;\n references: readonly ReferencedPrincipalHead[];\n}): Promise<ReferencedPrincipalHead[]> {\n const results = await Promise.all(\n input.references.map(async (reference) => {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n reference.principalType,\n reference.principalId,\n );\n const cachedPolicy = input.principalPolicyCache.get(\n referencedPrincipalPolicyKey(reference),\n );\n if (cachedPolicy) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, checkpoint)) {\n return null;\n }\n }\n const bundle = await loadPrincipalPolicyBundleForReference(\n input.execSql,\n reference,\n checkpoint,\n );\n return bundle ? null : reference;\n }),\n );\n return results.filter(\n (reference): reference is ReferencedPrincipalHead => reference !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,IACE,CAAC,wCAAwC,CAAC,YAAY,EAAE,SAAS,CAAC,EAClE,CAAC;gBACD,MAAM,IAAI,uBAAuB,CAC/B,eAAe,EACf,qEAAqE,CACtE,CAAC;YACJ,CAAC;YACD,IAAI,sCAAsC,CAAC,YAAY,EAAE,UAAU,CAAC,EAAE,CAAC;gBACrE,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QACD,MAAM,MAAM,GAAG,MAAM,qCAAqC,CACxD,KAAK,CAAC,OAAO,EACb,SAAS,EACT,UAAU,CACX,CAAC;QACF,OAAO,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC;IACnC,CAAC,CAAC,CACH,CAAC;IACF,OAAO,OAAO,CAAC,MAAM,CACnB,CAAC,SAAS,EAAwC,EAAE,CAAC,SAAS,KAAK,IAAI,CACxE,CAAC;AACJ,CAAC","sourcesContent":["import type { ReferencedPrincipalHead } from \"@tearleads/crypto\";\nimport { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport { principalStateMatchesReference } from \"../../principals/principalPolicyStates\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"./principalPolicyCheckpointSelection\";\n\n/**\n * Cache key for a referenced principal policy. The in-memory principal-policy\n * cache is populated and read from several call sites; they must agree on this\n * format byte-for-byte or a populated entry looks uncached (extra warm fetches)\n * — so this is the single source of truth, imported rather than re-declared.\n */\nexport function referencedPrincipalPolicyKey(\n reference: ReferencedPrincipalHead,\n): string {\n return JSON.stringify([\n reference.principalType,\n reference.principalId,\n reference.version,\n reference.stateHash,\n reference.keyEpoch,\n reference.keyFingerprint,\n ]);\n}\n\n/**\n * Dedupes references by their exact head identity, keyed with\n * {@link referencedPrincipalPolicyKey} so every consumer agrees on what\n * \"the same reference\" means. Later duplicates win, preserving each\n * caller's original last-wins behavior.\n */\nexport function dedupeReferencedPrincipalStates<\n TReference extends ReferencedPrincipalHead,\n>(references: ReadonlyArray<TReference>): TReference[] {\n const referencesByState = new Map<string, TReference>();\n for (const reference of references) {\n referencesByState.set(referencedPrincipalPolicyKey(reference), reference);\n }\n return Array.from(referencesByState.values());\n}\n\nexport function principalPolicyCacheForVerifiedPolicies(\n policies: readonly PrincipalPolicyCurrentEvidence[],\n): Map<string, PrincipalPolicyCurrentEvidence> {\n const cache = new Map<string, PrincipalPolicyCurrentEvidence>();\n for (const policy of policies) {\n const states = principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.state,\n );\n for (const state of states) {\n cache.set(\n referencedPrincipalPolicyKey({\n principalType: state.principalType,\n principalId: state.principalId,\n version: state.version,\n keyEpoch: state.keyEpoch,\n stateHash: state.stateHash,\n keyFingerprint: state.keyFingerprint,\n }),\n policy,\n );\n }\n }\n return cache;\n}\n\nexport function verifiedPrincipalPolicyContainsReference(\n policy: PrincipalPolicyCurrentEvidence,\n reference: ReferencedPrincipalHead,\n): boolean {\n const states = principalPolicyEvidenceEntries(policy).map(\n ({ state }) => state,\n );\n return states.some((state) =>\n principalStateMatchesReference(state, reference),\n );\n}\n\n// Identify which referenced policies are absent from both the in-memory cache\n// and local storage, so the warmer fetches only what is genuinely missing.\nexport async function filterUncachedPrincipalPolicyReferences(input: {\n execSql: ExecSql;\n principalPolicyCache: ReadonlyMap<string, PrincipalPolicyCurrentEvidence>;\n references: readonly ReferencedPrincipalHead[];\n}): Promise<ReferencedPrincipalHead[]> {\n const results = await Promise.all(\n input.references.map(async (reference) => {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n reference.principalType,\n reference.principalId,\n );\n const cachedPolicy = input.principalPolicyCache.get(\n referencedPrincipalPolicyKey(reference),\n );\n if (cachedPolicy) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, checkpoint)) {\n return null;\n }\n }\n const bundle = await loadPrincipalPolicyBundleForReference(\n input.execSql,\n reference,\n checkpoint,\n );\n return bundle ? null : reference;\n }),\n );\n return results.filter(\n (reference): reference is ReferencedPrincipalHead => reference !== null,\n );\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import type { PrincipalPolicyAuthorization, PrincipalPolicyCheckpoint } from "../../../internal/crypto/index.js";
2
+ export declare function principalPolicyHeadMeetsCheckpoint(head: {
3
+ readonly stateHash: string;
4
+ readonly version: number;
5
+ }, checkpoint: PrincipalPolicyCheckpoint | null): boolean;
6
+ export declare function verifiedPrincipalPolicyMeetsCheckpoint(policy: PrincipalPolicyAuthorization, checkpoint: PrincipalPolicyCheckpoint | null): boolean;
@@ -1,5 +1,5 @@
1
1
  import { verifyPrincipalPolicyCheckpoint } from "../../../internal/crypto/index.js";
2
- import { assertPrincipalPolicyCheckpointShape } from "../keyingCheckpoints/keyingCheckpointPersistence.js";
2
+ import { assertPrincipalPolicyCheckpointShape } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
3
  export function principalPolicyHeadMeetsCheckpoint(head, checkpoint) {
4
4
  return (!checkpoint ||
5
5
  head.version > checkpoint.version ||
@@ -0,0 +1 @@
1
+ {"version":3,"file":"principalPolicyCheckpointSelection.js","sourceRoot":"","sources":["principalPolicyCheckpointSelection.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,+BAA+B,EAAE,MAAM,mBAAmB,CAAC;AACpE,OAAO,EAAE,oCAAoC,EAAE,MAAM,iEAAiE,CAAC;AAEvH,MAAM,UAAU,kCAAkC,CAChD,IAA8D,EAC9D,UAA4C;IAE5C,OAAO,CACL,CAAC,UAAU;QACX,IAAI,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO;QACjC,CAAC,IAAI,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO;YAClC,IAAI,CAAC,SAAS,KAAK,UAAU,CAAC,SAAS,CAAC,CAC3C,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,sCAAsC,CACpD,MAAoC,EACpC,UAA4C;IAE5C,IAAI,CAAC,UAAU,EAAE,CAAC;QAChB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,oCAAoC,CAAC,UAAU,EAAE,MAAM,CAAC,CAAC;IACzD,IAAI,MAAM,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO,EAAE,CAAC;QACxC,OAAO,KAAK,CAAC;IACf,CAAC;IACD,+BAA+B,CAAC;QAC9B,KAAK,EACH,iBAAiB,IAAI,MAAM;YACzB,CAAC,CAAC,MAAM,CAAC,eAAe;YACxB,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,IAAI,EAAE,CAAC;QAC5B,YAAY,EAAE,MAAM,CAAC,KAAK;QAC1B,eAAe,EAAE,UAAU;KAC5B,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\n PrincipalPolicyCheckpoint,\n} from \"@tearleads/crypto\";\nimport { verifyPrincipalPolicyCheckpoint } from \"@tearleads/crypto\";\nimport { assertPrincipalPolicyCheckpointShape } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\n\nexport function principalPolicyHeadMeetsCheckpoint(\n head: { readonly stateHash: string; readonly version: number },\n checkpoint: PrincipalPolicyCheckpoint | null,\n): boolean {\n return (\n !checkpoint ||\n head.version > checkpoint.version ||\n (head.version === checkpoint.version &&\n head.stateHash === checkpoint.stateHash)\n );\n}\n\nexport function verifiedPrincipalPolicyMeetsCheckpoint(\n policy: PrincipalPolicyAuthorization,\n checkpoint: PrincipalPolicyCheckpoint | null,\n): boolean {\n if (!checkpoint) {\n return true;\n }\n assertPrincipalPolicyCheckpointShape(checkpoint, policy);\n if (policy.version < checkpoint.version) {\n return false;\n }\n verifyPrincipalPolicyCheckpoint({\n chain:\n \"retainedHistory\" in policy\n ? policy.retainedHistory\n : (policy.history ?? []),\n currentState: policy.state,\n localCheckpoint: checkpoint,\n });\n return true;\n}\n"]}
@@ -0,0 +1,24 @@
1
+ import { type ReferencedPrincipalHead } from "../../../internal/crypto/index.js";
2
+ import type { PrincipalPolicyCurrentEvidence } from "../../principals/principalPolicyEvidence.js";
3
+ import { type ProjectionCheckpointContext } from "../checkpoints/checkpointContext.js";
4
+ import type { PrincipalPolicyCache, ProjectionUserKeyResolver, ReferencedPrincipalPolicyWarmer } from "../types.js";
5
+ /**
6
+ * A referenced principal policy is not in the local store and warming could
7
+ * not fetch it this pass — a transient cold-cache condition, typical for a
8
+ * member whose access arrives via a group policy the device has not hydrated
9
+ * yet. Sync passes discriminate on this type to defer the affected container
10
+ * and retry on a later trigger, rather than failing the whole pass.
11
+ */
12
+ export declare class PrincipalPolicyNotCachedError extends Error {
13
+ constructor(referenceLabel: string);
14
+ }
15
+ export declare function isPrincipalPolicyNotCachedError(error: unknown): boolean;
16
+ export declare function collectReferencedPrincipalPolicies(input: {
17
+ checkpointContext: ProjectionCheckpointContext;
18
+ organizationId: string;
19
+ principalPolicyCache: PrincipalPolicyCache;
20
+ references: readonly ReferencedPrincipalHead[];
21
+ resolveUserKey: ProjectionUserKeyResolver;
22
+ stillCurrent?: (() => boolean) | undefined;
23
+ warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
24
+ }): Promise<PrincipalPolicyCurrentEvidence[]>;
@@ -1,6 +1,5 @@
1
1
  import { KeyingVerificationError, toFingerprint, verifyPrincipalPolicyBundle, } from "../../../internal/crypto/index.js";
2
2
  import { loadPrincipalPolicyCheckpoint } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
- import { principalPolicyHeadMeetsCheckpoint, verifiedPrincipalPolicyMeetsCheckpoint, } from "../../persistence/principalPolicy/principalPolicyCheckpointSelection.js";
4
3
  import { loadPrincipalPolicyBundle } from "../../persistence/principalPolicy/principalPolicyPersistence.js";
5
4
  import { loadPrincipalPolicyBundleForReference } from "../../persistence/principalPolicy/principalPolicyReferencePersistence.js";
6
5
  import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../principals/organizationAuthorityDescriptor.js";
@@ -11,6 +10,7 @@ import { ProjectionDependencyUnavailableError } from "../dependencyUnavailable.j
11
10
  import { rethrowProjectionVerificationBoundaryError } from "../error.js";
12
11
  import { assertProjectionVerificationCurrent, generationGuardedPrincipalPolicyWarmer, } from "../types.js";
13
12
  import { filterUncachedPrincipalPolicyReferences, referencedPrincipalPolicyKey, verifiedPrincipalPolicyContainsReference, } from "./principalPolicyCache.js";
13
+ import { principalPolicyHeadMeetsCheckpoint, verifiedPrincipalPolicyMeetsCheckpoint, } from "./principalPolicyCheckpointSelection.js";
14
14
  import { resolveReferencedPrincipalPolicy } from "./resolvedPrincipalPolicy.js";
15
15
  function principalPolicyReferenceLabel(reference) {
16
16
  return `${reference.principalType}:${reference.principalId}@${reference.version}`;
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,aAAa,EAEb,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EACL,kCAAkC,EAClC,sCAAsC,GACvC,MAAM,sEAAsE,CAAC;AAC9E,OAAO,EAAE,yBAAyB,EAAE,MAAM,8DAA8D,CAAC;AACzG,OAAO,EAAE,qCAAqC,EAAE,MAAM,uEAAuE,CAAC;AAC9H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO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AK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B;KAChC,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n toFingerprint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"../../persistence/principalPolicy/principalPolicyCheckpointSelection\";\nimport { loadPrincipalPolicyBundle } from \"../../persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { principalPolicyBundleStates } from \"../../principals/principalPolicyStates\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { rethrowProjectionVerificationBoundaryError } from \"../error\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport { resolveReferencedPrincipalPolicy } from \"./resolvedPrincipalPolicy\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\nasync function collectPrincipalPolicySignerPublicKeys(input: {\n bundle: PrincipalPolicyBundleResponse;\n label: string;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicySignerPublicKey[]> {\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyBundleStates(input.bundle)) {\n const cacheKey = `${state.signerUserId}:${state.signerUserKeyFingerprint}`;\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const signerKey = await input.resolveUserKey(state.signerUserId);\n if (!signerKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer key could not be resolved for ${state.signerUserId}`,\n );\n }\n\n const signingKeyFingerprint = await toFingerprint(\n signerKey.signingPublicKey,\n );\n if (signingKeyFingerprint !== state.signerUserKeyFingerprint) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${input.label} signer key fingerprint mismatch`,\n );\n }\n\n signerPublicKeysByKey.set(cacheKey, {\n userId: state.signerUserId,\n signingKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n });\n }\n\n return [...signerPublicKeysByKey.values()];\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: Awaited<\n ReturnType<typeof loadPrincipalPolicyCheckpoint>\n >;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n stillCurrent?: (() => boolean) | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n // Scoped recovery carries organization, dependency and lifetime bindings.\n // A bare policy cache entry cannot replace those bindings.\n const recovered = await resolveReferencedPrincipalPolicy(input);\n if (recovered) return recovered;\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy && !(\"retainedHistory\" in cachedPolicy)) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (\n warmReferencedPrincipalPolicies &&\n !warmReferencedPrincipalPolicies.resolveReference\n ) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n // The warmer's operation shares one recovery view across its collections.\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n stillCurrent: input.stillCurrent,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAGvB,aAAa,EAEb,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EAAE,yBAAyB,EAAE,MAAM,8DAA8D,CAAC;AACzG,OAAO,EAAE,qCAAqC,EAAE,MAAM,uEAAuE,CAAC;AAC9H,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EACL,kCAAkC,EAClC,kCAAkC,EAClC,6BAA6B,EAC7B,yDAAyD,GAC1D,MAAM,8CAA8C,CA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QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B;KAChC,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicySignerPublicKey,\n type ReferencedPrincipalHead,\n toFingerprint,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { loadPrincipalPolicyBundle } from \"../../persistence/principalPolicy/principalPolicyPersistence\";\nimport { loadPrincipalPolicyBundleForReference } from \"../../persistence/principalPolicy/principalPolicyReferencePersistence\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../principals/principalPolicyAdminSigners\";\nimport type { PrincipalPolicyCurrentEvidence } from \"../../principals/principalPolicyEvidence\";\nimport { principalPolicyBundleStates } from \"../../principals/principalPolicyStates\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { ProjectionDependencyUnavailableError } from \"../dependencyUnavailable\";\nimport { rethrowProjectionVerificationBoundaryError } from \"../error\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n assertProjectionVerificationCurrent,\n generationGuardedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n filterUncachedPrincipalPolicyReferences,\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport {\n principalPolicyHeadMeetsCheckpoint,\n verifiedPrincipalPolicyMeetsCheckpoint,\n} from \"./principalPolicyCheckpointSelection\";\nimport { resolveReferencedPrincipalPolicy } from \"./resolvedPrincipalPolicy\";\n\nfunction principalPolicyReferenceLabel(\n reference: ReferencedPrincipalHead,\n): string {\n return `${reference.principalType}:${reference.principalId}@${reference.version}`;\n}\n\n/**\n * A referenced principal policy is not in the local store and warming could\n * not fetch it this pass — a transient cold-cache condition, typical for a\n * member whose access arrives via a group policy the device has not hydrated\n * yet. Sync passes discriminate on this type to defer the affected container\n * and retry on a later trigger, rather than failing the whole pass.\n */\nexport class PrincipalPolicyNotCachedError extends Error {\n constructor(referenceLabel: string) {\n super(`Principal policy ${referenceLabel} is not cached`);\n this.name = \"PrincipalPolicyNotCachedError\";\n }\n}\n\nexport function isPrincipalPolicyNotCachedError(error: unknown): boolean {\n return (\n error instanceof PrincipalPolicyNotCachedError ||\n (error instanceof Error && error.name === \"PrincipalPolicyNotCachedError\")\n );\n}\n\nasync function collectPrincipalPolicySignerPublicKeys(input: {\n bundle: PrincipalPolicyBundleResponse;\n label: string;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<PrincipalPolicySignerPublicKey[]> {\n const signerPublicKeysByKey = new Map<\n string,\n PrincipalPolicySignerPublicKey\n >();\n\n for (const state of principalPolicyBundleStates(input.bundle)) {\n const cacheKey = `${state.signerUserId}:${state.signerUserKeyFingerprint}`;\n if (signerPublicKeysByKey.has(cacheKey)) {\n continue;\n }\n\n const signerKey = await input.resolveUserKey(state.signerUserId);\n if (!signerKey) {\n throw new ProjectionDependencyUnavailableError(\n `${input.label} signer key could not be resolved for ${state.signerUserId}`,\n );\n }\n\n const signingKeyFingerprint = await toFingerprint(\n signerKey.signingPublicKey,\n );\n if (signingKeyFingerprint !== state.signerUserKeyFingerprint) {\n throw new KeyingVerificationError(\n \"signer_mismatch\",\n `${input.label} signer key fingerprint mismatch`,\n );\n }\n\n signerPublicKeysByKey.set(cacheKey, {\n userId: state.signerUserId,\n signingKeyFingerprint,\n signingPublicKey: signerKey.signingPublicKey,\n });\n }\n\n return [...signerPublicKeysByKey.values()];\n}\n\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: Awaited<\n ReturnType<typeof loadPrincipalPolicyCheckpoint>\n >;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (\n !principalPolicyHeadMeetsCheckpoint(bundle.currentState, localCheckpoint) &&\n input.warmReferencedPrincipalPolicies\n ) {\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [principalPolicyReferenceFromBundle(bundle)],\n });\n bundle = await loadPrincipalPolicyBundle(\n execSql,\n \"organization\",\n input.organizationId,\n );\n localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n \"organization\",\n input.organizationId,\n );\n if (!bundle) {\n return undefined;\n }\n }\n\n return { bundle, localCheckpoint };\n}\n\nfunction assertReservedAdminsPolicyShape(\n policy: VerifiedPrincipalPolicy,\n): void {\n const history = policy.history ?? [{ projection: policy.projection }];\n if (\n history.some(\n (entry) =>\n entry.projection.length === 0 ||\n entry.projection.some((member) => member.role !== \"admin\"),\n )\n ) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"reserved Admins policy must contain only direct admin users\",\n );\n }\n}\n\nasync function verifyOrganizationAdminsPolicy(input: {\n adminGroupId: string;\n execSql: ProjectionCheckpointContext[\"execSql\"];\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await loadPrincipalPolicyBundle(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n if (!adminBundle) {\n return undefined;\n }\n if (\n !principalHeadMatchesReference(\n principalPolicyReferenceFromBundle(adminBundle),\n input.expectedHead,\n )\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"Admins policy does not match the signed organization directory\",\n );\n }\n const adminCheckpoint = await loadPrincipalPolicyCheckpoint(\n input.execSql,\n \"group\",\n input.adminGroupId,\n );\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: adminBundle,\n label: `Admins policy ${input.adminGroupId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyPrincipalPolicyBundle({\n bundle: adminBundle,\n expectedReference: input.expectedHead,\n localCheckpoint: adminCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n assertReservedAdminsPolicyShape(verified.value);\n return verified.value;\n}\n\nasync function loadOrganizationExternalAuthority(\n input: OrganizationAdminPolicyInput,\n): Promise<ReturnType<typeof organizationAdminExternalAuthority> | null> {\n const organizationPolicy = await loadOrganizationPolicyForVerification(input);\n if (!organizationPolicy) {\n return null;\n }\n\n try {\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle: organizationPolicy.bundle,\n label: `Organization policy ${input.organizationId}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified = await verifyOrganizationAdminPolicy({\n bundle: organizationPolicy.bundle,\n localCheckpoint: organizationPolicy.localCheckpoint,\n organizationId: input.organizationId,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n const descriptor = parseOrganizationAuthorityDescriptor(\n organizationPolicy.bundle.currentPayload.ciphertext,\n );\n if (descriptor.organizationId !== input.organizationId) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"organization authority descriptor scope does not match\",\n );\n }\n const verifiedAdmins = await verifyOrganizationAdminsPolicy({\n adminGroupId: descriptor.adminGroupId,\n execSql: input.checkpointContext.execSql,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n });\n if (!verifiedAdmins) {\n return null;\n }\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n observePrincipalPolicy(\n input.checkpointContext,\n verifiedAdmins,\n input.organizationId,\n );\n return organizationAdminExternalAuthority(verifiedAdmins);\n } catch (error) {\n rethrowProjectionVerificationBoundaryError(error);\n if (error instanceof KeyingVerificationError) {\n throw error;\n }\n return null;\n }\n}\n\nasync function verifyReferencedPrincipalPolicy(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n reference: ReferencedPrincipalHead;\n stillCurrent?: (() => boolean) | undefined;\n resolveUserKey: ProjectionUserKeyResolver;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence> {\n // Scoped recovery carries organization, dependency and lifetime bindings.\n // A bare policy cache entry cannot replace those bindings.\n const recovered = await resolveReferencedPrincipalPolicy(input);\n if (recovered) return recovered;\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await loadPrincipalPolicyCheckpoint(\n execSql,\n input.reference.principalType,\n input.reference.principalId,\n );\n if (cachedPolicy && !(\"retainedHistory\" in cachedPolicy)) {\n if (\n !verifiedPrincipalPolicyContainsReference(cachedPolicy, input.reference)\n ) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n \"in-memory principal policy cache does not match its exact reference\",\n );\n }\n if (verifiedPrincipalPolicyMeetsCheckpoint(cachedPolicy, localCheckpoint)) {\n observePrincipalPolicy(\n input.checkpointContext,\n cachedPolicy,\n input.organizationId,\n );\n return cachedPolicy;\n }\n }\n\n const referenceLabel = principalPolicyReferenceLabel(input.reference);\n let bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n if (!bundle && input.warmReferencedPrincipalPolicies) {\n // The reference is not cached locally — the common case for a member who\n // gained access via another org's group grant and never hydrated that\n // group's policy. Fetch+verify+persist it, then re-read from the cache.\n await input.warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: [input.reference],\n });\n bundle = await loadPrincipalPolicyBundleForReference(\n execSql,\n input.reference,\n localCheckpoint,\n );\n }\n if (!bundle) {\n throw new PrincipalPolicyNotCachedError(referenceLabel);\n }\n\n const signerPublicKeys = await collectPrincipalPolicySignerPublicKeys({\n bundle,\n label: `Principal policy ${referenceLabel}`,\n resolveUserKey: input.resolveUserKey,\n });\n const verified =\n await verifyPrincipalPolicyBundleWithExternalOrganizationAdmins({\n bundle,\n expectedReference: input.reference,\n loadExternalAuthority: () =>\n loadOrganizationExternalAuthority({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n\n observePrincipalPolicy(\n input.checkpointContext,\n verified.value,\n input.organizationId,\n );\n input.principalPolicyCache.set(cacheKey, verified.value);\n return verified.value;\n}\n\nexport async function collectReferencedPrincipalPolicies(input: {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n principalPolicyCache: PrincipalPolicyCache;\n references: readonly ReferencedPrincipalHead[];\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n}): Promise<PrincipalPolicyCurrentEvidence[]> {\n const warmReferencedPrincipalPolicies =\n generationGuardedPrincipalPolicyWarmer(\n input.warmReferencedPrincipalPolicies,\n input.stillCurrent,\n );\n const uniqueReferences = new Map<string, ReferencedPrincipalHead>();\n for (const reference of input.references) {\n uniqueReferences.set(referencedPrincipalPolicyKey(reference), reference);\n }\n\n const references = [...uniqueReferences.values()];\n // Warm every missing reference in one batched fetch before verifying, so a\n // path that references several uncached policies makes a single round of\n // requests rather than one per reference.\n if (\n warmReferencedPrincipalPolicies &&\n !warmReferencedPrincipalPolicies.resolveReference\n ) {\n const uncached = await filterUncachedPrincipalPolicyReferences({\n execSql: input.checkpointContext.execSql,\n principalPolicyCache: input.principalPolicyCache,\n references,\n });\n if (uncached.length > 0) {\n assertProjectionVerificationCurrent(input.stillCurrent);\n await warmReferencedPrincipalPolicies({\n organizationId: input.organizationId,\n references: uncached,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n }\n }\n\n // The warmer's operation shares one recovery view across its collections.\n return Promise.all(\n references.map((reference) =>\n verifyReferencedPrincipalPolicy({\n checkpointContext: input.checkpointContext,\n organizationId: input.organizationId,\n principalPolicyCache: input.principalPolicyCache,\n reference,\n stillCurrent: input.stillCurrent,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies,\n }),\n ),\n );\n}\n"]}
@@ -1,10 +1,10 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { loadPrincipalPolicyCheckpoint } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
- import { verifiedPrincipalPolicyMeetsCheckpoint } from "../../persistence/principalPolicy/principalPolicyCheckpointSelection.js";
4
3
  import { observePrincipalPolicy, } from "../checkpoints/checkpointContext.js";
5
4
  import { observeProjectionLifetime } from "../projectionLifetimes.js";
6
5
  import { assertProjectionVerificationCurrent, } from "../types.js";
7
6
  import { referencedPrincipalPolicyKey, verifiedPrincipalPolicyContainsReference, } from "./principalPolicyCache.js";
7
+ import { verifiedPrincipalPolicyMeetsCheckpoint } from "./principalPolicyCheckpointSelection.js";
8
8
  // Scoped evidence is always resolved through the warmer: its operation memo is
9
9
  // the only reuse of recovered directory and Admins evidence, with one set of
10
10
  // validity rules. The caller's policy cache keeps bare verified policies; it
@@ -1 +1 @@
1
- {"version":3,"file":"resolvedPrincipalPolicy.js","sourceRoot":"","sources":["resolvedPrincipalPolicy.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,6BAA6B,EAAE,MAAM,iEAAiE,CAAC;AAChH,OAAO,EAAE,sCAAsC,EAAE,MAAM,sEAAsE,CAAC;AAC9H,OAAO,EACL,sBAAsB,GAEvB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EACL,mCAAmC,GAIpC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,4BAA4B,EAC5B,wCAAwC,GACzC,MAAM,wBAAwB,CAAC;AAEhC,+EAA+E;AAC/E,6EAA6E;AAC7E,6EAA6E;AAC7E,qEAAqE;AACrE,KAAK,UAAU,gBAAgB,CAC7B,OAAoC,EACpC,MAAuC,EACvC,cAAuB;IAEvB,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QAC7D,MAAM,UAAU,GAAG,MAAM,6BAA6B,CACpD,OAAO,CAAC,OAAO,EACf,MAAM,CAAC,aAAa,EACpB,MAAM,CAAC,WAAW,CACnB,CAAC;QACF,IACE,cAAc;YACd,UAAU;YACV,CAAC,MAAM,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO;gBAClC,CAAC,MAAM,CAAC,OAAO,GAAG,UAAU,CAAC,OAAO;oBAClC,CAAC,MAAM,CAAC,eAAe,CAAC,IAAI,CAC1B,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,OAAO,KAAK,UAAU,CAAC,OAAO,CACtD,CAAC,CAAC;YAEP,OAAO,KAAK,CAAC;QACf,IAAI,CAAC,sCAAsC,CAAC,MAA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C1D,MAAM,OAAO,GAAG,KAAK,CAAC,+BAA+B,EAAE,gBAAgB,CAAC;IACxE,IAAI,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC;IAC1B,MAAM,MAAM,GAAG,MAAM,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACrD,MAAM,eAAe,GAAG,MAAM,CAAC,YAAY,CAAC;IAC5C,2EAA2E;IAC3E,mEAAmE;IACnE,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,IAAI,eAAe,EAAE,CAAC;IAC7E,mCAAmC,CAAC,QAAQ,CAAC,CAAC;IAC9C,yBAAyB,CAAC,KAAK,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;IAC7D,IAAI,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAChD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;IACJ,IAAI,CAAC,wCAAwC,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC;QAC3E,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kEAAkE,CACnE,CAAC;IACJ,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC;QAC1D,sBAAsB,CACpB,KAAK,CAAC,iBAAiB,EACvB,MAAM,EACN,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,KAAK,CAAC,oBAAoB,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnD,OAAO,MAAM,CAAC,MAAM,CAAC;AACvB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"../../persistence/principalPolicy/principalPolicyCheckpointSelection\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { observeProjectionLifetime } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyCache,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../types\";\nimport {\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\n\n// Scoped evidence is always resolved through the warmer: its operation memo is\n// the only reuse of recovered directory and Admins evidence, with one set of\n// validity rules. The caller's policy cache keeps bare verified policies; it\n// never stands in for organization, dependency or lifetime bindings.\nasync function meetsCheckpoints(\n context: ProjectionCheckpointContext,\n result: ResolvedPrincipalPolicyEvidence,\n refreshMissing: boolean,\n): Promise<boolean> {\n for (const policy of [...result.dependencies, result.policy]) {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n context.execSql,\n policy.principalType,\n policy.principalId,\n );\n if (\n refreshMissing &&\n checkpoint &&\n (policy.version < checkpoint.version ||\n (policy.version > checkpoint.version &&\n !policy.retainedHistory.some(\n (entry) => entry.state.version === checkpoint.version,\n )))\n )\n return false;\n if (!verifiedPrincipalPolicyMeetsCheckpoint(policy, checkpoint))\n throw new KeyingVerificationError(\n \"rollback\",\n \"Recovered principal evidence predates the durable checkpoint\",\n );\n }\n return true;\n}\n\ninterface ResolveReferencedPrincipalPolicyInput {\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly organizationId: string;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly reference: ReferencedPrincipalHead;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nasync function recoverEvidence(\n input: ResolveReferencedPrincipalPolicyInput,\n resolve: NonNullable<ReferencedPrincipalPolicyWarmer[\"resolveReference\"]>,\n): Promise<ResolvedPrincipalPolicyEvidence> {\n const read = async (recoveryBatch?: object) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const recovered = await resolve({\n recoveryBatch,\n organizationId: input.organizationId,\n reference: input.reference,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n return recovered;\n };\n let result = await read();\n // A concurrent admission may advance a pin after recovery verified it.\n // Refresh once outside the operation's directory view; the fresh\n // recovery and final checkpoint check still reject rollback/equivocation.\n if (!(await meetsCheckpoints(input.checkpointContext, result, true))) {\n assertProjectionVerificationCurrent(result.stillCurrent);\n result = await read({});\n await meetsCheckpoints(input.checkpointContext, result, false);\n }\n return result;\n}\n\nexport async function resolveReferencedPrincipalPolicy(\n input: ResolveReferencedPrincipalPolicyInput,\n): Promise<VerifiedPrincipalPolicyCurrent | null> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const key = referencedPrincipalPolicyKey(input.reference);\n const resolve = input.warmReferencedPrincipalPolicies?.resolveReference;\n if (!resolve) return null;\n const result = await recoverEvidence(input, resolve);\n const evidenceCurrent = result.stillCurrent;\n // The consumer's and every producer's lifetime guard the evidence where it\n // is used: projection admission rechecks them through the context.\n const lifetime = () => input.stillCurrent?.() !== false && evidenceCurrent();\n assertProjectionVerificationCurrent(lifetime);\n observeProjectionLifetime(input.checkpointContext, lifetime);\n if (result.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence belongs to another organization\",\n );\n if (!verifiedPrincipalPolicyContainsReference(result.policy, input.reference))\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence does not contain the exact citation\",\n );\n for (const policy of [...result.dependencies, result.policy])\n observePrincipalPolicy(\n input.checkpointContext,\n policy,\n input.organizationId,\n );\n input.principalPolicyCache.set(key, result.policy);\n return result.policy;\n}\n"]}
1
+ {"version":3,"file":"resolved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C,OAAO;QAAE,OAAO,IAAI,CAAC;IAC1B,MAAM,MAAM,GAAG,MAAM,eAAe,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;IACrD,MAAM,eAAe,GAAG,MAAM,CAAC,YAAY,CAAC;IAC5C,2EAA2E;IAC3E,mEAAmE;IACnE,MAAM,QAAQ,GAAG,GAAG,EAAE,CAAC,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK,IAAI,eAAe,EAAE,CAAC;IAC7E,mCAAmC,CAAC,QAAQ,CAAC,CAAC;IAC9C,yBAAyB,CAAC,KAAK,CAAC,iBAAiB,EAAE,QAAQ,CAAC,CAAC;IAC7D,IAAI,MAAM,CAAC,cAAc,KAAK,KAAK,CAAC,cAAc;QAChD,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,8DAA8D,CAC/D,CAAC;IACJ,IAAI,CAAC,wCAAwC,CAAC,MAAM,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,CAAC;QAC3E,MAAM,IAAI,uBAAuB,CAC/B,iBAAiB,EACjB,kEAAkE,CACnE,CAAC;IACJ,KAAK,MAAM,MAAM,IAAI,CAAC,GAAG,MAAM,CAAC,YAAY,EAAE,MAAM,CAAC,MAAM,CAAC;QAC1D,sBAAsB,CACpB,KAAK,CAAC,iBAAiB,EACvB,MAAM,EACN,KAAK,CAAC,cAAc,CACrB,CAAC;IACJ,KAAK,CAAC,oBAAoB,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,MAAM,CAAC,CAAC;IACnD,OAAO,MAAM,CAAC,MAAM,CAAC;AACvB,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicyCurrent,\n} from \"@tearleads/crypto\";\nimport { loadPrincipalPolicyCheckpoint } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { observeProjectionLifetime } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyCache,\n type ReferencedPrincipalPolicyWarmer,\n type ResolvedPrincipalPolicyEvidence,\n} from \"../types\";\nimport {\n referencedPrincipalPolicyKey,\n verifiedPrincipalPolicyContainsReference,\n} from \"./principalPolicyCache\";\nimport { verifiedPrincipalPolicyMeetsCheckpoint } from \"./principalPolicyCheckpointSelection\";\n\n// Scoped evidence is always resolved through the warmer: its operation memo is\n// the only reuse of recovered directory and Admins evidence, with one set of\n// validity rules. The caller's policy cache keeps bare verified policies; it\n// never stands in for organization, dependency or lifetime bindings.\nasync function meetsCheckpoints(\n context: ProjectionCheckpointContext,\n result: ResolvedPrincipalPolicyEvidence,\n refreshMissing: boolean,\n): Promise<boolean> {\n for (const policy of [...result.dependencies, result.policy]) {\n const checkpoint = await loadPrincipalPolicyCheckpoint(\n context.execSql,\n policy.principalType,\n policy.principalId,\n );\n if (\n refreshMissing &&\n checkpoint &&\n (policy.version < checkpoint.version ||\n (policy.version > checkpoint.version &&\n !policy.retainedHistory.some(\n (entry) => entry.state.version === checkpoint.version,\n )))\n )\n return false;\n if (!verifiedPrincipalPolicyMeetsCheckpoint(policy, checkpoint))\n throw new KeyingVerificationError(\n \"rollback\",\n \"Recovered principal evidence predates the durable checkpoint\",\n );\n }\n return true;\n}\n\ninterface ResolveReferencedPrincipalPolicyInput {\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly organizationId: string;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly reference: ReferencedPrincipalHead;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n}\n\nasync function recoverEvidence(\n input: ResolveReferencedPrincipalPolicyInput,\n resolve: NonNullable<ReferencedPrincipalPolicyWarmer[\"resolveReference\"]>,\n): Promise<ResolvedPrincipalPolicyEvidence> {\n const read = async (recoveryBatch?: object) => {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const recovered = await resolve({\n recoveryBatch,\n organizationId: input.organizationId,\n reference: input.reference,\n stillCurrent: input.stillCurrent,\n });\n assertProjectionVerificationCurrent(input.stillCurrent);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n return recovered;\n };\n let result = await read();\n // A concurrent admission may advance a pin after recovery verified it.\n // Refresh once outside the operation's directory view; the fresh\n // recovery and final checkpoint check still reject rollback/equivocation.\n if (!(await meetsCheckpoints(input.checkpointContext, result, true))) {\n assertProjectionVerificationCurrent(result.stillCurrent);\n result = await read({});\n await meetsCheckpoints(input.checkpointContext, result, false);\n }\n return result;\n}\n\nexport async function resolveReferencedPrincipalPolicy(\n input: ResolveReferencedPrincipalPolicyInput,\n): Promise<VerifiedPrincipalPolicyCurrent | null> {\n assertProjectionVerificationCurrent(input.stillCurrent);\n const key = referencedPrincipalPolicyKey(input.reference);\n const resolve = input.warmReferencedPrincipalPolicies?.resolveReference;\n if (!resolve) return null;\n const result = await recoverEvidence(input, resolve);\n const evidenceCurrent = result.stillCurrent;\n // The consumer's and every producer's lifetime guard the evidence where it\n // is used: projection admission rechecks them through the context.\n const lifetime = () => input.stillCurrent?.() !== false && evidenceCurrent();\n assertProjectionVerificationCurrent(lifetime);\n observeProjectionLifetime(input.checkpointContext, lifetime);\n if (result.organizationId !== input.organizationId)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence belongs to another organization\",\n );\n if (!verifiedPrincipalPolicyContainsReference(result.policy, input.reference))\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Recovered principal evidence does not contain the exact citation\",\n );\n for (const policy of [...result.dependencies, result.policy])\n observePrincipalPolicy(\n input.checkpointContext,\n policy,\n input.organizationId,\n );\n input.principalPolicyCache.set(key, result.policy);\n return result.policy;\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { and, eq, inArray } from "drizzle-orm";
2
+ import { DOCUMENTS_APP_KIND } from "../../documents/documentConstants.js";
2
3
  import { documents, inLocalIntentLane, LOCAL_INTENT_LANES, localIntents, } from "../../sqlite/schema/index.js";
3
- import { DOCUMENTS_APP_KIND } from "../documents/internal/constants.js";
4
4
  export async function loadDocumentMovePlacement(tx, documentId) {
5
5
  const [intent] = await tx
6
6
  .select({
@@ -1 +1 @@
1
- {"version":3,"file":"documentPlacement.js","sourceRoot":"","sources":["documentPlacement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAE7B,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAarE,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,EAAgC,EAChC,UAAkB;IAElB,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC;QACN,EAAE,EAAE,YAAY,CAAC,EAAE;QACnB,UAAU,EAAE,YAAY,CAAC,UAAU;QACnC,iBAAiB,EAAE,YAAY,CAAC,iBAAiB;KAClD,CAAC;SACD,IAAI,CAAC,YAAY,CAAC;SAClB,KAAK,CACJ,GAAG,CACD,iBAAiB,CAAC,kBAAkB,CAAC,iBAAiB,CAAC,EACvD,EAAE,CAAC,YAAY,CAAC,SAAS,EAAE,UAAU,CAAC,CACvC,CACF;SACA,KAAK,CAAC,CAAC,CAAC,CAAC;IACZ,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,2FAA2F;AAC3F,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,EAAgC,EAChC,MAAyC,EACzC,OAAuC;IAEvC,MAAM,GAAG,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,IAAI,GAAG,CACrB,CACE,MAAM,EAAE;SACL,MAAM,CAAC;QAC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IACR,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QAC7B,IAAI,OAAO,EAAE,YAAY;YACvB,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,KAAK,OAAO,CAAC,YAAY,CAAC;QAChE,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC;YAAE,OAAO,KAAK,CAAC;QAChD,OAAO,CACL,KAAK,CAAC,WAAW,KAAK,SAAS;YAC/B,KAAK,CAAC,WAAW,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CACzD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, inArray } from \"drizzle-orm\";\nimport {\n documents,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { DOCUMENTS_APP_KIND } from \"../documents/internal/constants\";\n\nexport interface DocumentPlacementInput {\n documentId: string;\n containerIds: ReadonlyArray<string>;\n accessEpoch?: number | undefined;\n}\n\nexport interface DocumentPlacementWriteOptions {\n stillCurrent?: (() => boolean) | undefined;\n moveIntentId?: string | undefined;\n}\n\nexport async function loadDocumentMovePlacement(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n) {\n const [intent] = await tx\n .select({\n id: localIntents.id,\n intentType: localIntents.intentType,\n targetContainerId: localIntents.targetContainerId,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, documentId),\n ),\n )\n .limit(1);\n return intent;\n}\n\n/** Check at commit time: neither intermediate replay nor discovery owns a pending move. */\nexport async function filterWritableDocumentPlacements(\n tx: ClientSQLiteTransactionScope,\n inputs: readonly DocumentPlacementInput[],\n options?: DocumentPlacementWriteOptions,\n): Promise<readonly DocumentPlacementInput[]> {\n const ids = inputs.map((input) => input.documentId);\n const intents = new Map(\n (\n await tx\n .select({\n documentId: localIntents.subjectId,\n id: localIntents.id,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n inArray(localIntents.subjectId, ids),\n ),\n )\n ).map((row) => [row.documentId, row.id]),\n );\n const versionedIds = inputs\n .filter((input) => input.accessEpoch !== undefined)\n .map((input) => input.documentId);\n const epochs = new Map<string, number>();\n if (versionedIds.length > 0) {\n const rows = await tx\n .select({\n documentId: documents.documentId,\n accessEpoch: documents.accessEpoch,\n })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n inArray(documents.documentId, versionedIds),\n ),\n );\n for (const row of rows)\n if (row.documentId)\n epochs.set(\n row.documentId,\n Math.max(epochs.get(row.documentId) ?? 0, row.accessEpoch),\n );\n }\n return inputs.filter((input) => {\n if (options?.moveIntentId)\n return intents.get(input.documentId) === options.moveIntentId;\n if (intents.has(input.documentId)) return false;\n return (\n input.accessEpoch === undefined ||\n input.accessEpoch >= (epochs.get(input.documentId) ?? 0)\n );\n });\n}\n"]}
1
+ {"version":3,"file":"documentPlacement.js","sourceRoot":"","sources":["documentPlacement.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,EAAE,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,kBAAkB,EAAE,MAAM,mCAAmC,CAAC;AACvE,OAAO,EACL,SAAS,EACT,iBAAiB,EACjB,kBAAkB,EAClB,YAAY,GACb,MAAM,qBAAqB,CAAC;AAc7B,MAAM,CAAC,KAAK,UAAU,yBAAyB,CAC7C,EAAgC,EAChC,UAAkB;IAElB,MAAM,CAAC,MAAM,CAAC,GAAG,MAAM,EAAE;SACtB,MAAM,CAAC;QACN,EAAE,EAAE,YAAY,CAAC,EAAE;QACnB,UAAU,EAAE,YAAY,CAAC,UAAU;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CAAC;QAC5B,MAAM,IAAI,GAAG,MAAM,EAAE;aAClB,MAAM,CAAC;YACN,UAAU,EAAE,SAAS,CAAC,UAAU;YAChC,WAAW,EAAE,SAAS,CAAC,WAAW;SACnC,CAAC;aACD,IAAI,CAAC,SAAS,CAAC;aACf,KAAK,CACJ,GAAG,CACD,EAAE,CAAC,SAAS,CAAC,OAAO,EAAE,kBAAkB,CAAC,EACzC,OAAO,CAAC,SAAS,CAAC,UAAU,EAAE,YAAY,CAAC,CAC5C,CACF,CAAC;QACJ,KAAK,MAAM,GAAG,IAAI,IAAI;YACpB,IAAI,GAAG,CAAC,UAAU;gBAChB,MAAM,CAAC,GAAG,CACR,GAAG,CAAC,UAAU,EACd,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,GAAG,CAAC,WAAW,CAAC,CAC3D,CAAC;IACR,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;QAC7B,IAAI,OAAO,EAAE,YAAY;YACvB,OAAO,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,KAAK,OAAO,CAAC,YAAY,CAAC;QAChE,IAAI,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC;YAAE,OAAO,KAAK,CAAC;QAChD,OAAO,CACL,KAAK,CAAC,WAAW,KAAK,SAAS;YAC/B,KAAK,CAAC,WAAW,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CACzD,CAAC;IACJ,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { and, eq, inArray } from \"drizzle-orm\";\nimport { DOCUMENTS_APP_KIND } from \"../../documents/documentConstants\";\nimport {\n documents,\n inLocalIntentLane,\n LOCAL_INTENT_LANES,\n localIntents,\n} from \"../../sqlite/schema\";\nimport type { ClientSQLiteTransactionScope } from \"../../sqlite/sqlitePersistenceRuntime\";\n\nexport interface DocumentPlacementInput {\n documentId: string;\n containerIds: ReadonlyArray<string>;\n accessEpoch?: number | undefined;\n}\n\nexport interface DocumentPlacementWriteOptions {\n stillCurrent?: (() => boolean) | undefined;\n moveIntentId?: string | undefined;\n}\n\nexport async function loadDocumentMovePlacement(\n tx: ClientSQLiteTransactionScope,\n documentId: string,\n) {\n const [intent] = await tx\n .select({\n id: localIntents.id,\n intentType: localIntents.intentType,\n targetContainerId: localIntents.targetContainerId,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n eq(localIntents.subjectId, documentId),\n ),\n )\n .limit(1);\n return intent;\n}\n\n/** Check at commit time: neither intermediate replay nor discovery owns a pending move. */\nexport async function filterWritableDocumentPlacements(\n tx: ClientSQLiteTransactionScope,\n inputs: readonly DocumentPlacementInput[],\n options?: DocumentPlacementWriteOptions,\n): Promise<readonly DocumentPlacementInput[]> {\n const ids = inputs.map((input) => input.documentId);\n const intents = new Map(\n (\n await tx\n .select({\n documentId: localIntents.subjectId,\n id: localIntents.id,\n })\n .from(localIntents)\n .where(\n and(\n inLocalIntentLane(LOCAL_INTENT_LANES.documentPlacement),\n inArray(localIntents.subjectId, ids),\n ),\n )\n ).map((row) => [row.documentId, row.id]),\n );\n const versionedIds = inputs\n .filter((input) => input.accessEpoch !== undefined)\n .map((input) => input.documentId);\n const epochs = new Map<string, number>();\n if (versionedIds.length > 0) {\n const rows = await tx\n .select({\n documentId: documents.documentId,\n accessEpoch: documents.accessEpoch,\n })\n .from(documents)\n .where(\n and(\n eq(documents.appKind, DOCUMENTS_APP_KIND),\n inArray(documents.documentId, versionedIds),\n ),\n );\n for (const row of rows)\n if (row.documentId)\n epochs.set(\n row.documentId,\n Math.max(epochs.get(row.documentId) ?? 0, row.accessEpoch),\n );\n }\n return inputs.filter((input) => {\n if (options?.moveIntentId)\n return intents.get(input.documentId) === options.moveIntentId;\n if (intents.has(input.documentId)) return false;\n return (\n input.accessEpoch === undefined ||\n input.accessEpoch >= (epochs.get(input.documentId) ?? 0)\n );\n });\n}\n"]}
@@ -1,8 +1,8 @@
1
1
  import { and, eq, max } from "drizzle-orm";
2
+ import { DOCUMENTS_APP_KIND } from "../../documents/documentConstants.js";
2
3
  import { containerDocumentTombstoneHolds, documentContainerProjectionTables, documents, documentTables, } from "../../sqlite/schema/index.js";
3
4
  import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
4
5
  import { ensureSqlTables, runSerializedSqlMutation, } from "../../sqlite/sqlSchema.js";
5
- import { DOCUMENTS_APP_KIND } from "./internal/constants.js";
6
6
  import { deleteContainerDocumentTombstoneHoldRows, holdContainerDocumentTombstonesInTransaction, listContainerDocumentTombstoneHoldsForDocumentsInTransaction, listContainerDocumentTombstoneHoldsInTransaction, listKnownContainerDocumentPlacementsInTransaction, partitionContainerDocumentTombstoneHolds, } from "./internal/containerDocumentTombstoneHolds.js";
7
7
  export { containerDocumentPlacementKey, deleteContainerDocumentTombstoneHoldRowsForLinks, deleteContainerDocumentTombstoneHoldsForContainers, deleteContainerDocumentTombstoneHoldsForDocuments, } from "./internal/containerDocumentTombstoneHolds.js";
8
8
  /**