@tearleads/client-sdk 0.1.223 → 0.1.225

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 (89) hide show
  1. package/client/organizations/organizationMemberships.d.ts +1 -1
  2. package/client/organizations/organizationMemberships.js +1 -1
  3. package/client/organizations/organizationMemberships.js.map +1 -1
  4. package/data/documents/shared/containerKek/containerKekPathVerification.js +2 -0
  5. package/data/documents/shared/containerKek/containerKekPathVerification.js.map +1 -1
  6. package/data/documents/shared/projection/index.js +2 -0
  7. package/data/documents/shared/projection/index.js.map +1 -1
  8. package/data/keyingProjectionVerification/checkpoints/checkpointContext.d.ts +3 -0
  9. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +2 -1
  10. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  11. package/data/keyingProjectionVerification/container/containerDestinationVerification.d.ts +2 -1
  12. package/data/keyingProjectionVerification/container/containerDestinationVerification.js +1 -0
  13. package/data/keyingProjectionVerification/container/containerDestinationVerification.js.map +1 -1
  14. package/data/keyingProjectionVerification/container/containerProjectionVerification.d.ts +3 -2
  15. package/data/keyingProjectionVerification/container/containerProjectionVerification.js +2 -0
  16. package/data/keyingProjectionVerification/container/containerProjectionVerification.js.map +1 -1
  17. package/data/keyingProjectionVerification/document/documentProjectionVerification.d.ts +2 -1
  18. package/data/keyingProjectionVerification/document/documentProjectionVerification.js +2 -0
  19. package/data/keyingProjectionVerification/document/documentProjectionVerification.js.map +1 -1
  20. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js +3 -2
  21. package/data/keyingProjectionVerification/documentPurge/documentPurgeCheckpointCurrency.js.map +1 -1
  22. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.d.ts +2 -1
  23. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js +7 -3
  24. package/data/keyingProjectionVerification/documentPurge/documentPurgeProofVerification.js.map +1 -1
  25. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js +3 -2
  26. package/data/keyingProjectionVerification/principalPolicy/principalPolicyCache.js.map +1 -1
  27. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js +17 -6
  28. package/data/keyingProjectionVerification/principalPolicy/principalPolicyVerification.js.map +1 -1
  29. package/data/keyingProjectionVerification/types.d.ts +20 -2
  30. package/data/keyingProjectionVerification/types.js.map +1 -1
  31. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js +2 -0
  32. package/data/persistence/principalPolicy/principalPolicyBundleRepository.js.map +1 -1
  33. package/package.json +1 -1
  34. package/stores/container-contents/operations/forgetOrganizationContentOperation.js +1 -1
  35. package/stores/container-contents/operations/forgetOrganizationContentOperation.js.map +1 -1
  36. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js +1 -1
  37. package/stores/documents/documentStore/attachmentUpload/attachmentUploadLane.js.map +1 -1
  38. package/stores/documents/documentStore/initialization/index.js +1 -1
  39. package/stores/documents/documentStore/initialization/index.js.map +1 -1
  40. package/stores/documents/documentStore/storedDocument.js +1 -1
  41. package/stores/documents/documentStore/storedDocument.js.map +1 -1
  42. package/stores/documents/documentStore/sync/syncAttachments.js +1 -1
  43. package/stores/documents/documentStore/sync/syncAttachments.js.map +1 -1
  44. package/workflows/container-contents/container-state/create/createAdoption.js +2 -0
  45. package/workflows/container-contents/container-state/create/createAdoption.js.map +1 -1
  46. package/workflows/container-contents/container-state/purge/purgeTreeScope.js +2 -0
  47. package/workflows/container-contents/container-state/purge/purgeTreeScope.js.map +1 -1
  48. package/workflows/container-contents/container-state/share/groupGrantVerification.js +2 -0
  49. package/workflows/container-contents/container-state/share/groupGrantVerification.js.map +1 -1
  50. package/workflows/container-contents/container-state/share/index.js +2 -0
  51. package/workflows/container-contents/container-state/share/index.js.map +1 -1
  52. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js +2 -0
  53. package/workflows/container-contents/remoteHydration/destination/verifiedDestination.js.map +1 -1
  54. package/workflows/container-contents/syncPause/documentRemoval.js +1 -1
  55. package/workflows/container-contents/syncPause/documentRemoval.js.map +1 -1
  56. package/workflows/containers/child/create/index.d.ts +1 -1
  57. package/workflows/containers/child/create/index.js +2 -0
  58. package/workflows/containers/child/create/index.js.map +1 -1
  59. package/workflows/containers/child/move/moveWraps.js +3 -0
  60. package/workflows/containers/child/move/moveWraps.js.map +1 -1
  61. package/workflows/containers/child/rekey/carriedDescendantRekeys.js +2 -0
  62. package/workflows/containers/child/rekey/carriedDescendantRekeys.js.map +1 -1
  63. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js +2 -0
  64. package/workflows/containers/child/rotation/rotationPrincipalPolicies.js.map +1 -1
  65. package/workflows/containers/child/share/sharePlanCore.js +2 -0
  66. package/workflows/containers/child/share/sharePlanCore.js.map +1 -1
  67. package/workflows/containers/rematerialization/principalContainerRematerialization.js +2 -0
  68. package/workflows/containers/rematerialization/principalContainerRematerialization.js.map +1 -1
  69. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js +2 -0
  70. package/workflows/containers/rematerialization/principalContainerRematerializationPlanning.js.map +1 -1
  71. package/workflows/documents/create/index.js +2 -0
  72. package/workflows/documents/create/index.js.map +1 -1
  73. package/workflows/documents/linkSet/linkSetAuthority.js +2 -0
  74. package/workflows/documents/linkSet/linkSetAuthority.js.map +1 -1
  75. package/workflows/documents/purge/index.js +6 -0
  76. package/workflows/documents/purge/index.js.map +1 -1
  77. package/workflows/documents/sync/syncSubmittedResult.js +2 -0
  78. package/workflows/documents/sync/syncSubmittedResult.js.map +1 -1
  79. package/workflows/documents/syncFailures/syncRepairAccess.js +2 -0
  80. package/workflows/documents/syncFailures/syncRepairAccess.js.map +1 -1
  81. package/workflows/organizations/memberships/organizationMemberships.d.ts +1 -1
  82. package/workflows/organizations/memberships/organizationMemberships.js +1 -1
  83. package/workflows/organizations/memberships/organizationMemberships.js.map +1 -1
  84. package/workflows/sync/coordination.d.ts +6 -0
  85. package/workflows/sync/coordination.js +6 -0
  86. package/workflows/sync/coordination.js.map +1 -0
  87. package/workflows/sync/index.d.ts +1 -6
  88. package/workflows/sync/index.js +1 -5
  89. package/workflows/sync/index.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"documentProjectionVerification.js","sourceRoot":"","sources":["documentProjectionVerification.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EACL,mCAAmC,EACnC,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,8BAA8B,EAAE,MAAM,qDAAqD,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAMhD,OAAO,EAAE,iCAAiC,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAAE,iCAAiC,EAAE,MAAM,gCAAgC,CAAC;AAKnF,SAAS,oCAAoC,CAC3C,UAA4C;IAE5C,OAAO;QACL,GAAG,UAAU,CAAC,8BAA8B;QAC5C,GAAG,UAAU,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;KACjE,CAAC;AACJ,CAAC;AAED,SAAS,yCAAyC,CAChD,UAA4C;IAE5C,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC1E,KAAK,MAAM,CAAC,KAAK,EAAE,WAAW,CAAC,IAAI,4BAA4B,CAC7D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AAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\n VerifiedContainerAccessManifest,\n VerifiedDocumentLinkSetManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyContainerManifestPath } from \"../container/containerPathVerification\";\nimport {\n addContainerWriterProjectionBundles,\n verifiedContainerManifestsForBundles,\n verifyContainerWriterProjectionWithContext,\n} from \"../container/containerProjectionVerification\";\nimport { rejectPurgedDocumentProjection } from \"../documentPurge/documentPurgeCheckpointEnforcement\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { readAccessManifest } from \"../readers\";\nimport type {\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { withGenerationGuardedPolicyWarmer } from \"../types\";\nimport { documentContainerProjections } from \"./documentContainerProjections\";\nimport { verifyDocumentProjectionManifests } from \"./documentManifestVerification\";\n\ntype VerifiedManifestMap = Map<string, VerifiedContainerAccessManifest>;\ntype PolicyWarmer = ReferencedPrincipalPolicyWarmer | undefined;\n\nfunction readDocumentProjectionContainerPaths(\n projection: DocumentWriterProjectionResponse,\n): AccessManifestBundleWireResponse[][] {\n return [\n ...projection.documentManifestContainerPaths,\n ...projection.authorizingContainerPaths.map((path) => path.path),\n ];\n}\n\nfunction collectDocumentProjectionContainerBundles(\n projection: DocumentWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n for (const [index, authorizing] of documentContainerProjections(\n projection,\n ).entries()) {\n addContainerWriterProjectionBundles(\n bundlesByHash,\n authorizing,\n `Document writer projection authorizing path[${index}]`,\n );\n }\n for (const [index, path] of readDocumentProjectionContainerPaths(\n projection,\n ).entries()) {\n for (const [pathIndex, bundle] of path.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection dependency path[${index}][${pathIndex}]`,\n );\n }\n }\n for (const [\n index,\n bundle,\n ] of projection.documentContainerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection container history[${index}]`,\n );\n }\n return bundlesByHash;\n}\n\nasync function verifyProjectionContainerPaths(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}): Promise<Map<string, readonly VerifiedContainerAccessManifest[]>> {\n const bundlesByHash = collectDocumentProjectionContainerBundles(\n input.projection,\n );\n const containerPathByManifestHash = new Map<\n string,\n readonly VerifiedContainerAccessManifest[]\n >();\n // Reuse a caller-supplied cache when provided so a later unwrap pass over the\n // same authorizing container paths does not re-verify identical manifests.\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n for (const projection of documentContainerProjections(input.projection)) {\n const path = await verifyContainerWriterProjectionWithContext(\n {\n authorizationEvidence: input.authorizationEvidence,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n input.checkpointContext,\n );\n const leaf = path.at(-1);\n if (leaf) {\n containerPathByManifestHash.set(leaf.manifestHash, path);\n }\n for (const manifest of path) {\n verifiedByHash.set(manifest.manifestHash, manifest);\n }\n }\n // Grouping supplies evidence only; each signed artifact selects its citations.\n for (const [\n index,\n path,\n ] of input.projection.documentManifestContainerPaths.entries()) {\n // Historical dependency evidence is verified without current checkpoint\n // enforcement. Its grouping cannot substitute an uncited ancestor into\n // document or content-write authorization.\n const verifiedPath = await verifyContainerManifestPath({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoints: false,\n label: `Document writer projection dependency path[${index}]`,\n path,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The authorizing path recorded for the same leaf takes precedence.\n const leaf = verifiedPath.at(-1);\n if (leaf && !containerPathByManifestHash.has(leaf.manifestHash)) {\n containerPathByManifestHash.set(leaf.manifestHash, verifiedPath);\n }\n }\n\n // Keep every verified head as evidence. Events and content headers select\n // their own signed paths through resolveEventContainerPaths.\n for (const [hash, manifest] of verifiedByHash) {\n if (!containerPathByManifestHash.has(hash))\n containerPathByManifestHash.set(hash, [manifest]);\n }\n\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [],\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n return containerPathByManifestHash;\n}\n\ninterface DocumentWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}\nexport interface DocumentWriterProjectionAuthorization {\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly documentManifestByHash: ReadonlyMap<\n string,\n VerifiedDocumentLinkSetManifest\n >;\n readonly principalPolicies: readonly PrincipalPolicyAuthorization[];\n}\n\ninterface VerifiedDocumentWriterProjectionResult {\n readonly authorization: DocumentWriterProjectionAuthorization;\n readonly headManifest: VerifiedDocumentLinkSetManifest;\n}\n\nasync function verifyDocumentWriterProjectionWithContext(\n input: Omit<DocumentWriterProjectionVerificationInput, \"execSql\">,\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedDocumentWriterProjectionResult> {\n const principalPolicyCache =\n input.principalPolicyCache ?? new Map<string, VerifiedPrincipalPolicy>();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [\n input.projection.documentManifest,\n ...input.projection.documentManifestHistory,\n ...collectDocumentProjectionContainerBundles(input.projection).values(),\n ],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: readAccessManifest(\n input.projection.documentManifest.manifest,\n \"Document projection manifest\",\n ).organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const containerPathByManifestHash = await verifyProjectionContainerPaths({\n authorizationEvidence,\n checkpointContext,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const { headManifest, verifiedByHash } =\n await verifyDocumentProjectionManifests({\n authorizationEvidence,\n checkpointContext,\n containerPathByManifestHash,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await rejectPurgedDocumentProjection(\n headManifest.state.documentId,\n checkpointContext.execSql,\n );\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: [headManifest],\n verifiedManifests: [...verifiedByHash.values()],\n });\n\n return {\n authorization: {\n containerPathByManifestHash,\n documentManifestByHash: verifiedByHash,\n principalPolicies: authorizationEvidence,\n },\n headManifest,\n };\n}\n\n/** Each served bundle, document and container, whose manifest verified. */\nfunction observeVerifiedDocumentProjectionBundles(\n checkpointContext: ProjectionCheckpointContext,\n projection: DocumentWriterProjectionResponse,\n authorization: DocumentWriterProjectionAuthorization,\n): void {\n observeVerifiedProjectionBundles(\n checkpointContext,\n new Map(\n [projection.documentManifest, ...projection.documentManifestHistory].map(\n (bundle) => [bundle.manifestHash, bundle],\n ),\n ),\n authorization.documentManifestByHash,\n );\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectDocumentProjectionContainerBundles(projection),\n new Map(\n [...authorization.containerPathByManifestHash.values()]\n .flat()\n .map((manifest) => [manifest.manifestHash, manifest]),\n ),\n );\n observeVerifiedKekLevels(\n checkpointContext,\n projection.authorizingContainerPaths,\n );\n}\n\nexport async function verifyDocumentWriterProjection(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<VerifiedDocumentLinkSetManifest> {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n return verified.headManifest;\n}\n\nexport async function verifyDocumentWriterProjectionAuthorization(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<DocumentWriterProjectionAuthorization> {\n try {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n return verified.authorization;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
1
+ {"version":3,"file":"documentProjectionVerification.js","sourceRoot":"","sources":["documentProjectionVerification.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,6BAA6B,EAC7B,gCAAgC,EAChC,wBAAwB,EACxB,gCAAgC,GAEjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EACL,mCAAmC,EACnC,oCAAoC,EACpC,0CAA0C,GAC3C,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAAE,8BAA8B,EAAE,MAAM,qDAAqD,CAAC;AACrG,OAAO,EAAE,mCAAmC,EAAE,MAAM,UAAU,CAAC;AAC/D,OAAO,EAAE,qCAAqC,EAAE,MAAM,oDAAoD,CAAC;AAC3G,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAOhD,OAAO,EAAE,iCAAiC,EAAE,MAAM,UAAU,CAAC;AAC7D,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAC9E,OAAO,EAAE,iCAAiC,EAAE,MAAM,gCAAgC,CAAC;AAKnF,SAAS,oCAAoC,CAC3C,UAA4C;IAE5C,OAAO;QACL,GAAG,UAAU,CAAC,8BAA8B;QAC5C,GAAG,UAAU,CAAC,yBAAyB,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC;KACjE,CAAC;AACJ,CAAC;AAED,SAAS,yCAAyC,CAChD,UAA4C;IAE5C,MAAM,aAAa,GAAG,IAAI,GAAG,EAA4C,CAAC;IAC1E,KAAK,MAAM,CAAC,KAAK,EAAE,WAAW,CAAC,IAAI,4BAA4B,CAC7D,UA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Aa,CAAC;IAChC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,mCAAmC,CAAC,KAAK,CAAC,CAAC;IAC7C,CAAC;AACH,CAAC","sourcesContent":["import type {\n PrincipalPolicyAuthorization,\n VerifiedContainerAccessManifest,\n VerifiedDocumentLinkSetManifest,\n VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentWriterProjectionResponse,\n} from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n finalizeProjectionCheckpoints,\n observeAccessManifestCheckpoints,\n observeVerifiedKekLevels,\n observeVerifiedProjectionBundles,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyContainerManifestPath } from \"../container/containerPathVerification\";\nimport {\n addContainerWriterProjectionBundles,\n verifiedContainerManifestsForBundles,\n verifyContainerWriterProjectionWithContext,\n} from \"../container/containerProjectionVerification\";\nimport { rejectPurgedDocumentProjection } from \"../documentPurge/documentPurgeCheckpointEnforcement\";\nimport { throwKeyingVerificationShapeFailure } from \"../error\";\nimport { verifyProjectionAuthorizationEvidence } from \"../principalPolicy/projectionAuthorizationEvidence\";\nimport { readAccessManifest } from \"../readers\";\nimport type {\n OpenPrincipalPolicyBundleReader,\n PrincipalPolicyCache,\n ProjectionUserKeyResolver,\n ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport { withGenerationGuardedPolicyWarmer } from \"../types\";\nimport { documentContainerProjections } from \"./documentContainerProjections\";\nimport { verifyDocumentProjectionManifests } from \"./documentManifestVerification\";\n\ntype VerifiedManifestMap = Map<string, VerifiedContainerAccessManifest>;\ntype PolicyWarmer = ReferencedPrincipalPolicyWarmer | undefined;\n\nfunction readDocumentProjectionContainerPaths(\n projection: DocumentWriterProjectionResponse,\n): AccessManifestBundleWireResponse[][] {\n return [\n ...projection.documentManifestContainerPaths,\n ...projection.authorizingContainerPaths.map((path) => path.path),\n ];\n}\n\nfunction collectDocumentProjectionContainerBundles(\n projection: DocumentWriterProjectionResponse,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n for (const [index, authorizing] of documentContainerProjections(\n projection,\n ).entries()) {\n addContainerWriterProjectionBundles(\n bundlesByHash,\n authorizing,\n `Document writer projection authorizing path[${index}]`,\n );\n }\n for (const [index, path] of readDocumentProjectionContainerPaths(\n projection,\n ).entries()) {\n for (const [pathIndex, bundle] of path.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection dependency path[${index}][${pathIndex}]`,\n );\n }\n }\n for (const [\n index,\n bundle,\n ] of projection.documentContainerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document writer projection container history[${index}]`,\n );\n }\n return bundlesByHash;\n}\n\nasync function verifyProjectionContainerPaths(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ProjectionCheckpointContext;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}): Promise<Map<string, readonly VerifiedContainerAccessManifest[]>> {\n const bundlesByHash = collectDocumentProjectionContainerBundles(\n input.projection,\n );\n const containerPathByManifestHash = new Map<\n string,\n readonly VerifiedContainerAccessManifest[]\n >();\n // Reuse a caller-supplied cache when provided so a later unwrap pass over the\n // same authorizing container paths does not re-verify identical manifests.\n const verifiedByHash =\n input.verifiedByHash ?? new Map<string, VerifiedContainerAccessManifest>();\n for (const projection of documentContainerProjections(input.projection)) {\n const path = await verifyContainerWriterProjectionWithContext(\n {\n authorizationEvidence: input.authorizationEvidence,\n principalPolicyCache: input.principalPolicyCache,\n projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n },\n input.checkpointContext,\n );\n const leaf = path.at(-1);\n if (leaf) {\n containerPathByManifestHash.set(leaf.manifestHash, path);\n }\n for (const manifest of path) {\n verifiedByHash.set(manifest.manifestHash, manifest);\n }\n }\n // Grouping supplies evidence only; each signed artifact selects its citations.\n for (const [\n index,\n path,\n ] of input.projection.documentManifestContainerPaths.entries()) {\n // Historical dependency evidence is verified without current checkpoint\n // enforcement. Its grouping cannot substitute an uncited ancestor into\n // document or content-write authorization.\n const verifiedPath = await verifyContainerManifestPath({\n authorizationEvidence: input.authorizationEvidence,\n requireAuthorizationEvidence: true,\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoints: false,\n label: `Document writer projection dependency path[${index}]`,\n path,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n // The authorizing path recorded for the same leaf takes precedence.\n const leaf = verifiedPath.at(-1);\n if (leaf && !containerPathByManifestHash.has(leaf.manifestHash)) {\n containerPathByManifestHash.set(leaf.manifestHash, verifiedPath);\n }\n }\n\n // Keep every verified head as evidence. Events and content headers select\n // their own signed paths through resolveEventContainerPaths.\n for (const [hash, manifest] of verifiedByHash) {\n if (!containerPathByManifestHash.has(hash))\n containerPathByManifestHash.set(hash, [manifest]);\n }\n\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: [],\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n\n return containerPathByManifestHash;\n}\n\ninterface DocumentWriterProjectionVerificationInput {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly projection: DocumentWriterProjectionResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly verifiedByHash?: VerifiedManifestMap | undefined;\n readonly warmReferencedPrincipalPolicies?: PolicyWarmer;\n}\nexport interface DocumentWriterProjectionAuthorization {\n readonly containerPathByManifestHash: ReadonlyMap<\n string,\n readonly VerifiedContainerAccessManifest[]\n >;\n readonly documentManifestByHash: ReadonlyMap<\n string,\n VerifiedDocumentLinkSetManifest\n >;\n readonly principalPolicies: readonly PrincipalPolicyAuthorization[];\n}\n\ninterface VerifiedDocumentWriterProjectionResult {\n readonly authorization: DocumentWriterProjectionAuthorization;\n readonly headManifest: VerifiedDocumentLinkSetManifest;\n}\n\nasync function verifyDocumentWriterProjectionWithContext(\n input: Omit<DocumentWriterProjectionVerificationInput, \"execSql\">,\n checkpointContext: ProjectionCheckpointContext,\n): Promise<VerifiedDocumentWriterProjectionResult> {\n const principalPolicyCache =\n input.principalPolicyCache ?? new Map<string, VerifiedPrincipalPolicy>();\n const authorizationEvidence = await verifyProjectionAuthorizationEvidence({\n bundles: [\n input.projection.documentManifest,\n ...input.projection.documentManifestHistory,\n ...collectDocumentProjectionContainerBundles(input.projection).values(),\n ],\n checkpointContext,\n policyEvidence: input.projection.policyEvidence,\n organizationId: readAccessManifest(\n input.projection.documentManifest.manifest,\n \"Document projection manifest\",\n ).organizationId,\n principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const containerPathByManifestHash = await verifyProjectionContainerPaths({\n authorizationEvidence,\n checkpointContext,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n verifiedByHash: input.verifiedByHash,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n const { headManifest, verifiedByHash } =\n await verifyDocumentProjectionManifests({\n authorizationEvidence,\n checkpointContext,\n containerPathByManifestHash,\n principalPolicyCache,\n projection: input.projection,\n resolveUserKey: input.resolveUserKey,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n await rejectPurgedDocumentProjection(\n headManifest.state.documentId,\n checkpointContext.execSql,\n );\n\n observeAccessManifestCheckpoints(checkpointContext, {\n verifiedHeads: [headManifest],\n verifiedManifests: [...verifiedByHash.values()],\n });\n\n return {\n authorization: {\n containerPathByManifestHash,\n documentManifestByHash: verifiedByHash,\n principalPolicies: authorizationEvidence,\n },\n headManifest,\n };\n}\n\n/** Each served bundle, document and container, whose manifest verified. */\nfunction observeVerifiedDocumentProjectionBundles(\n checkpointContext: ProjectionCheckpointContext,\n projection: DocumentWriterProjectionResponse,\n authorization: DocumentWriterProjectionAuthorization,\n): void {\n observeVerifiedProjectionBundles(\n checkpointContext,\n new Map(\n [projection.documentManifest, ...projection.documentManifestHistory].map(\n (bundle) => [bundle.manifestHash, bundle],\n ),\n ),\n authorization.documentManifestByHash,\n );\n observeVerifiedProjectionBundles(\n checkpointContext,\n collectDocumentProjectionContainerBundles(projection),\n new Map(\n [...authorization.containerPathByManifestHash.values()]\n .flat()\n .map((manifest) => [manifest.manifestHash, manifest]),\n ),\n );\n observeVerifiedKekLevels(\n checkpointContext,\n projection.authorizingContainerPaths,\n );\n}\n\nexport async function verifyDocumentWriterProjection(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<VerifiedDocumentLinkSetManifest> {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n return verified.headManifest;\n}\n\nexport async function verifyDocumentWriterProjectionAuthorization(\n input: DocumentWriterProjectionVerificationInput,\n): Promise<DocumentWriterProjectionAuthorization> {\n try {\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n });\n const verified = await verifyDocumentWriterProjectionWithContext(\n withGenerationGuardedPolicyWarmer(input),\n checkpointContext,\n );\n observeVerifiedDocumentProjectionBundles(\n checkpointContext,\n input.projection,\n verified.authorization,\n );\n await finalizeProjectionCheckpoints(checkpointContext, input);\n return verified.authorization;\n } catch (error) {\n throwKeyingVerificationShapeFailure(error);\n }\n}\n"]}
@@ -2,7 +2,6 @@ import { validateAccessManifestCheckpointEvidence } from "../../persistence/keyi
2
2
  import { accessManifestObjectKey } from "../../persistence/keyingCheckpoints/keyingCheckpointPersistence.js";
3
3
  import { KeyingCheckpointRepository } from "../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
4
4
  import { PrincipalAuthorizationCheckpointUnavailableError, validatePrincipalAuthorizationCheckpoints, } from "../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js";
5
- import { PrincipalPolicyBundleRepository } from "../../persistence/principalPolicy/principalPolicyBundleRepository.js";
6
5
  import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
7
6
  import { registerClientSQLiteCommitGuard } from "../../sqlite/sqliteCommitGuards.js";
8
7
  import { getClientSQLitePersistenceRuntime } from "../../sqlite/sqlitePersistenceRuntime.js";
@@ -58,7 +57,9 @@ async function checkPurgeCheckpointCurrency(input, documentPurgeCheckpoint) {
58
57
  verifiedManifests: input.context.verifiedManifests,
59
58
  });
60
59
  if (input.currencyPolicies.length) {
61
- await new PrincipalPolicyBundleRepository(execSql).ensurePrincipalPolicyTables();
60
+ await input.context
61
+ .openPrincipalPolicyBundleReader(execSql)
62
+ .ensurePrincipalPolicyTables();
62
63
  await validatePrincipalAuthorizationCheckpoints(transaction, input.currencyPolicies);
63
64
  }
64
65
  if (superseded) {
@@ -1 +1 @@
1
- {"version":3,"file":"documentPurgeCheck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AAK,CAAC;IACd,CAAC,CAAC,CAAC;AACL,CAAC;AAED,MAAM,UAAU,gCAAgC,CAC9C,KAA2B;IAE3B,OAAO,4BAA4B,CAAC,KAAK,CAAC,CAAC;AAC7C,CAAC;AAED,MAAM,UAAU,8BAA8B,CAC5C,KAEC;IAED,OAAO,4BAA4B,CAAC,KAAK,EAAE,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedAccessManifestCheckpointEvidence,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"../../persistence/keyingCheckpoints/keyingCheckpointEvidence\";\nimport { accessManifestObjectKey } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n PrincipalAuthorizationCheckpointUnavailableError,\n validatePrincipalAuthorizationCheckpoints,\n} from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport { PrincipalPolicyBundleRepository } from \"../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport { registerClientSQLiteCommitGuard } from \"../../sqlite/sqliteCommitGuards\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { validateAccessManifestCheckpoints } from \"../checkpoints/accessManifestCheckpointEnforcement\";\nimport {\n commitProjectionCheckpoints,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { admitDocumentPurgePolicyCheckpoints } from \"./documentPurgePolicyCheckpoints\";\nimport type { PurgePolicyCurrencyEvidence } from \"./documentPurgePolicyCurrency\";\n\ninterface PurgeCheckpointInput {\n readonly context: ProjectionCheckpointContext;\n readonly execSql: ExecSql;\n readonly principalPolicies: readonly VerifiedPrincipalPolicySelection[];\n readonly currencyPolicies: readonly PurgePolicyCurrencyEvidence[];\n readonly observedPrincipalHeads: readonly ReferencedPrincipalHead[];\n}\n\n/** All artifacts must already be authenticated before currency is considered. */\nasync function currentContainerHeads(input: PurgeCheckpointInput) {\n const current: VerifiedAccessManifestCheckpointEvidence[] = [];\n let superseded = false;\n for (const head of input.context.verifiedHeads) {\n const checkpoint = head.checkpoint;\n const local =\n checkpoint.objectKind === \"container\"\n ? await new KeyingCheckpointRepository(\n input.execSql,\n ).loadAccessManifestCheckpoint(\n \"container\",\n checkpoint.organizationId,\n checkpoint.objectId,\n )\n : null;\n if (!local || checkpoint.epoch >= local.epoch) {\n current.push(head);\n continue;\n }\n // A newer head does not order this separately signed purge event. Still\n // reject signed forks visible in the supplied evidence before deferring.\n const key = accessManifestObjectKey(checkpoint);\n validateAccessManifestCheckpointEvidence({\n head,\n localCheckpoint: local,\n predecessors: input.context.verifiedManifests.filter(\n (evidence) =>\n accessManifestObjectKey(evidence.checkpoint) === key &&\n evidence.manifestHash !== head.manifestHash,\n ),\n });\n superseded = true;\n }\n return { current, superseded };\n}\n\nasync function checkPurgeCheckpointCurrency(\n input: PurgeCheckpointInput,\n documentPurgeCheckpoint?: DocumentPurgeCheckpoint,\n): Promise<void> {\n // Keep comparison and optional advancement in the same immediate transaction.\n // Pass the locked executor through nested readers and checkpoint commits.\n await runSerializedSqlMutation(input.execSql, async (execSql) => {\n await getClientSQLitePersistenceRuntime(execSql).transaction(\n async (transaction) => {\n const stillCurrent = projectionLifetimeGuard(input.context);\n registerClientSQLiteCommitGuard(execSql, () =>\n assertProjectionVerificationCurrent(stillCurrent),\n );\n const { current, superseded } = await currentContainerHeads({\n ...input,\n execSql,\n });\n // An older container must not conceal a document fork, a policy fork, or\n // conflicting current evidence for another container in the same proof.\n await validateAccessManifestCheckpoints({\n execSql,\n policies: [],\n verifiedHeads: current,\n verifiedManifests: input.context.verifiedManifests,\n });\n if (input.currencyPolicies.length) {\n await new PrincipalPolicyBundleRepository(\n execSql,\n ).ensurePrincipalPolicyTables();\n await validatePrincipalAuthorizationCheckpoints(\n transaction,\n input.currencyPolicies,\n );\n }\n if (superseded) {\n throw new ProjectionDependencyUnavailableError(\n \"Document purge cannot be ordered against a newer container checkpoint\",\n );\n }\n if (documentPurgeCheckpoint) {\n // Only the complete authenticated terminal proof admits these public\n // observations. Page recovery and baseline verification never pin.\n await admitDocumentPurgePolicyCheckpoints({\n transaction,\n organizationId: input.context.organizationId,\n policies: input.principalPolicies,\n heads: input.observedPrincipalHeads,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n await commitProjectionCheckpoints(\n {\n ...input.context,\n policies: [],\n // Currency was rechecked above in this same transaction. Private\n // ancestry bridges must never become newly admitted purge heads.\n authorizationPolicies: [],\n },\n {\n documentPurgeCheckpoint,\n execSql,\n },\n );\n }\n },\n { behavior: \"immediate\" },\n );\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n}\n\nexport function validateDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput,\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input);\n}\n\nexport function commitDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput & {\n readonly documentPurgeCheckpoint: DocumentPurgeCheckpoint;\n },\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input, input.documentPurgeCheckpoint);\n}\n"]}
1
+ {"version":3,"file":"documentPurgeCheckpointCurrency.js","sourceRoot":"","sources":["documentPurgeCheckpointCurrency.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,wCAAwC,EAAE,MAAM,8DAA8D,CAAC;AACxH,OAAO,EAAE,uBAAuB,EAA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EC;IAED,OAAO,4BAA4B,CAAC,KAAK,EAAE,KAAK,CAAC,uBAAuB,CAAC,CAAC;AAC5E,CAAC","sourcesContent":["import type {\n ReferencedPrincipalHead,\n VerifiedAccessManifestCheckpointEvidence,\n VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { validateAccessManifestCheckpointEvidence } from \"../../persistence/keyingCheckpoints/keyingCheckpointEvidence\";\nimport { accessManifestObjectKey } from \"../../persistence/keyingCheckpoints/keyingCheckpointPersistence\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n PrincipalAuthorizationCheckpointUnavailableError,\n validatePrincipalAuthorizationCheckpoints,\n} from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport { registerClientSQLiteCommitGuard } from \"../../sqlite/sqliteCommitGuards\";\nimport { getClientSQLitePersistenceRuntime } from \"../../sqlite/sqlitePersistenceRuntime\";\nimport { type ExecSql, runSerializedSqlMutation } from \"../../sqlite/sqlSchema\";\nimport { validateAccessManifestCheckpoints } from \"../checkpoints/accessManifestCheckpointEnforcement\";\nimport {\n commitProjectionCheckpoints,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport { assertProjectionVerificationCurrent } from \"../types\";\nimport { admitDocumentPurgePolicyCheckpoints } from \"./documentPurgePolicyCheckpoints\";\nimport type { PurgePolicyCurrencyEvidence } from \"./documentPurgePolicyCurrency\";\n\ninterface PurgeCheckpointInput {\n readonly context: ProjectionCheckpointContext;\n readonly execSql: ExecSql;\n readonly principalPolicies: readonly VerifiedPrincipalPolicySelection[];\n readonly currencyPolicies: readonly PurgePolicyCurrencyEvidence[];\n readonly observedPrincipalHeads: readonly ReferencedPrincipalHead[];\n}\n\n/** All artifacts must already be authenticated before currency is considered. */\nasync function currentContainerHeads(input: PurgeCheckpointInput) {\n const current: VerifiedAccessManifestCheckpointEvidence[] = [];\n let superseded = false;\n for (const head of input.context.verifiedHeads) {\n const checkpoint = head.checkpoint;\n const local =\n checkpoint.objectKind === \"container\"\n ? await new KeyingCheckpointRepository(\n input.execSql,\n ).loadAccessManifestCheckpoint(\n \"container\",\n checkpoint.organizationId,\n checkpoint.objectId,\n )\n : null;\n if (!local || checkpoint.epoch >= local.epoch) {\n current.push(head);\n continue;\n }\n // A newer head does not order this separately signed purge event. Still\n // reject signed forks visible in the supplied evidence before deferring.\n const key = accessManifestObjectKey(checkpoint);\n validateAccessManifestCheckpointEvidence({\n head,\n localCheckpoint: local,\n predecessors: input.context.verifiedManifests.filter(\n (evidence) =>\n accessManifestObjectKey(evidence.checkpoint) === key &&\n evidence.manifestHash !== head.manifestHash,\n ),\n });\n superseded = true;\n }\n return { current, superseded };\n}\n\nasync function checkPurgeCheckpointCurrency(\n input: PurgeCheckpointInput,\n documentPurgeCheckpoint?: DocumentPurgeCheckpoint,\n): Promise<void> {\n // Keep comparison and optional advancement in the same immediate transaction.\n // Pass the locked executor through nested readers and checkpoint commits.\n await runSerializedSqlMutation(input.execSql, async (execSql) => {\n await getClientSQLitePersistenceRuntime(execSql).transaction(\n async (transaction) => {\n const stillCurrent = projectionLifetimeGuard(input.context);\n registerClientSQLiteCommitGuard(execSql, () =>\n assertProjectionVerificationCurrent(stillCurrent),\n );\n const { current, superseded } = await currentContainerHeads({\n ...input,\n execSql,\n });\n // An older container must not conceal a document fork, a policy fork, or\n // conflicting current evidence for another container in the same proof.\n await validateAccessManifestCheckpoints({\n execSql,\n policies: [],\n verifiedHeads: current,\n verifiedManifests: input.context.verifiedManifests,\n });\n if (input.currencyPolicies.length) {\n await input.context\n .openPrincipalPolicyBundleReader(execSql)\n .ensurePrincipalPolicyTables();\n await validatePrincipalAuthorizationCheckpoints(\n transaction,\n input.currencyPolicies,\n );\n }\n if (superseded) {\n throw new ProjectionDependencyUnavailableError(\n \"Document purge cannot be ordered against a newer container checkpoint\",\n );\n }\n if (documentPurgeCheckpoint) {\n // Only the complete authenticated terminal proof admits these public\n // observations. Page recovery and baseline verification never pin.\n await admitDocumentPurgePolicyCheckpoints({\n transaction,\n organizationId: input.context.organizationId,\n policies: input.principalPolicies,\n heads: input.observedPrincipalHeads,\n });\n assertProjectionVerificationCurrent(stillCurrent);\n await commitProjectionCheckpoints(\n {\n ...input.context,\n policies: [],\n // Currency was rechecked above in this same transaction. Private\n // ancestry bridges must never become newly admitted purge heads.\n authorizationPolicies: [],\n },\n {\n documentPurgeCheckpoint,\n execSql,\n },\n );\n }\n },\n { behavior: \"immediate\" },\n );\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n}\n\nexport function validateDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput,\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input);\n}\n\nexport function commitDocumentPurgeCheckpoints(\n input: PurgeCheckpointInput & {\n readonly documentPurgeCheckpoint: DocumentPurgeCheckpoint;\n },\n): Promise<void> {\n return checkPurgeCheckpointCurrency(input, input.documentPurgeCheckpoint);\n}\n"]}
@@ -2,11 +2,12 @@ import { type AccessManifestCheckpoint, type PrincipalPolicyAuthorization, type
2
2
  import type { DocumentPurgeProofResponse } from "../../../internal/validators/response/index.js";
3
3
  import type { ExecSql } from "../../sqlite/sqlSchema.js";
4
4
  import { createProjectionCheckpointContext } from "../checkpoints/checkpointContext.js";
5
- import { type PrincipalPolicyCache, type ProjectionUserKeyResolver, type ReferencedPrincipalPolicyWarmer } from "../types.js";
5
+ import { type OpenPrincipalPolicyBundleReader, type PrincipalPolicyCache, type ProjectionUserKeyResolver, type ReferencedPrincipalPolicyWarmer } from "../types.js";
6
6
  interface VerifyDocumentPurgeProofInput {
7
7
  readonly stillCurrent?: (() => boolean) | undefined;
8
8
  readonly warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;
9
9
  readonly execSql: ExecSql;
10
+ readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;
10
11
  readonly expectedDocumentId: string;
11
12
  readonly expectedOrganizationId: string;
12
13
  readonly principalPolicyCache?: PrincipalPolicyCache | undefined;
@@ -122,15 +122,19 @@ function purgePrincipalSourceHeads(proof) {
122
122
  ...proof.policyEvidence.groups,
123
123
  ].flatMap((source) => (source ? [source.head] : []));
124
124
  }
125
- async function verifyDocumentPurgeProofWithMode(input, enforceLocalCheckpoints) {
126
- requirePurgeProofShape(input.proof);
127
- input = { ...input, proof: structuredClone(input.proof) };
125
+ function requirePurgeProofTarget(input) {
128
126
  if (input.proof.documentId !== input.expectedDocumentId ||
129
127
  input.proof.documentManifest.manifestHash.length === 0) {
130
128
  throw new KeyingVerificationError("object_mismatch", "Document purge proof targets the wrong document");
131
129
  }
130
+ }
131
+ async function verifyDocumentPurgeProofWithMode(input, enforceLocalCheckpoints) {
132
+ requirePurgeProofShape(input.proof);
133
+ input = { ...input, proof: structuredClone(input.proof) };
134
+ requirePurgeProofTarget(input);
132
135
  const checkpointContext = createProjectionCheckpointContext({
133
136
  execSql: input.execSql,
137
+ openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,
134
138
  organizationId: input.expectedOrganizationId,
135
139
  });
136
140
  const principalPolicyCache = input.principalPolicyCache ?? new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"documentPurgeProofVerification.js","sourceRoot":"","sources":["documentPurgeProofVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAE9E,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,gCAAgC,GACjC,MAAM,kC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B,uBAAuB;YACvB,OAAO;YACP,iBAAiB;YACjB,gBAAgB;YAChB,sBAAsB;SACvB,CAAC;QACJ,kBAAkB,EAAE,gBAAgB,CAAC,UAAU;KAChD,CAAC;AACJ,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,gCAAgC,CACpD,KAAoC;IAEpC,sBAAsB,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;IACpC,MAAM,QAAQ,GAAG,MAAM,gCAAgC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACtE,OAAO;QACL,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;KAChD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAoC;IAEpC,OAAO,gCAAgC,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentPurgeProofResponse,\n} from \"@tearleads/validators/response\";\nimport { isDocumentPurgeProofResponse } from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n observeAccessManifestCheckpoints,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyContainerManifestPath } from \"../container/containerPathVerification\";\nimport { verifiedContainerManifestsForBundles } from \"../container/containerProjectionVerification\";\nimport { verifyProjectionPolicyEvidence } from \"../principalPolicy/projectionPolicyEvidence\";\nimport { observeProjectionLifetime } from \"../projectionLifetimes\";\nimport { readAccessManifest } from \"../readers\";\nimport {\n assertProjectionVerificationCurrent,\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n commitDocumentPurgeCheckpoints,\n validateDocumentPurgeCheckpoints,\n} from \"./documentPurgeCheckpointCurrency\";\nimport { recoverDocumentPurgePolicyCurrency } from \"./documentPurgePolicyCurrency\";\nimport { authenticateDocumentPurgeArtifacts } from \"./documentPurgePrincipalEvidence\";\n\ninterface VerifyDocumentPurgeProofInput {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n readonly execSql: ExecSql;\n readonly expectedDocumentId: string;\n readonly expectedOrganizationId: string;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly proof: DocumentPurgeProofResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}\n\ninterface VerifiedDocumentPurgeProofCommit {\n readonly commitCheckpoints: (execSql?: ExecSql) => Promise<void>;\n readonly documentCheckpoint: AccessManifestCheckpoint;\n}\n\ntype PurgeContainerEvidence = Pick<\n DocumentPurgeProofResponse,\n | \"authorizingContainerPath\"\n | \"documentContainerManifestHistory\"\n | \"documentManifestContainerPaths\"\n>;\n\nfunction collectContainerBundles(\n proof: PurgeContainerEvidence,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n for (const [index, bundle] of proof.authorizingContainerPath.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document purge authorizing container path[${index}]`,\n );\n }\n for (const [\n index,\n bundle,\n ] of proof.documentContainerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document purge container history[${index}]`,\n );\n }\n for (const [\n pathIndex,\n path,\n ] of proof.documentManifestContainerPaths.entries()) {\n for (const [bundleIndex, bundle] of path.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document purge dependency path[${pathIndex}][${bundleIndex}]`,\n );\n }\n }\n return bundlesByHash;\n}\n\nexport async function verifyPurgeContainerPaths(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ReturnType<\n typeof createProjectionCheckpointContext\n >;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly proof: PurgeContainerEvidence;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}) {\n const bundlesByHash = collectContainerBundles(input.proof);\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const authorizingContainerPath = await verifyContainerManifestPath({\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n authorizationEvidence: input.authorizationEvidence,\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n // Authenticate the signed path here; the complete purge's local currency\n // is checked after its event and document evidence have authenticated.\n enforceLocalCheckpoints: false,\n label: \"Document purge authorizing container path\",\n path: input.proof.authorizingContainerPath,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n requireAuthorizationEvidence: true,\n verifiedByHash,\n });\n const authorizingLeaf = authorizingContainerPath.at(-1);\n if (!authorizingLeaf) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Document purge authorizing container path is empty\",\n );\n }\n const containerPathByManifestHash = new Map<\n string,\n readonly VerifiedContainerAccessManifest[]\n >();\n containerPathByManifestHash.set(authorizingLeaf.manifestHash, [\n ...authorizingContainerPath,\n ]);\n for (const [\n index,\n path,\n ] of input.proof.documentManifestContainerPaths.entries()) {\n const verifiedPath = await verifyContainerManifestPath({\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n authorizationEvidence: input.authorizationEvidence,\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoints: false,\n label: `Document purge dependency path[${index}]`,\n path,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n requireAuthorizationEvidence: true,\n verifiedByHash,\n });\n const leaf = verifiedPath.at(-1);\n if (leaf && !containerPathByManifestHash.has(leaf.manifestHash)) {\n containerPathByManifestHash.set(leaf.manifestHash, verifiedPath);\n }\n }\n // Purge verification consumes event citations only, never content-write\n // headers, so historical evidence needs no pinned target-path grouping.\n for (const [hash, manifest] of verifiedByHash) {\n if (!containerPathByManifestHash.has(hash)) {\n containerPathByManifestHash.set(hash, [manifest]);\n }\n }\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: authorizingContainerPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n return {\n authorizingContainerPath,\n containerPathByManifestHash,\n verifiedContainerManifests: new Map(verifiedByHash),\n };\n}\n\nfunction requirePurgeProofShape(\n proof: unknown,\n): asserts proof is DocumentPurgeProofResponse {\n if (!isDocumentPurgeProofResponse(proof)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Document purge proof has an invalid shape\",\n );\n }\n}\n\nfunction requirePurgeOrganization(actual: string, expected: string): void {\n if (actual !== expected)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document purge proof belongs to another organization\",\n );\n}\n\nasync function recoverPurgePolicyEvidence(\n input: VerifyDocumentPurgeProofInput,\n) {\n const references = [...collectContainerBundles(input.proof).values()].flatMap(\n (bundle) =>\n readAccessManifest(bundle.manifest, \"Purge container manifest\")\n .referencedPrincipalHeads,\n );\n if (\n !references.length &&\n (input.proof.policyEvidence.organization ||\n input.proof.policyEvidence.groups.length ||\n input.proof.policyEvidence.organizationPayloads.length)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Document purge proof includes unrelated principal policy evidence\",\n );\n return verifyProjectionPolicyEvidence({\n evidence: input.proof.policyEvidence,\n organizationId: input.expectedOrganizationId,\n references,\n historicalProof: true,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n\nfunction purgePrincipalSourceHeads(proof: DocumentPurgeProofResponse) {\n return [\n proof.policyEvidence.organization,\n ...proof.policyEvidence.groups,\n ].flatMap((source) => (source ? [source.head] : []));\n}\n\nasync function verifyDocumentPurgeProofWithMode(\n input: VerifyDocumentPurgeProofInput,\n enforceLocalCheckpoints: boolean,\n): Promise<VerifiedDocumentPurgeProofCommit> {\n requirePurgeProofShape(input.proof);\n input = { ...input, proof: structuredClone(input.proof) };\n if (\n input.proof.documentId !== input.expectedDocumentId ||\n input.proof.documentManifest.manifestHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document purge proof targets the wrong document\",\n );\n }\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n organizationId: input.expectedOrganizationId,\n });\n const principalPolicyCache =\n input.principalPolicyCache ?? new Map<string, VerifiedPrincipalPolicy>();\n const recovered = await recoverPurgePolicyEvidence(input);\n observeProjectionLifetime(checkpointContext, recovered.stillCurrent);\n const authorizationEvidence = recovered.policies;\n const {\n authorizingContainerPath,\n containerPathByManifestHash,\n verifiedContainerManifests,\n } = await verifyPurgeContainerPaths({\n authorizationEvidence,\n checkpointContext,\n principalPolicyCache,\n proof: input.proof,\n resolveUserKey: input.resolveUserKey,\n });\n const { documentManifest, principalPolicies, purgeEventHash } =\n await authenticateDocumentPurgeArtifacts({\n authorizationEvidence,\n authorizingContainerPath,\n checkpointContext,\n containerPathByManifestHash,\n enforceLocalCheckpoints,\n expectedDocumentId: input.expectedDocumentId,\n principalPolicyCache,\n proof: input.proof,\n resolveUserKey: input.resolveUserKey,\n verifiedContainerManifests,\n });\n requirePurgeOrganization(\n documentManifest.state.organizationId,\n input.expectedOrganizationId,\n );\n const observedPrincipalHeads = purgePrincipalSourceHeads(input.proof);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n const currencyPolicies = enforceLocalCheckpoints\n ? await recoverDocumentPurgePolicyCurrency({\n context: checkpointContext,\n organizationId: input.expectedOrganizationId,\n policies: principalPolicies,\n warmer: input.warmReferencedPrincipalPolicies,\n stillCurrent: recovered.stillCurrent,\n })\n : principalPolicies;\n if (enforceLocalCheckpoints) {\n await validateDocumentPurgeCheckpoints({\n context: checkpointContext,\n execSql: input.execSql,\n principalPolicies,\n currencyPolicies,\n observedPrincipalHeads,\n });\n }\n const documentPurgeCheckpoint = {\n documentId: input.expectedDocumentId,\n documentManifestHash: documentManifest.manifestHash,\n organizationId: documentManifest.state.organizationId,\n purgeEventHash,\n };\n return {\n commitCheckpoints: (execSql = input.execSql) =>\n commitDocumentPurgeCheckpoints({\n context: checkpointContext,\n documentPurgeCheckpoint,\n execSql,\n principalPolicies,\n currencyPolicies,\n observedPrincipalHeads,\n }),\n documentCheckpoint: documentManifest.checkpoint,\n };\n}\n\nexport async function verifyDocumentPurgeProofBaseline(\n input: VerifyDocumentPurgeProofInput,\n): Promise<Pick<VerifiedDocumentPurgeProofCommit, \"documentCheckpoint\">> {\n requirePurgeProofShape(input.proof);\n const verified = await verifyDocumentPurgeProofWithMode(input, false);\n return {\n documentCheckpoint: verified.documentCheckpoint,\n };\n}\n\nexport function verifyDocumentPurgeProof(\n input: VerifyDocumentPurgeProofInput,\n): Promise<VerifiedDocumentPurgeProofCommit> {\n return verifyDocumentPurgeProofWithMode(input, true);\n}\n"]}
1
+ {"version":3,"file":"documentPurgeProofVerification.js","sourceRoot":"","sources":["documentPurgeProofVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAK3B,OAAO,EAAE,4BAA4B,EAAE,MAAM,gCAAgC,CAAC;AAE9E,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EACL,iCAAiC,EACjC,gCAAgC,GACjC,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,2BAA2B,EAAE,MAAM,wCAAwC,CAAC;AACrF,OAAO,EAAE,oCAAoC,EAAE,MAAM,8CAA8C,CAAC;AACpG,OAAO,EAAE,8BAA8B,EAAE,MAAM,6CAA6C,CAAC;AAC7F,OAAO,EAAE,yBAAyB,EAAE,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAC;AAChD,OAAO,EACL,mCAAmC,GAKpC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,8BA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AC,KAAK,CAAC,CAAC;IACpC,MAAM,QAAQ,GAAG,MAAM,gCAAgC,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IACtE,OAAO;QACL,kBAAkB,EAAE,QAAQ,CAAC,kBAAkB;KAChD,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,wBAAwB,CACtC,KAAoC;IAEpC,OAAO,gCAAgC,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type PrincipalPolicyAuthorization,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicy,\n} from \"@tearleads/crypto\";\nimport type {\n AccessManifestBundleWireResponse,\n DocumentPurgeProofResponse,\n} from \"@tearleads/validators/response\";\nimport { isDocumentPurgeProofResponse } from \"@tearleads/validators/response\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { addBundleByHash } from \"../checkpoints/bundleVerification\";\nimport {\n createProjectionCheckpointContext,\n observeAccessManifestCheckpoints,\n} from \"../checkpoints/checkpointContext\";\nimport { verifyContainerManifestPath } from \"../container/containerPathVerification\";\nimport { verifiedContainerManifestsForBundles } from \"../container/containerProjectionVerification\";\nimport { verifyProjectionPolicyEvidence } from \"../principalPolicy/projectionPolicyEvidence\";\nimport { observeProjectionLifetime } from \"../projectionLifetimes\";\nimport { readAccessManifest } from \"../readers\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n type PrincipalPolicyCache,\n type ProjectionUserKeyResolver,\n type ReferencedPrincipalPolicyWarmer,\n} from \"../types\";\nimport {\n commitDocumentPurgeCheckpoints,\n validateDocumentPurgeCheckpoints,\n} from \"./documentPurgeCheckpointCurrency\";\nimport { recoverDocumentPurgePolicyCurrency } from \"./documentPurgePolicyCurrency\";\nimport { authenticateDocumentPurgeArtifacts } from \"./documentPurgePrincipalEvidence\";\n\ninterface VerifyDocumentPurgeProofInput {\n readonly stillCurrent?: (() => boolean) | undefined;\n readonly warmReferencedPrincipalPolicies?:\n | ReferencedPrincipalPolicyWarmer\n | undefined;\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly expectedDocumentId: string;\n readonly expectedOrganizationId: string;\n readonly principalPolicyCache?: PrincipalPolicyCache | undefined;\n readonly proof: DocumentPurgeProofResponse;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}\n\ninterface VerifiedDocumentPurgeProofCommit {\n readonly commitCheckpoints: (execSql?: ExecSql) => Promise<void>;\n readonly documentCheckpoint: AccessManifestCheckpoint;\n}\n\ntype PurgeContainerEvidence = Pick<\n DocumentPurgeProofResponse,\n | \"authorizingContainerPath\"\n | \"documentContainerManifestHistory\"\n | \"documentManifestContainerPaths\"\n>;\n\nfunction collectContainerBundles(\n proof: PurgeContainerEvidence,\n): Map<string, AccessManifestBundleWireResponse> {\n const bundlesByHash = new Map<string, AccessManifestBundleWireResponse>();\n for (const [index, bundle] of proof.authorizingContainerPath.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document purge authorizing container path[${index}]`,\n );\n }\n for (const [\n index,\n bundle,\n ] of proof.documentContainerManifestHistory.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document purge container history[${index}]`,\n );\n }\n for (const [\n pathIndex,\n path,\n ] of proof.documentManifestContainerPaths.entries()) {\n for (const [bundleIndex, bundle] of path.entries()) {\n addBundleByHash(\n bundlesByHash,\n bundle,\n `Document purge dependency path[${pathIndex}][${bundleIndex}]`,\n );\n }\n }\n return bundlesByHash;\n}\n\nexport async function verifyPurgeContainerPaths(input: {\n readonly authorizationEvidence: readonly PrincipalPolicyAuthorization[];\n readonly checkpointContext: ReturnType<\n typeof createProjectionCheckpointContext\n >;\n readonly principalPolicyCache: PrincipalPolicyCache;\n readonly proof: PurgeContainerEvidence;\n readonly resolveUserKey: ProjectionUserKeyResolver;\n}) {\n const bundlesByHash = collectContainerBundles(input.proof);\n const verifiedByHash = new Map<string, VerifiedContainerAccessManifest>();\n const authorizingContainerPath = await verifyContainerManifestPath({\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n authorizationEvidence: input.authorizationEvidence,\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n // Authenticate the signed path here; the complete purge's local currency\n // is checked after its event and document evidence have authenticated.\n enforceLocalCheckpoints: false,\n label: \"Document purge authorizing container path\",\n path: input.proof.authorizingContainerPath,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n requireAuthorizationEvidence: true,\n verifiedByHash,\n });\n const authorizingLeaf = authorizingContainerPath.at(-1);\n if (!authorizingLeaf) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Document purge authorizing container path is empty\",\n );\n }\n const containerPathByManifestHash = new Map<\n string,\n readonly VerifiedContainerAccessManifest[]\n >();\n containerPathByManifestHash.set(authorizingLeaf.manifestHash, [\n ...authorizingContainerPath,\n ]);\n for (const [\n index,\n path,\n ] of input.proof.documentManifestContainerPaths.entries()) {\n const verifiedPath = await verifyContainerManifestPath({\n servedAsCurrent: false,\n authorizationMembership: \"referenced\",\n authorizationEvidence: input.authorizationEvidence,\n bundlesByHash,\n checkpointContext: input.checkpointContext,\n enforceLocalCheckpoints: false,\n label: `Document purge dependency path[${index}]`,\n path,\n principalPolicyCache: input.principalPolicyCache,\n resolveUserKey: input.resolveUserKey,\n requireAuthorizationEvidence: true,\n verifiedByHash,\n });\n const leaf = verifiedPath.at(-1);\n if (leaf && !containerPathByManifestHash.has(leaf.manifestHash)) {\n containerPathByManifestHash.set(leaf.manifestHash, verifiedPath);\n }\n }\n // Purge verification consumes event citations only, never content-write\n // headers, so historical evidence needs no pinned target-path grouping.\n for (const [hash, manifest] of verifiedByHash) {\n if (!containerPathByManifestHash.has(hash)) {\n containerPathByManifestHash.set(hash, [manifest]);\n }\n }\n observeAccessManifestCheckpoints(input.checkpointContext, {\n verifiedHeads: authorizingContainerPath,\n verifiedManifests: verifiedContainerManifestsForBundles(\n bundlesByHash,\n verifiedByHash,\n ),\n });\n return {\n authorizingContainerPath,\n containerPathByManifestHash,\n verifiedContainerManifests: new Map(verifiedByHash),\n };\n}\n\nfunction requirePurgeProofShape(\n proof: unknown,\n): asserts proof is DocumentPurgeProofResponse {\n if (!isDocumentPurgeProofResponse(proof)) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Document purge proof has an invalid shape\",\n );\n }\n}\n\nfunction requirePurgeOrganization(actual: string, expected: string): void {\n if (actual !== expected)\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document purge proof belongs to another organization\",\n );\n}\n\nasync function recoverPurgePolicyEvidence(\n input: VerifyDocumentPurgeProofInput,\n) {\n const references = [...collectContainerBundles(input.proof).values()].flatMap(\n (bundle) =>\n readAccessManifest(bundle.manifest, \"Purge container manifest\")\n .referencedPrincipalHeads,\n );\n if (\n !references.length &&\n (input.proof.policyEvidence.organization ||\n input.proof.policyEvidence.groups.length ||\n input.proof.policyEvidence.organizationPayloads.length)\n )\n throw new KeyingVerificationError(\n \"invalid_shape\",\n \"Document purge proof includes unrelated principal policy evidence\",\n );\n return verifyProjectionPolicyEvidence({\n evidence: input.proof.policyEvidence,\n organizationId: input.expectedOrganizationId,\n references,\n historicalProof: true,\n stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies: input.warmReferencedPrincipalPolicies,\n });\n}\n\nfunction purgePrincipalSourceHeads(proof: DocumentPurgeProofResponse) {\n return [\n proof.policyEvidence.organization,\n ...proof.policyEvidence.groups,\n ].flatMap((source) => (source ? [source.head] : []));\n}\n\nfunction requirePurgeProofTarget(input: VerifyDocumentPurgeProofInput): void {\n if (\n input.proof.documentId !== input.expectedDocumentId ||\n input.proof.documentManifest.manifestHash.length === 0\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"Document purge proof targets the wrong document\",\n );\n }\n}\n\nasync function verifyDocumentPurgeProofWithMode(\n input: VerifyDocumentPurgeProofInput,\n enforceLocalCheckpoints: boolean,\n): Promise<VerifiedDocumentPurgeProofCommit> {\n requirePurgeProofShape(input.proof);\n input = { ...input, proof: structuredClone(input.proof) };\n requirePurgeProofTarget(input);\n const checkpointContext = createProjectionCheckpointContext({\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n organizationId: input.expectedOrganizationId,\n });\n const principalPolicyCache =\n input.principalPolicyCache ?? new Map<string, VerifiedPrincipalPolicy>();\n const recovered = await recoverPurgePolicyEvidence(input);\n observeProjectionLifetime(checkpointContext, recovered.stillCurrent);\n const authorizationEvidence = recovered.policies;\n const {\n authorizingContainerPath,\n containerPathByManifestHash,\n verifiedContainerManifests,\n } = await verifyPurgeContainerPaths({\n authorizationEvidence,\n checkpointContext,\n principalPolicyCache,\n proof: input.proof,\n resolveUserKey: input.resolveUserKey,\n });\n const { documentManifest, principalPolicies, purgeEventHash } =\n await authenticateDocumentPurgeArtifacts({\n authorizationEvidence,\n authorizingContainerPath,\n checkpointContext,\n containerPathByManifestHash,\n enforceLocalCheckpoints,\n expectedDocumentId: input.expectedDocumentId,\n principalPolicyCache,\n proof: input.proof,\n resolveUserKey: input.resolveUserKey,\n verifiedContainerManifests,\n });\n requirePurgeOrganization(\n documentManifest.state.organizationId,\n input.expectedOrganizationId,\n );\n const observedPrincipalHeads = purgePrincipalSourceHeads(input.proof);\n assertProjectionVerificationCurrent(recovered.stillCurrent);\n const currencyPolicies = enforceLocalCheckpoints\n ? await recoverDocumentPurgePolicyCurrency({\n context: checkpointContext,\n organizationId: input.expectedOrganizationId,\n policies: principalPolicies,\n warmer: input.warmReferencedPrincipalPolicies,\n stillCurrent: recovered.stillCurrent,\n })\n : principalPolicies;\n if (enforceLocalCheckpoints) {\n await validateDocumentPurgeCheckpoints({\n context: checkpointContext,\n execSql: input.execSql,\n principalPolicies,\n currencyPolicies,\n observedPrincipalHeads,\n });\n }\n const documentPurgeCheckpoint = {\n documentId: input.expectedDocumentId,\n documentManifestHash: documentManifest.manifestHash,\n organizationId: documentManifest.state.organizationId,\n purgeEventHash,\n };\n return {\n commitCheckpoints: (execSql = input.execSql) =>\n commitDocumentPurgeCheckpoints({\n context: checkpointContext,\n documentPurgeCheckpoint,\n execSql,\n principalPolicies,\n currencyPolicies,\n observedPrincipalHeads,\n }),\n documentCheckpoint: documentManifest.checkpoint,\n };\n}\n\nexport async function verifyDocumentPurgeProofBaseline(\n input: VerifyDocumentPurgeProofInput,\n): Promise<Pick<VerifiedDocumentPurgeProofCommit, \"documentCheckpoint\">> {\n requirePurgeProofShape(input.proof);\n const verified = await verifyDocumentPurgeProofWithMode(input, false);\n return {\n documentCheckpoint: verified.documentCheckpoint,\n };\n}\n\nexport function verifyDocumentPurgeProof(\n input: VerifyDocumentPurgeProofInput,\n): Promise<VerifiedDocumentPurgeProofCommit> {\n return verifyDocumentPurgeProofWithMode(input, true);\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  import { KeyingVerificationError } from "../../../internal/crypto/index.js";
2
2
  import { KeyingCheckpointRepository } from "../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
3
- import { PrincipalPolicyBundleRepository } from "../../persistence/principalPolicy/principalPolicyBundleRepository.js";
4
3
  import { principalPolicyEvidenceEntries, } from "../../principals/principalPolicyEvidence.js";
5
4
  import { principalStateMatchesReference } from "../../principals/principalPolicyStates.js";
6
5
  import { verifiedPrincipalPolicyMeetsCheckpoint } from "./principalPolicyCheckpointSelection.js";
@@ -68,7 +67,9 @@ export async function filterUncachedPrincipalPolicyReferences(input) {
68
67
  return null;
69
68
  }
70
69
  }
71
- const bundle = await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundleForReference(reference, checkpoint);
70
+ const bundle = await input
71
+ .openPrincipalPolicyBundleReader(input.execSql)
72
+ .loadPrincipalPolicyBundleForReference(reference, checkpoint);
72
73
  return bundle ? null : reference;
73
74
  }));
74
75
  return results.filter((reference) => reference !== null);
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyC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AwC,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,IAAI,+BAA+B,CACtD,KAAK,CAAC,OAAO,CACd,CAAC,qCAAqC,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;QAC/D,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 { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../persistence/principalPolicy/principalPolicyBundleRepository\";\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 new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\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 new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundleForReference(reference, checkpoint);\n return bundle ? null : reference;\n }),\n );\n return results.filter(\n (reference): reference is ReferencedPrincipalHead => reference !== null,\n );\n}\n"]}
1
+ {"version":3,"file":"principalPolicyCache.js","sourceRoot":"","sources":["principalPolicyCache.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EAEL,8BAA8B,GAC/B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,wCAAwC,CAAC;AAGxF,OAAO,EAAE,sCAAsC,EAAE,MAAM,sCAAsC,CAAC;AAE9F;;;;;GAKG;AACH,MAAM,UAAU,4BAA4B,CAC1C,SAAkC;IAElC,OAAO,IAAI,CAAC,SAAS,CAAC;QACpB,SAAS,CAAC,aAAa;QACvB,SAAS,CAAC,WAAW;QACrB,SAAS,CAAC,OAAO;QACjB,SAAS,CAAC,SAAS;QACnB,SAAS,CAAC,QAAQ;QAClB,SAAS,CAAC,cAAc;KACzB,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAE7C,UAAqC;IACrC,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAsB,CAAC;IACxD,KAAK,MAAM,SAAS,IAAI,UAAU,EAAE,CAAC;QACnC,iBAAiB,CAAC,GAAG,CAAC,4BAA4B,CAAC,SAAS,CAA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AAC,GAAG,CAC/B,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,SAAS,EAAE,EAAE;QACvC,MAAM,UAAU,GAAG,MAAM,IAAI,0BAA0B,CACrD,KAAK,CAAC,OAAO,CACd,CAAC,6BAA6B,CAC7B,SAAS,CAAC,aAAa,EACvB,SAAS,CAAC,WAAW,CACtB,CAAC;QACF,MAAM,YAAY,GAAG,KAAK,CAAC,oBAAoB,CAAC,GAAG,CACjD,4BAA4B,CAAC,SAAS,CAAC,CACxC,CAAC;QACF,IAAI,YAAY,EAAE,CAAC;YACjB,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,KAAK;aACvB,+BAA+B,CAAC,KAAK,CAAC,OAAO,CAAC;aAC9C,qCAAqC,CAAC,SAAS,EAAE,UAAU,CAAC,CAAC;QAChE,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 { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport { principalStateMatchesReference } from \"../../principals/principalPolicyStates\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport type { OpenPrincipalPolicyBundleReader } from \"../types\";\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 openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\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 new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\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 input\n .openPrincipalPolicyBundleReader(input.execSql)\n .loadPrincipalPolicyBundleForReference(reference, checkpoint);\n return bundle ? null : reference;\n }),\n );\n return results.filter(\n (reference): reference is ReferencedPrincipalHead => reference !== null,\n );\n}\n"]}
@@ -1,6 +1,5 @@
1
1
  import { KeyingVerificationError, verifyPrincipalPolicyBundle, } from "../../../internal/crypto/index.js";
2
2
  import { KeyingCheckpointRepository } from "../../persistence/keyingCheckpoints/keyingCheckpointRepository.js";
3
- import { PrincipalPolicyBundleRepository } from "../../persistence/principalPolicy/principalPolicyBundleRepository.js";
4
3
  import { parseOrganizationAuthorityDescriptor, principalHeadMatchesReference, requireOrganizationGroupHead, } from "../../principals/organizationAuthorityDescriptor.js";
5
4
  import { assertPrincipalIdentityCommitments, publishVerifiedPolicyBundle, } from "../../principals/principalIdentityCommitments.js";
6
5
  import { organizationAdminExternalAuthority, principalPolicyReferenceFromBundle, verifyOrganizationAdminPolicy, verifyPrincipalPolicyBundleWithExternalOrganizationAdmins, } from "../../principals/principalPolicyAdminSigners.js";
@@ -34,7 +33,9 @@ export function isPrincipalPolicyNotCachedError(error) {
34
33
  }
35
34
  async function loadOrganizationPolicyForVerification(input) {
36
35
  const execSql = input.checkpointContext.execSql;
37
- let bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundle("organization", input.organizationId);
36
+ let bundle = await input.checkpointContext
37
+ .openPrincipalPolicyBundleReader(execSql)
38
+ .loadPrincipalPolicyBundle("organization", input.organizationId);
38
39
  if (!bundle) {
39
40
  return undefined;
40
41
  }
@@ -45,7 +46,9 @@ async function loadOrganizationPolicyForVerification(input) {
45
46
  organizationId: input.organizationId,
46
47
  references: [principalPolicyReferenceFromBundle(bundle)],
47
48
  });
48
- bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundle("organization", input.organizationId);
49
+ bundle = await input.checkpointContext
50
+ .openPrincipalPolicyBundleReader(execSql)
51
+ .loadPrincipalPolicyBundle("organization", input.organizationId);
49
52
  localCheckpoint = await new KeyingCheckpointRepository(execSql).loadPrincipalPolicyCheckpoint("organization", input.organizationId);
50
53
  if (!bundle) {
51
54
  return undefined;
@@ -61,7 +64,9 @@ function assertReservedAdminsPolicyShape(policy) {
61
64
  }
62
65
  }
63
66
  async function verifyOrganizationAdminsPolicy(input) {
64
- const adminBundle = await new PrincipalPolicyBundleRepository(input.execSql).loadPrincipalPolicyBundle("group", input.adminGroupId);
67
+ const adminBundle = await input
68
+ .openPrincipalPolicyBundleReader(input.execSql)
69
+ .loadPrincipalPolicyBundle("group", input.adminGroupId);
65
70
  if (!adminBundle) {
66
71
  return undefined;
67
72
  }
@@ -115,6 +120,7 @@ async function loadOrganizationExternalAuthority(input) {
115
120
  const verifiedAdmins = await verifyOrganizationAdminsPolicy({
116
121
  adminGroupId: descriptor.adminGroupId,
117
122
  execSql: input.checkpointContext.execSql,
123
+ openPrincipalPolicyBundleReader: input.checkpointContext.openPrincipalPolicyBundleReader,
118
124
  expectedHead: requireOrganizationGroupHead(descriptor, descriptor.adminGroupId),
119
125
  resolveUserKey: input.resolveUserKey,
120
126
  stillCurrent: input.stillCurrent,
@@ -176,7 +182,9 @@ async function verifyReferencedPrincipalPolicy(input) {
176
182
  }
177
183
  }
178
184
  const referenceLabel = principalPolicyReferenceLabel(input.reference);
179
- let bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);
185
+ let bundle = await input.checkpointContext
186
+ .openPrincipalPolicyBundleReader(execSql)
187
+ .loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);
180
188
  if (!bundle && input.warmReferencedPrincipalPolicies) {
181
189
  // The reference is not cached locally — the common case for a member who
182
190
  // gained access via another org's group grant and never hydrated that
@@ -185,7 +193,9 @@ async function verifyReferencedPrincipalPolicy(input) {
185
193
  organizationId: input.organizationId,
186
194
  references: [input.reference],
187
195
  });
188
- bundle = await new PrincipalPolicyBundleRepository(execSql).loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);
196
+ bundle = await input.checkpointContext
197
+ .openPrincipalPolicyBundleReader(execSql)
198
+ .loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);
189
199
  }
190
200
  if (!bundle) {
191
201
  throw new PrincipalPolicyNotCachedError(referenceLabel);
@@ -230,6 +240,7 @@ export async function collectReferencedPrincipalPolicies(input) {
230
240
  !warmReferencedPrincipalPolicies.resolveReference) {
231
241
  const uncached = await filterUncachedPrincipalPolicyReferences({
232
242
  execSql: input.checkpointContext.execSql,
243
+ openPrincipalPolicyBundleReader: input.checkpointContext.openPrincipalPolicyBundleReader,
233
244
  principalPolicyCache: input.principalPolicyCache,
234
245
  references,
235
246
  });
@@ -1 +1 @@
1
- {"version":3,"file":"principalPolicyVerification.js","sourceRoot":"","sources":["principalPolicyVerification.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EAIvB,2BAA2B,GAC5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7D,OAAO,EAAE,KAAK,CAAC,iBAAiB,CAAC,OAAO;YACxC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;YAChD,UAAU;SACX,CAAC,CAAC;QACH,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACxB,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACxD,MAAM,+BAA+B,CAAC;gBACpC,cAAc,EAAE,KAAK,CAAC,cAAc;gBACpC,UAAU,EAAE,QAAQ;aACrB,CAAC,CAAC;YACH,mCAAmC,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;QAC1D,CAAC;IACH,CAAC;IAED,0EAA0E;IAC1E,OAAO,OAAO,CAAC,GAAG,CAChB,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAC3B,+BAA+B,CAAC;QAC9B,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,SAAS;QACT,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B;KAChC,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport { PrincipalPolicyBundleRepository } from \"../../persistence/principalPolicy/principalPolicyBundleRepository\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n assertPrincipalIdentityCommitments,\n publishVerifiedPolicyBundle,\n} from \"../../principals/principalIdentityCommitments\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../principals/principalPolicyAdminSigners\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\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 { collectPrincipalPolicySignerPublicKeys } from \"./principalPolicySigners\";\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\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n /** The verification's lifetime, checked inside every pin write. */\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\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 new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\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 stillCurrent: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await new PrincipalPolicyBundleRepository(\n input.execSql,\n ).loadPrincipalPolicyBundle(\"group\", input.adminGroupId);\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 new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", input.adminGroupId);\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 await publishVerifiedPolicyBundle(adminBundle, input.resolveUserKey, () =>\n assertProjectionVerificationCurrent(input.stillCurrent),\n );\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 await publishVerifiedPolicyBundle(\n organizationPolicy.bundle,\n input.resolveUserKey,\n () => assertProjectionVerificationCurrent(input.stillCurrent),\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 stillCurrent: input.stillCurrent,\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\n/**\n * Fresh or reused: check every projection, history included; pin first\n * sights within the verification's lifetime. A freshly verified `bundle` also\n * pins its signers.\n */\nasync function assertVerifiedPolicyCommitments(\n policy: PrincipalPolicyCurrentEvidence,\n scope: {\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n bundle?: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const assertCurrent = () =>\n assertProjectionVerificationCurrent(scope.stillCurrent);\n await assertPrincipalIdentityCommitments({\n assertCurrent,\n authenticated: true,\n projections: [\n policy.projection,\n ...principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.projection,\n ),\n ],\n resolveTrustedUserIdentity: scope.resolveUserKey,\n });\n if (bundle)\n await publishVerifiedPolicyBundle(\n bundle,\n scope.resolveUserKey,\n assertCurrent,\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) {\n await assertVerifiedPolicyCommitments(recovered, input);\n return recovered;\n }\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\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 await assertVerifiedPolicyCommitments(cachedPolicy, input);\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 new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);\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 new PrincipalPolicyBundleRepository(\n execSql,\n ).loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);\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 stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await assertVerifiedPolicyCommitments(verified.value, input, bundle);\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,EAIvB,2BAA2B,GAC5B,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,0BAA0B,EAAE,MAAM,gEAAgE,CAAC;AAC5G,OAAO,EACL,oCAAoC,EACpC,6BAA6B,EAC7B,4BAA4B,GAC7B,MAAM,kDAAkD,CAAC;AAC1D,OAAO,EACL,kCAAkC,EAClC,2BAA2B,GAC5B,MAAM,+CAA+C,CAAC;AACvD,OAAO,EACL,kCAAkC,EAClC,kCAAkC,EAClC,6BAA6B,EAC7B,yDAAyD,GAC1D,MAAM,8CAA8C,CAAC;AACtD,OAAO,EAEL,8BAA8B,GAC/B,MAAM,0CAA0C,CAAC;AAClD,OAAO,EACL,sBAAsB,GAEvB,MAAM,kCAAkC,CAAC;AAC1C,OAAO,EAAE,0CAA0C,EAAE,MAAM,UAAU,CAAC;AAOtE,OAAO,EACL,mCAAmC,EACnC,sCAAsC,GACvC,MAAM,UAAU,CAAC;AAClB,OAAO,EACL,uCAAuC,EACvC,4BAA4B,EAC5B,wCAAwC,GACzC,MAAM,wBAAwB,C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,CAAC,CAAC,SAAS,EAAE,EAAE,CAC3B,+BAA+B,CAAC;QAC9B,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,oBAAoB,EAAE,KAAK,CAAC,oBAAoB;QAChD,SAAS;QACT,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,cAAc,EAAE,KAAK,CAAC,cAAc;QACpC,+BAA+B;KAChC,CAAC,CACH,CACF,CAAC;AACJ,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type PrincipalPolicyCheckpoint,\n type ReferencedPrincipalHead,\n type VerifiedPrincipalPolicy,\n verifyPrincipalPolicyBundle,\n} from \"@tearleads/crypto\";\nimport type { PrincipalPolicyBundleResponse } from \"@tearleads/validators/response\";\nimport { KeyingCheckpointRepository } from \"../../persistence/keyingCheckpoints/keyingCheckpointRepository\";\nimport {\n parseOrganizationAuthorityDescriptor,\n principalHeadMatchesReference,\n requireOrganizationGroupHead,\n} from \"../../principals/organizationAuthorityDescriptor\";\nimport {\n assertPrincipalIdentityCommitments,\n publishVerifiedPolicyBundle,\n} from \"../../principals/principalIdentityCommitments\";\nimport {\n organizationAdminExternalAuthority,\n principalPolicyReferenceFromBundle,\n verifyOrganizationAdminPolicy,\n verifyPrincipalPolicyBundleWithExternalOrganizationAdmins,\n} from \"../../principals/principalPolicyAdminSigners\";\nimport {\n type PrincipalPolicyCurrentEvidence,\n principalPolicyEvidenceEntries,\n} from \"../../principals/principalPolicyEvidence\";\nimport {\n observePrincipalPolicy,\n type ProjectionCheckpointContext,\n} from \"../checkpoints/checkpointContext\";\nimport { rethrowProjectionVerificationBoundaryError } from \"../error\";\nimport type {\n OpenPrincipalPolicyBundleReader,\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 { collectPrincipalPolicySignerPublicKeys } from \"./principalPolicySigners\";\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\ntype OrganizationAdminPolicyInput = {\n checkpointContext: ProjectionCheckpointContext;\n organizationId: string;\n resolveUserKey: ProjectionUserKeyResolver;\n /** The verification's lifetime, checked inside every pin write. */\n stillCurrent?: (() => boolean) | undefined;\n warmReferencedPrincipalPolicies?: ReferencedPrincipalPolicyWarmer | undefined;\n};\n\nasync function loadOrganizationPolicyForVerification(\n input: OrganizationAdminPolicyInput,\n): Promise<\n | {\n bundle: PrincipalPolicyBundleResponse;\n localCheckpoint: PrincipalPolicyCheckpoint | null;\n }\n | undefined\n> {\n const execSql = input.checkpointContext.execSql;\n let bundle = await input.checkpointContext\n .openPrincipalPolicyBundleReader(execSql)\n .loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n if (!bundle) {\n return undefined;\n }\n let localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\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 input.checkpointContext\n .openPrincipalPolicyBundleReader(execSql)\n .loadPrincipalPolicyBundle(\"organization\", input.organizationId);\n localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\"organization\", input.organizationId);\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 openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n expectedHead: ReferencedPrincipalHead;\n resolveUserKey: ProjectionUserKeyResolver;\n stillCurrent: (() => boolean) | undefined;\n}): Promise<VerifiedPrincipalPolicy | undefined> {\n const adminBundle = await input\n .openPrincipalPolicyBundleReader(input.execSql)\n .loadPrincipalPolicyBundle(\"group\", input.adminGroupId);\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 new KeyingCheckpointRepository(\n input.execSql,\n ).loadPrincipalPolicyCheckpoint(\"group\", input.adminGroupId);\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 await publishVerifiedPolicyBundle(adminBundle, input.resolveUserKey, () =>\n assertProjectionVerificationCurrent(input.stillCurrent),\n );\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 await publishVerifiedPolicyBundle(\n organizationPolicy.bundle,\n input.resolveUserKey,\n () => assertProjectionVerificationCurrent(input.stillCurrent),\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 openPrincipalPolicyBundleReader:\n input.checkpointContext.openPrincipalPolicyBundleReader,\n expectedHead: requireOrganizationGroupHead(\n descriptor,\n descriptor.adminGroupId,\n ),\n resolveUserKey: input.resolveUserKey,\n stillCurrent: input.stillCurrent,\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\n/**\n * Fresh or reused: check every projection, history included; pin first\n * sights within the verification's lifetime. A freshly verified `bundle` also\n * pins its signers.\n */\nasync function assertVerifiedPolicyCommitments(\n policy: PrincipalPolicyCurrentEvidence,\n scope: {\n readonly resolveUserKey: ProjectionUserKeyResolver;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n bundle?: PrincipalPolicyBundleResponse,\n): Promise<void> {\n const assertCurrent = () =>\n assertProjectionVerificationCurrent(scope.stillCurrent);\n await assertPrincipalIdentityCommitments({\n assertCurrent,\n authenticated: true,\n projections: [\n policy.projection,\n ...principalPolicyEvidenceEntries(policy).map(\n (entry) => entry.projection,\n ),\n ],\n resolveTrustedUserIdentity: scope.resolveUserKey,\n });\n if (bundle)\n await publishVerifiedPolicyBundle(\n bundle,\n scope.resolveUserKey,\n assertCurrent,\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) {\n await assertVerifiedPolicyCommitments(recovered, input);\n return recovered;\n }\n const cacheKey = referencedPrincipalPolicyKey(input.reference);\n const cachedPolicy = input.principalPolicyCache.get(cacheKey);\n const execSql = input.checkpointContext.execSql;\n const localCheckpoint = await new KeyingCheckpointRepository(\n execSql,\n ).loadPrincipalPolicyCheckpoint(\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 await assertVerifiedPolicyCommitments(cachedPolicy, input);\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 input.checkpointContext\n .openPrincipalPolicyBundleReader(execSql)\n .loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);\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 input.checkpointContext\n .openPrincipalPolicyBundleReader(execSql)\n .loadPrincipalPolicyBundleForReference(input.reference, localCheckpoint);\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 stillCurrent: input.stillCurrent,\n warmReferencedPrincipalPolicies:\n input.warmReferencedPrincipalPolicies,\n }),\n localCheckpoint,\n signerPublicKeys,\n });\n if (!verified.ok) {\n throw verified.error;\n }\n await assertVerifiedPolicyCommitments(verified.value, input, bundle);\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 openPrincipalPolicyBundleReader:\n input.checkpointContext.openPrincipalPolicyBundleReader,\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,28 @@
1
- import type { ReferencedPrincipalHead, VerifiedPrincipalPolicyCurrent, VerifiedPrincipalPolicySelection } from "../../internal/crypto/index.js";
2
- import type { ProjectionPolicyEvidenceResponse } from "../../internal/validators/response/index.js";
1
+ import type { PrincipalPolicyCheckpoint, ReferencedPrincipalHead, VerifiedPrincipalPolicyCurrent, VerifiedPrincipalPolicySelection } from "../../internal/crypto/index.js";
2
+ import type { PrincipalPolicyBundleResponse, PrincipalStateResponse, ProjectionPolicyEvidenceResponse } from "../../internal/validators/response/index.js";
3
3
  import type { PrincipalPolicyCurrentEvidence } from "../principals/principalPolicyEvidence.js";
4
+ import type { ExecSql } from "../sqlite/sqlSchema.js";
4
5
  import type { TrustedUserIdentity } from "../trustedUserIdentity/index.js";
5
6
  export type ProjectionUserKey = TrustedUserIdentity;
6
7
  export type ProjectionUserKeyResolver = (userId: string) => Promise<ProjectionUserKey | null>;
7
8
  export type PrincipalPolicyCache = Map<string, PrincipalPolicyCurrentEvidence>;
9
+ /**
10
+ * The cached principal policy bundles verification reads, supplied by the
11
+ * caller so verification does not depend on Principal Policy's store. Each
12
+ * method ensures the principal policy tables on the executor it was opened on.
13
+ */
14
+ export interface PrincipalPolicyBundleReader {
15
+ ensurePrincipalPolicyTables(): Promise<void>;
16
+ loadPrincipalPolicyBundle(principalType: PrincipalStateResponse["principalType"], principalId: string): Promise<PrincipalPolicyBundleResponse | null>;
17
+ /** The newest stored bundle containing exactly `reference`, never a guess. */
18
+ loadPrincipalPolicyBundleForReference(reference: ReferencedPrincipalHead, checkpoint: PrincipalPolicyCheckpoint | null): Promise<PrincipalPolicyBundleResponse | null>;
19
+ }
20
+ /**
21
+ * Opens the bundle reader on one executor. Verification opens it on the
22
+ * executor each read runs on, a locked transaction handle included, so every
23
+ * read sees that executor's snapshot.
24
+ */
25
+ export type OpenPrincipalPolicyBundleReader = (execSql: ExecSql) => PrincipalPolicyBundleReader;
8
26
  export interface PrincipalPolicyResolveRequest {
9
27
  /** Reuse authenticated local ancestry before an authorized online recovery. */
10
28
  readonly preferLocalHistory?: boolean | undefined;