@tearleads/client-sdk 0.1.241 → 0.1.242

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 (36) hide show
  1. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js +12 -3
  2. package/data/keyingProjectionVerification/checkpoints/checkpointContext.js.map +1 -1
  3. package/data/keyingProjectionVerification/checkpoints/verifiedBundleBytes.js +73 -8
  4. package/data/keyingProjectionVerification/checkpoints/verifiedBundleBytes.js.map +1 -1
  5. package/data/keyingProjectionVerification/container/containerAncestorCitations.js +20 -4
  6. package/data/keyingProjectionVerification/container/containerAncestorCitations.js.map +1 -1
  7. package/data/keyingProjectionVerification/container/containerManifestVerification.js +43 -32
  8. package/data/keyingProjectionVerification/container/containerManifestVerification.js.map +1 -1
  9. package/data/keyingProjectionVerification/container/containerSignedParentReference.js +129 -0
  10. package/data/keyingProjectionVerification/container/containerSignedParentReference.js.map +1 -0
  11. package/data/keyingProjectionVerification/document/documentManifestVerification.js +28 -7
  12. package/data/keyingProjectionVerification/document/documentManifestVerification.js.map +1 -1
  13. package/data/persistence/verifiedCitations/bundleCitationRows.js.map +1 -1
  14. package/data/persistence/verifiedCitations/citationCollection.js +2 -2
  15. package/data/persistence/verifiedCitations/citationCollection.js.map +1 -1
  16. package/data/persistence/verifiedManifestBundlePersistence.d.ts +3 -2
  17. package/data/persistence/verifiedManifestBundlePersistence.js +1 -1
  18. package/data/persistence/verifiedManifestBundlePersistence.js.map +1 -1
  19. package/internal/api-client/verifiedManifestCitations.d.ts +4 -3
  20. package/internal/api-client/verifiedManifestCitations.js +3 -3
  21. package/internal/api-client/verifiedManifestCitations.js.map +1 -1
  22. package/internal/validators/operation/writerProjections.d.ts +8 -8
  23. package/internal/validators/response/container.d.ts +4 -4
  24. package/internal/validators/response/documentMutation.d.ts +4 -4
  25. package/internal/validators/response/manifestBundleReferences.js +4 -3
  26. package/internal/validators/response/manifestBundleReferences.js.map +1 -1
  27. package/internal/validators/response/writerProjectionWire.d.ts +4 -4
  28. package/internal/validators/response/writerProjectionWire.js +8 -5
  29. package/internal/validators/response/writerProjectionWire.js.map +1 -1
  30. package/internal/validators/util/index.d.ts +1 -0
  31. package/internal/validators/util/index.js +1 -0
  32. package/internal/validators/util/index.js.map +1 -1
  33. package/internal/validators/util/servedManifestBundle.d.ts +71 -0
  34. package/internal/validators/util/servedManifestBundle.js +100 -0
  35. package/internal/validators/util/servedManifestBundle.js.map +1 -0
  36. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { containerKekWireLevel, } from "../../../internal/validators/response/index.js";
3
+ import { toServedAccessManifestBundle } from "../../../internal/validators/util/index.js";
3
4
  import { PrincipalAuthorizationCheckpointUnavailableError } from "../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints.js";
4
5
  import { ProjectionDependencyUnavailableError } from "../../shared/dependencyUnavailable.js";
5
6
  import { projectionLifetimeGuard } from "../projectionLifetimes.js";
@@ -37,10 +38,18 @@ export function observeAccessManifestCheckpoints(context, input) {
37
38
  export function observeVerifiedProjectionBundles(context, bundlesByHash, verifiedByHash) {
38
39
  for (const [manifestHash, bundle] of bundlesByHash) {
39
40
  const verified = verifiedByHash.get(manifestHash);
41
+ if (!verified)
42
+ continue;
40
43
  // A cache hit verifies the hash, not these bytes: store only bytes that
41
- // a fresh verification accepted, so a citation never replays others.
42
- if (verified && matchesVerifiedBundleBytes(verified, bundle))
43
- context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });
44
+ // a fresh verification accepted, so a citation never replays others. One
45
+ // copy is compared and stored, taken before persistence awaits, so no
46
+ // later read of the projection's object can reach storage.
47
+ const snapshot = structuredClone(bundle);
48
+ if (matchesVerifiedBundleBytes(verified, snapshot))
49
+ context.verifiedBundles.push({
50
+ bundle: toServedAccessManifestBundle(snapshot),
51
+ checkpoint: verified.checkpoint,
52
+ });
44
53
  }
45
54
  }
46
55
  /**
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essManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n} from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { rememberVerifiedContainerHeads } from \"./heldContainerHeads\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // The caller's principal policy bundle store, opened per executor.\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others.\n if (verified && matchesVerifiedBundleBytes(verified, bundle))\n context.verifiedBundles.push({ bundle, checkpoint: verified.checkpoint });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
1
+ {"version":3,"file":"checkpointContext.js","sourceRoot":"","sources":["checkpointContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,uBAAuB,GAIxB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAGL,qBAAqB,GACtB,MAAM,gCAAgC,CAAC;AACxC,OAAO,EAAE,4BAA4B,EAAE,MAAM,4BAA4B,CAAC;AAE1E,OAAO,EAAE,gDAAgD,EAAE,MAAM,uEAAuE,CAAC;AAGzI,OAAO,EAAE,oCAAoC,EAAE,MAAM,oC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,aAAa;QACpC,iBAAiB,EAAE,OAAO,CAAC,iBAAiB;KAC7C,CAAC,CAAC,KAAK,CAAC,CAAC,KAAc,EAAE,EAAE;QAC1B,IAAI,KAAK,YAAY,gDAAgD;YACnE,MAAM,IAAI,oCAAoC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;QAChE,MAAM,KAAK,CAAC;IACd,CAAC,CAAC,CAAC;IACH,mCAAmC,CAAC,KAAK,EAAE,YAAY,CAAC,CAAC;AAC3D,CAAC;AAED,MAAM,CAAC,KAAK,UAAU,6BAA6B,CACjD,OAAoC,EACpC,KAIC;IAED,IAAI,KAAK,CAAC,8BAA8B,KAAK,KAAK,EAAE,CAAC;QACnD,MAAM,6BAA6B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;QACpD,OAAO;IACT,CAAC;IACD,MAAM,2BAA2B,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAClD,IAAI,KAAK,CAAC,YAAY,EAAE,EAAE,KAAK,KAAK;QAAE,OAAO;IAC7C,MAAM,cAAc,GAClB,OAAO,CAAC,cAAc;QACtB,OAAO,CAAC,kBAAkB,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,cAAc,CAAC;IACtD,IAAI,cAAc,KAAK,SAAS;QAAE,OAAO;IACzC,IAAI,CAAC;QACH,8BAA8B,CAAC;YAC7B,cAAc;YACd,OAAO,EAAE,KAAK,CAAC,OAAO,IAAI,OAAO,CAAC,OAAO;YACzC,KAAK,EAAE,OAAO,CAAC,kBAAkB;YACjC,QAAQ,EAAE,OAAO,CAAC,QAAQ;SAC3B,CAAC,CAAC;IACL,CAAC;IAAC,MAAM,CAAC;QACP,wEAAwE;QACxE,sEAAsE;IACxE,CAAC;AACH,CAAC","sourcesContent":["import {\n type AccessManifestCheckpoint,\n KeyingVerificationError,\n type VerifiedAccessManifestCheckpointEvidence,\n type VerifiedContainerAccessManifest,\n type VerifiedPrincipalPolicySelection,\n} from \"@tearleads/crypto\";\nimport {\n type AccessManifestBundleWireResponse,\n type ContainerKeyingPathResponse,\n containerKekWireLevel,\n} from \"@tearleads/validators/response\";\nimport { toServedAccessManifestBundle } from \"@tearleads/validators/util\";\nimport type { DocumentPurgeCheckpoint } from \"../../persistence/keyingCheckpoints/documentPurgeCheckpointPersistence\";\nimport { PrincipalAuthorizationCheckpointUnavailableError } from \"../../persistence/keyingCheckpoints/principalAuthorizationCheckpoints\";\nimport type { VerifiedManifestBundle } from \"../../persistence/verifiedManifestBundlePersistence\";\nimport type { PrincipalPolicyCheckpointEvidence } from \"../../principalContracts/principalPolicyEvidence\";\nimport { ProjectionDependencyUnavailableError } from \"../../shared/dependencyUnavailable\";\nimport type { ExecSql } from \"../../sqlite/sqlSchema\";\nimport { projectionLifetimeGuard } from \"../projectionLifetimes\";\nimport {\n assertProjectionVerificationCurrent,\n type OpenPrincipalPolicyBundleReader,\n} from \"../types\";\nimport {\n enforceAccessManifestCheckpoints,\n validateAccessManifestCheckpoints,\n} from \"./accessManifestCheckpointEnforcement\";\nimport { rememberVerifiedContainerHeads } from \"./heldContainerHeads\";\nimport { matchesVerifiedBundleBytes } from \"./verifiedBundleBytes\";\n\nexport interface ProjectionCheckpointContext {\n readonly heldContainerHeads: VerifiedContainerAccessManifest[];\n readonly execSql: ExecSql;\n // The caller's principal policy bundle store, opened per executor.\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n // Local checkpoints read during this verification, one read per object.\n readonly localCheckpoints: Map<string, AccessManifestCheckpoint | null>;\n organizationId?: string | undefined;\n readonly policies: PrincipalPolicyCheckpointEvidence[];\n readonly authorizationPolicies: VerifiedPrincipalPolicySelection[];\n // Served bundles whose manifests verified, and KEK levels of verified\n // paths, stored at finalization.\n readonly verifiedBundles: VerifiedManifestBundle[];\n readonly verifiedHeads: VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: VerifiedAccessManifestCheckpointEvidence[];\n}\n\nexport function createProjectionCheckpointContext(input: {\n readonly execSql: ExecSql;\n readonly openPrincipalPolicyBundleReader: OpenPrincipalPolicyBundleReader;\n readonly organizationId?: string | undefined;\n}): ProjectionCheckpointContext {\n if (typeof input.execSql !== \"function\") {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Projection verification requires durable keying checkpoint storage\",\n );\n }\n\n return {\n heldContainerHeads: [],\n execSql: input.execSql,\n openPrincipalPolicyBundleReader: input.openPrincipalPolicyBundleReader,\n localCheckpoints: new Map(),\n organizationId: input.organizationId,\n policies: [],\n authorizationPolicies: [],\n verifiedBundles: [],\n verifiedHeads: [],\n verifiedManifests: [],\n };\n}\n\nexport function observeAccessManifestCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly verifiedHeads: readonly VerifiedAccessManifestCheckpointEvidence[];\n readonly verifiedManifests: readonly VerifiedAccessManifestCheckpointEvidence[];\n },\n): void {\n context.verifiedHeads.push(...input.verifiedHeads);\n context.verifiedManifests.push(...input.verifiedManifests);\n}\n\n/**\n * Records each served bundle whose manifest this verification produced, so\n * the transaction finalizing the checkpoints also stores it for later\n * citation. A bundle the projection carried but verification never reached\n * is skipped.\n */\nexport function observeVerifiedProjectionBundles(\n context: ProjectionCheckpointContext,\n bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>,\n verifiedByHash: ReadonlyMap<\n string,\n { readonly checkpoint: AccessManifestCheckpoint }\n >,\n): void {\n for (const [manifestHash, bundle] of bundlesByHash) {\n const verified = verifiedByHash.get(manifestHash);\n if (!verified) continue;\n // A cache hit verifies the hash, not these bytes: store only bytes that\n // a fresh verification accepted, so a citation never replays others. One\n // copy is compared and stored, taken before persistence awaits, so no\n // later read of the projection's object can reach storage.\n const snapshot = structuredClone(bundle);\n if (matchesVerifiedBundleBytes(verified, snapshot))\n context.verifiedBundles.push({\n bundle: toServedAccessManifestBundle(snapshot),\n checkpoint: verified.checkpoint,\n });\n }\n}\n\n/**\n * Records every KEK level of paths this verification accepted in full, so\n * the finalizing transaction stores them for later citation by digest. A\n * cited level is refilled from these bytes only when the API's current\n * level has the same digest, and is verified again like a served one.\n */\nexport function observeVerifiedKekLevels(\n context: ProjectionCheckpointContext,\n paths: readonly ContainerKeyingPathResponse[],\n): void {\n for (const path of paths)\n for (const kek of path.containerKeks)\n context.verifiedBundles.push({\n kekLevel: containerKekWireLevel(kek),\n organizationId: path.organizationId,\n });\n}\n\nexport function observePrincipalPolicy(\n context: ProjectionCheckpointContext,\n policy: PrincipalPolicyCheckpointEvidence,\n organizationId?: string | undefined,\n): void {\n if (\n organizationId !== undefined &&\n context.organizationId !== undefined &&\n context.organizationId !== organizationId\n ) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n \"projection checkpoint batch crosses organization ownership\",\n );\n }\n context.organizationId ??= organizationId;\n context.policies.push(policy);\n}\n\nexport async function commitProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly documentPurgeCheckpoint?: DocumentPurgeCheckpoint | undefined;\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await enforceAccessManifestCheckpoints({\n documentPurgeCheckpoint: input?.documentPurgeCheckpoint,\n execSql: input?.execSql ?? context.execSql,\n organizationId: context.organizationId,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\n/** Validates against the latest durable pins without persisting new heads. */\nasync function validateProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input?: {\n readonly execSql?: ExecSql | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n input = {\n ...input,\n stillCurrent: projectionLifetimeGuard(context, input?.stillCurrent),\n };\n assertProjectionVerificationCurrent(input?.stillCurrent);\n await validateAccessManifestCheckpoints({\n execSql: input?.execSql ?? context.execSql,\n policies: context.policies,\n authorizationPolicies: context.authorizationPolicies,\n stillCurrent: input?.stillCurrent,\n verifiedBundles: context.verifiedBundles,\n verifiedHeads: context.verifiedHeads,\n verifiedManifests: context.verifiedManifests,\n }).catch((error: unknown) => {\n if (error instanceof PrincipalAuthorizationCheckpointUnavailableError)\n throw new ProjectionDependencyUnavailableError(error.message);\n throw error;\n });\n assertProjectionVerificationCurrent(input?.stillCurrent);\n}\n\nexport async function finalizeProjectionCheckpoints(\n context: ProjectionCheckpointContext,\n input: {\n readonly execSql?: ExecSql | undefined;\n readonly persistVerificationCheckpoints?: boolean | undefined;\n readonly stillCurrent?: (() => boolean) | undefined;\n },\n): Promise<void> {\n if (input.persistVerificationCheckpoints === false) {\n await validateProjectionCheckpoints(context, input);\n return;\n }\n await commitProjectionCheckpoints(context, input);\n if (input.stillCurrent?.() === false) return;\n const organizationId =\n context.organizationId ??\n context.heldContainerHeads[0]?.state.organizationId;\n if (organizationId === undefined) return;\n try {\n rememberVerifiedContainerHeads({\n organizationId,\n execSql: input.execSql ?? context.execSql,\n heads: context.heldContainerHeads,\n policies: context.policies,\n });\n } catch {\n // Checkpoints are already committed. Optional re-citation evidence must\n // never change successful verification into a caller-visible refusal.\n }\n}\n"]}
@@ -1,26 +1,91 @@
1
- import { readKeyingCanonicalJson, serializeKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
2
- // The exact bytes each manifest was verified from, keyed by the verified
3
- // result. A later projection can hit the same verified hash while serving
4
- // different bytes; only bytes that were themselves verified may be stored
5
- // for citation.
1
+ import { KeyingVerificationError, readKeyingCanonicalJson, serializeKeyingCanonicalJson, } from "../../../internal/crypto/index.js";
2
+ // The exact bundle each manifest was verified from (signed event, body,
3
+ // manifest and the completed state), keyed by the verified result. A later
4
+ // projection can hit the same verified hash with different bytes or a
5
+ // different completed state; only what was itself verified may answer from
6
+ // the cache or be stored for citation (in its served form).
6
7
  const verifiedBundleBytes = new WeakMap();
7
8
  function canonicalBytes(bundle) {
8
9
  try {
9
- return serializeKeyingCanonicalJson(readKeyingCanonicalJson(bundle, "Verified manifest bundle"));
10
+ return serializeKeyingCanonicalJson(readKeyingCanonicalJson({
11
+ event: bundle.event,
12
+ manifest: bundle.manifest,
13
+ manifestHash: bundle.manifestHash,
14
+ state: bundle.state,
15
+ }, "Verified manifest bundle"));
10
16
  }
11
17
  catch {
12
18
  return null;
13
19
  }
14
20
  }
21
+ /** Plain-data equality that keeps distinctions JSON cannot carry (`-0`). */
22
+ function sameData(left, right) {
23
+ if (typeof left !== "object" || left === null)
24
+ return Object.is(left, right);
25
+ if (typeof right !== "object" || right === null)
26
+ return false;
27
+ if (Array.isArray(left) !== Array.isArray(right))
28
+ return false;
29
+ const keys = Object.keys(left);
30
+ return (keys.length === Object.keys(right).length &&
31
+ keys.every((key) => Object.hasOwn(right, key) &&
32
+ sameData(Reflect.get(left, key), Reflect.get(right, key))));
33
+ }
15
34
  /** Remember the bundle a fresh verification accepted for `verified`. */
16
35
  export function recordVerifiedBundleBytes(verified, bundle) {
17
36
  const bytes = canonicalBytes(bundle);
18
37
  if (bytes !== null)
19
38
  verifiedBundleBytes.set(verified, bytes);
20
39
  }
21
- /** Whether `bundle` is byte-identical to the one `verified` came from. */
40
+ // Bundles frozen here after they matched a verified result. A frozen bundle
41
+ // of plain data can no longer change, so every later comparison against the
42
+ // same result is answered without serializing it again, and a caller reading
43
+ // it reads exactly the bytes verification accepted.
44
+ const frozenMatches = new WeakMap();
45
+ /** Whether every value under `value` is a plain data property. */
46
+ function isPlainData(value) {
47
+ if (typeof value !== "object" || value === null)
48
+ return true;
49
+ return Object.values(Object.getOwnPropertyDescriptors(value)).every((descriptor) => "value" in descriptor && isPlainData(descriptor.value));
50
+ }
51
+ function deepFreeze(value) {
52
+ if (typeof value !== "object" || value === null)
53
+ return;
54
+ Object.freeze(value);
55
+ for (const child of Object.values(value))
56
+ deepFreeze(child);
57
+ }
58
+ /**
59
+ * Whether `bundle` is byte-identical to the one `verified` came from. A
60
+ * plain-data bundle that matches is frozen, so it stays the verified copy.
61
+ */
22
62
  export function matchesVerifiedBundleBytes(verified, bundle) {
63
+ if (frozenMatches.get(bundle) === verified)
64
+ return true;
23
65
  const recorded = verifiedBundleBytes.get(verified);
24
- return recorded !== undefined && recorded === canonicalBytes(bundle);
66
+ const matches = recorded !== undefined && recorded === canonicalBytes(bundle);
67
+ if (matches && isPlainData(bundle)) {
68
+ deepFreeze(bundle);
69
+ frozenMatches.set(bundle, verified);
70
+ }
71
+ return matches;
72
+ }
73
+ /**
74
+ * Verification checks a copy taken before its first await; the caller reads
75
+ * the bundle it passed, so on return that bundle must still be the copy
76
+ * verification accepted.
77
+ */
78
+ export function assertUnchangedSinceVerification(verified, bundle, label, snapshot) {
79
+ // A bundle that could not be serialized was never recorded (nor stored for
80
+ // citation): it must equal the copy verification checked, and it is frozen
81
+ // all the same, so it stays that copy.
82
+ const unchanged = verifiedBundleBytes.has(verified)
83
+ ? matchesVerifiedBundleBytes(verified, bundle)
84
+ : snapshot !== undefined && sameData(bundle, snapshot);
85
+ if (unchanged && !verifiedBundleBytes.has(verified) && isPlainData(bundle))
86
+ deepFreeze(bundle);
87
+ if (!unchanged) {
88
+ throw new KeyingVerificationError("hash_mismatch", `${label} changed while it was verified`);
89
+ }
25
90
  }
26
91
  //# sourceMappingURL=verifiedBundleBytes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"verifiedBundleBytes.js","sourceRoot":"","sources":["verifiedBundleBytes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAE3B,yEAAyE;AACzE,0EAA0E;AAC1E,0EAA0E;AAC1E,gBAAgB;AAChB,MAAM,mBAAmB,GAAG,IAAI,OAAO,EAAkB,CAAC;AAE1D,SAAS,cAAc,CAAC,MAAe;IACrC,IAAI,CAAC;QACH,OAAO,4BAA4B,CACjC,uBAAuB,CAAC,MAAM,EAAE,0BAA0B,CAAC,CAC5D,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,wEAAwE;AACxE,MAAM,UAAU,yBAAyB,CACvC,QAAgB,EAChB,MAAe;IAEf,MAAM,KAAK,GAAG,cAAc,CAAC,MAAM,CAAC,CAAC;IACrC,IAAI,KAAK,KAAK,IAAI;QAAE,mBAAmB,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC;AAC/D,CAAC;AAED,0EAA0E;AAC1E,MAAM,UAAU,0BAA0B,CACxC,QAAgB,EAChB,MAAe;IAEf,MAAM,QAAQ,GAAG,mBAAmB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;IACnD,OAAO,QAAQ,KAAK,SAAS,IAAI,QAAQ,KAAK,cAAc,CAAC,MAAM,CAAC,CAAC;AACvE,CAAC","sourcesContent":["import {\n readKeyingCanonicalJson,\n serializeKeyingCanonicalJson,\n} from \"@tearleads/crypto\";\n\n// The exact bytes each manifest was verified from, keyed by the verified\n// result. A later projection can hit the same verified hash while serving\n// different bytes; only bytes that were themselves verified may be stored\n// for citation.\nconst verifiedBundleBytes = new WeakMap<object, string>();\n\nfunction canonicalBytes(bundle: unknown): string | null {\n try {\n return serializeKeyingCanonicalJson(\n readKeyingCanonicalJson(bundle, \"Verified manifest bundle\"),\n );\n } catch {\n return null;\n }\n}\n\n/** Remember the bundle a fresh verification accepted for `verified`. */\nexport function recordVerifiedBundleBytes(\n verified: object,\n bundle: unknown,\n): void {\n const bytes = canonicalBytes(bundle);\n if (bytes !== null) verifiedBundleBytes.set(verified, bytes);\n}\n\n/** Whether `bundle` is byte-identical to the one `verified` came from. */\nexport function matchesVerifiedBundleBytes(\n verified: object,\n bundle: unknown,\n): boolean {\n const recorded = verifiedBundleBytes.get(verified);\n return recorded !== undefined && recorded === canonicalBytes(bundle);\n}\n"]}
1
+ {"version":3,"file":"verifiedBundleBytes.js","sourceRoot":"","sources":["verifiedBundleBytes.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,uBAAuB,EACvB,4BAA4B,GAC7B,MAAM,mBAAmB,CAAC;AAG3B,wEAAwE;AACxE,2EAA2E;AAC3E,sEAAsE;AACtE,2EAA2E;AAC3E,4DAA4D;AAC5D,MAAM,mBAAmB,GAAG,IAAI,OAAO,EAAkB,CAAC;AAE1D,SAAS,cAAc,CACrB,MAAwC;IAExC,IAAI,CAAC;QACH,OAAO,4BAA4B,CACjC,uBAAuB,CACrB;YACE,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,QAAQ,EAAE,MAAM,CAAC,QAAQ;YACzB,YAAY,EAAE,MAAM,CAAC,YAAY;YACjC,KAAK,EAAE,MAAM,CAAC,KAAK;SACpB,EACD,0BAA0B,CAC3B,CACF,CAAC;IACJ,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,4EAA4E;AAC5E,SAAS,QAAQ,CAAC,IAAa,EAAE,KAAc;IAC7C,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,IAAI,KAAK,IAAI;QAAE,OAAO,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IAC7E,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,KAAK,CAAC;IAC9D,IAAI,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC/D,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC/B,OAAO,CACL,IAAI,CAAC,MAAM,KAAK,MAAM,CAAC,IAAI,CAAC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import type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\n\n// The exact bundle each manifest was verified from (signed event, body,\n// manifest and the completed state), keyed by the verified result. A later\n// projection can hit the same verified hash with different bytes or a\n// different completed state; only what was itself verified may answer from\n// the cache or be stored for citation (in its served form).\nconst verifiedBundleBytes = new WeakMap<object, string>();\n\nfunction canonicalBytes(\n bundle: AccessManifestBundleWireResponse,\n): string | null {\n try {\n return serializeKeyingCanonicalJson(\n readKeyingCanonicalJson(\n {\n event: bundle.event,\n manifest: bundle.manifest,\n manifestHash: bundle.manifestHash,\n state: bundle.state,\n },\n \"Verified manifest bundle\",\n ),\n );\n } catch {\n return null;\n }\n}\n\n/** Plain-data equality that keeps distinctions JSON cannot carry (`-0`). */\nfunction sameData(left: unknown, right: unknown): boolean {\n if (typeof left !== \"object\" || left === null) return Object.is(left, right);\n if (typeof right !== \"object\" || right === null) return false;\n if (Array.isArray(left) !== Array.isArray(right)) return false;\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every(\n (key) =>\n Object.hasOwn(right, key) &&\n sameData(Reflect.get(left, key), Reflect.get(right, key)),\n )\n );\n}\n\n/** Remember the bundle a fresh verification accepted for `verified`. */\nexport function recordVerifiedBundleBytes(\n verified: object,\n bundle: AccessManifestBundleWireResponse,\n): void {\n const bytes = canonicalBytes(bundle);\n if (bytes !== null) verifiedBundleBytes.set(verified, bytes);\n}\n\n// Bundles frozen here after they matched a verified result. A frozen bundle\n// of plain data can no longer change, so every later comparison against the\n// same result is answered without serializing it again, and a caller reading\n// it reads exactly the bytes verification accepted.\nconst frozenMatches = new WeakMap<object, object>();\n\n/** Whether every value under `value` is a plain data property. */\nfunction isPlainData(value: unknown): boolean {\n if (typeof value !== \"object\" || value === null) return true;\n return Object.values(Object.getOwnPropertyDescriptors(value)).every(\n (descriptor) => \"value\" in descriptor && isPlainData(descriptor.value),\n );\n}\n\nfunction deepFreeze(value: unknown): void {\n if (typeof value !== \"object\" || value === null) return;\n Object.freeze(value);\n for (const child of Object.values(value)) deepFreeze(child);\n}\n\n/**\n * Whether `bundle` is byte-identical to the one `verified` came from. A\n * plain-data bundle that matches is frozen, so it stays the verified copy.\n */\nexport function matchesVerifiedBundleBytes(\n verified: object,\n bundle: AccessManifestBundleWireResponse,\n): boolean {\n if (frozenMatches.get(bundle) === verified) return true;\n const recorded = verifiedBundleBytes.get(verified);\n const matches = recorded !== undefined && recorded === canonicalBytes(bundle);\n if (matches && isPlainData(bundle)) {\n deepFreeze(bundle);\n frozenMatches.set(bundle, verified);\n }\n return matches;\n}\n\n/**\n * Verification checks a copy taken before its first await; the caller reads\n * the bundle it passed, so on return that bundle must still be the copy\n * verification accepted.\n */\nexport function assertUnchangedSinceVerification(\n verified: object,\n bundle: AccessManifestBundleWireResponse,\n label: string,\n snapshot?: AccessManifestBundleWireResponse,\n): void {\n // A bundle that could not be serialized was never recorded (nor stored for\n // citation): it must equal the copy verification checked, and it is frozen\n // all the same, so it stays that copy.\n const unchanged = verifiedBundleBytes.has(verified)\n ? matchesVerifiedBundleBytes(verified, bundle)\n : snapshot !== undefined && sameData(bundle, snapshot);\n if (unchanged && !verifiedBundleBytes.has(verified) && isPlainData(bundle))\n deepFreeze(bundle);\n if (!unchanged) {\n throw new KeyingVerificationError(\n \"hash_mismatch\",\n `${label} changed while it was verified`,\n );\n }\n}\n"]}
@@ -1,9 +1,21 @@
1
1
  import { KeyingVerificationError, } from "../../../internal/crypto/index.js";
2
2
  import { readCanonicalRecord } from "../../keying/canonicalJson.js";
3
+ import { matchesVerifiedBundleBytes } from "../checkpoints/verifiedBundleBytes.js";
3
4
  import { readKeyingVerificationShape } from "../error.js";
4
- import { readRecordNullableString } from "../readers.js";
5
+ import { readRecordString } from "../readers.js";
6
+ /**
7
+ * The container a served bundle's manifest names, before it verifies. The
8
+ * manifest hash commits to it, and verification binds it to the signed event
9
+ * and the derived state, so a selection made here is checked there.
10
+ */
5
11
  function bundleContainerId(bundle, label) {
6
- return readKeyingVerificationShape(() => readRecordNullableString(readCanonicalRecord(bundle.state, `${label} state`), "containerId", `${label} state`));
12
+ return readKeyingVerificationShape(() => {
13
+ const manifest = readCanonicalRecord(bundle.manifest, `${label} manifest`);
14
+ return readRecordString(manifest, "objectKind", `${label} manifest`) ===
15
+ "container"
16
+ ? readRecordString(manifest, "objectId", `${label} manifest`)
17
+ : null;
18
+ });
7
19
  }
8
20
  function citedContainerId(input, manifestHash) {
9
21
  const verified = input.verifiedByHash.get(manifestHash);
@@ -24,10 +36,14 @@ function citedManifestHashForContainer(input, cited, containerId) {
24
36
  return manifestHash;
25
37
  }
26
38
  async function resolveCitedManifest(input, manifestHash, containerId) {
39
+ // The cache answers only for the bytes it verified (a match is frozen, so
40
+ // each ancestor is serialized once however many descendants cite it); a
41
+ // served ancestor that differs is verified as a cold device would.
27
42
  const verified = input.verifiedByHash.get(manifestHash);
28
- if (verified)
29
- return verified;
30
43
  const bundle = input.bundlesByHash.get(manifestHash);
44
+ if (verified && (!bundle || matchesVerifiedBundleBytes(verified, bundle))) {
45
+ return verified;
46
+ }
31
47
  if (!bundle) {
32
48
  throw new KeyingVerificationError("missing_dependency", `${input.label} cites a head of container ${containerId} that the projection does not serve`);
33
49
  }
@@ -1 +1 @@
1
- {"version":3,"file":"containerAncestorCitations.js","sourceRoot":"","sources":["containerAncestorCitations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBAAmB,CAAC;AAE3B,OAAO,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,EAAE,2BAA2B,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EAAE,wBAAwB,EAAE,MAAM,YAAY,CAAC;AAuCtD,SAAS,iBAAiB,CACxB,MAAwC,EACxC,KAAa;IAEb,OAAO,2BAA2B,CAAC,GAAG,EAAE,CACtC,wBAAwB,CACtB,mBAAmB,CAAC,MAAM,CAAC,KAAK,EAAE,GAAG,KAAK,QAAQ,CAAC,EACnD,aAAa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AW,EAAE,CAAC;gBACrD,2BAA2B,CAAC,KAAK,EAAE,QAAQ,EAAE,KAAK,CAAC,CAAC;YACtD,CAAC;QACH,CAAC;IACH,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,yCAAyC,CAAC,KAKzD;IACC,MAAM,SAAS,GAAG,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,wBAAwB,CAAC;IAClE,KAAK,MAAM,MAAM,IAAI,KAAK,CAAC,eAAe,EAAE,CAAC;QAC3C,MAAM,WAAW,GAAG,MAAM,CAAC,KAAK,CAAC,WAAW,CAAC;QAC7C,MAAM,KAAK,GAAG,iBAAiB,CAAC;YAC9B,KAAK,EAAE,SAAS;YAChB,WAAW;YACX,KAAK,EAAE,KAAK,CAAC,KAAK;YAClB,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC,CAAC;QACH,IAAI,CAAC,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,cAAc,EAAE,MAAM,EAAE,KAAK,CAAC;YAAE,SAAS;QAC1E,MAAM,IAAI,uBAAuB,CAC/B,UAAU,EACV,GAAG,KAAK,CAAC,KAAK,uCAAuC,WAAW,qDAAqD,CACtH,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedAccessEvent,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport { readKeyingVerificationShape } from \"../error\";\nimport { readRecordNullableString } from \"../readers\";\n\n/**\n * A container manifest pins the parent manifest it was created or moved\n * under, and successors inherit that pin, so the pin says nothing about the\n * ancestor heads a later grant, revoke, or rekey was actually authorized\n * under. Those heads are in the event: every container event signs the\n * manifest hashes of the path it was committed against, and the API refuses\n * an event whose citations are not the current heads at commit time. So a\n * head's authorization path is rebuilt here from its citations, root to\n * parent, and the signer is checked against those heads rather than against\n * whatever path the server pairs with the manifest.\n *\n * A head must also cite, for every ancestor, a head that is or descends from\n * the head an earlier signed statement already established, so an ancestor\n * head one signed statement established can never be rolled back or forked\n * away for a later one.\n *\n * As with principal policies, a successor new to a device need not cite the\n * authority's served current head. An honest server serves a\n * child head citing the ancestor head that was current when it was\n * committed, signed by a member since revoked at that ancestor, and refusing\n * that shape would leave every device holding the child unable to supersede\n * it. What can be refused is the opposite disagreement: a served current\n * ancestor head that does not descend from a head the child's signed event\n * proves exists is a stale or forked ancestor, whatever the server calls\n * current.\n */\n\ninterface CitedAncestorResolutionInput {\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly label: string;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n readonly verifyHistoryBundle: (\n bundle: AccessManifestBundleWireResponse,\n label: string,\n ) => Promise<VerifiedContainerAccessManifest>;\n}\n\nfunction bundleContainerId(\n bundle: AccessManifestBundleWireResponse,\n label: string,\n): string | null {\n return readKeyingVerificationShape(() =>\n readRecordNullableString(\n readCanonicalRecord(bundle.state, `${label} state`),\n \"containerId\",\n `${label} state`,\n ),\n );\n}\n\nfunction citedContainerId(\n input: CitedLineageInput,\n manifestHash: string,\n): string | null {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified) return verified.state.containerId;\n const bundle = input.bundlesByHash.get(manifestHash);\n return bundle ? bundleContainerId(bundle, input.label) : null;\n}\n\nfunction citedManifestHashForContainer(\n input: CitedAncestorResolutionInput,\n cited: readonly string[],\n containerId: string,\n): string {\n const hashes = cited.filter(\n (manifestHash) => citedContainerId(input, manifestHash) === containerId,\n );\n const [manifestHash] = hashes;\n if (manifestHash === undefined) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} does not cite a served head of its parent container ${containerId}`,\n );\n }\n if (hashes.length > 1) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `${input.label} cites more than one head of container ${containerId}`,\n );\n }\n return manifestHash;\n}\n\nasync function resolveCitedManifest(\n input: CitedAncestorResolutionInput,\n manifestHash: string,\n containerId: string,\n): Promise<VerifiedContainerAccessManifest> {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified) return verified;\n const bundle = input.bundlesByHash.get(manifestHash);\n if (!bundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} cites a head of container ${containerId} that the projection does not serve`,\n );\n }\n return input.verifyHistoryBundle(\n bundle,\n `${input.label} cited ancestor ${containerId}`,\n );\n}\n\n/**\n * The ancestor path, root first, that a container event cites, ending at the\n * head of `parentContainerId`. Empty for a root container.\n */\nexport async function resolveCitedAncestorPath(\n input: CitedAncestorResolutionInput & {\n readonly event: VerifiedAccessEvent;\n readonly parentContainerId: string | null;\n },\n): Promise<VerifiedContainerAccessManifest[]> {\n const cited = input.event.event.dependencyManifestHashes;\n const chain: VerifiedContainerAccessManifest[] = [];\n const seen = new Set<string>();\n let containerId = input.parentContainerId;\n while (containerId !== null) {\n if (seen.has(containerId)) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} cited ancestors form a cycle at ${containerId}`,\n );\n }\n seen.add(containerId);\n const ancestor = await resolveCitedManifest(\n input,\n citedManifestHashForContainer(input, cited, containerId),\n containerId,\n );\n chain.unshift(ancestor);\n containerId = ancestor.state.parentContainerId;\n }\n return chain;\n}\n\n/** What the lineage rules read: the served and the verified bundles. */\nexport type CitedLineageInput = Pick<\n CitedAncestorResolutionInput,\n \"bundlesByHash\" | \"label\" | \"verifiedByHash\"\n>;\n\n/**\n * The verified head of `containerId` among the cited hashes, if any. Reads\n * verified manifests only: a cited hash the pass has not verified is not a\n * head to reason about, and every caller runs after the cited ancestor path\n * resolved and verified the chain. An event cites one head per container,\n * so a second verified one is a served citation set that was tampered with,\n * not a choice to make.\n */\nexport function verifiedCitedHead(input: {\n readonly cited: readonly string[];\n readonly containerId: string;\n readonly label: string;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): VerifiedContainerAccessManifest | undefined {\n let found: VerifiedContainerAccessManifest | undefined;\n for (const manifestHash of input.cited) {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified?.state.containerId !== input.containerId) continue;\n if (found && found.manifestHash !== verified.manifestHash) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `${input.label} cites more than one head of container ${input.containerId}`,\n );\n }\n found = verified;\n }\n return found;\n}\n\n/**\n * Whether `head` is `floor` or descends from it through verified\n * predecessors. Epochs alone would let a same-epoch fork signed under an\n * older head pass; lineage cannot be forged without the chain. Every\n * predecessor of a verified manifest was verified with it, so a hop that is\n * not in the verified set means the chain was not served.\n */\nfunction descendsFrom(\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n head: VerifiedContainerAccessManifest,\n floor: VerifiedContainerAccessManifest,\n): boolean {\n let current: VerifiedContainerAccessManifest | undefined = head;\n while (current && current.state.epoch >= floor.state.epoch) {\n if (current.manifestHash === floor.manifestHash) return true;\n const previousHash: string | null = current.state.previousManifestHash;\n current =\n previousHash === null ? undefined : verifiedByHash.get(previousHash);\n }\n return false;\n}\n\n/** The cited head must be the established head or descend from it. */\nfunction assertCitedHeadDescendsFrom(\n input: CitedLineageInput,\n cited: VerifiedContainerAccessManifest,\n floor: VerifiedContainerAccessManifest,\n): void {\n if (descendsFrom(input.verifiedByHash, cited, floor)) return;\n throw new KeyingVerificationError(\n \"rollback\",\n `${input.label} cites a head of container ${cited.state.containerId} that does not descend from the head an earlier signed statement already proved current`,\n );\n}\n\n/**\n * A head must not cite a head of any ancestor that does not descend from the\n * head an earlier signed statement already established: the manifest before\n * it cited that ancestor, the previous manifest's own pin when this is its\n * parent, or a cited child of that ancestor was created or moved under it and\n * cited it. Ancestors no statement establishes are skipped.\n */\nexport function assertCitedAncestorsDoNotRegress(\n input: CitedLineageInput & {\n readonly citedAncestors: readonly VerifiedContainerAccessManifest[];\n readonly previousManifest: VerifiedContainerAccessManifest | null;\n },\n): void {\n const previous = input.previousManifest;\n const previousCited = previous?.event.event.dependencyManifestHashes ?? [];\n input.citedAncestors.forEach((ancestor, index) => {\n const containerId = ancestor.state.containerId;\n const citedChild = input.citedAncestors[index + 1] ?? previous;\n const floors = [\n verifiedCitedHead({\n cited: previousCited,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n }),\n ...(citedChild\n ? [\n input.verifiedByHash.get(citedChild.state.parentManifestHash ?? \"\"),\n verifiedCitedHead({\n cited: citedChild.event.event.dependencyManifestHashes,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n }),\n ]\n : []),\n ];\n for (const floor of floors) {\n if (floor && floor.state.containerId === containerId) {\n assertCitedHeadDescendsFrom(input, ancestor, floor);\n }\n }\n });\n}\n\n/**\n * Every served current ancestor head must be, or descend through verified\n * predecessors from, the head of that container the head's signed event\n * cites. A served head older than the cited one, or a same-epoch fork of it,\n * is a rollback the signature proves: the cited head exists. A served head\n * newer than the cited one is the ordinary lag of a descendant behind its\n * ancestors, and an ancestor the head does not cite at all joined the path\n * when an ancestor between them moved; neither is refused.\n */\nexport function assertServedAncestorsDescendFromCitations(input: {\n readonly head: VerifiedContainerAccessManifest;\n readonly label: string;\n readonly servedAncestors: readonly VerifiedContainerAccessManifest[];\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): void {\n const citations = input.head.event.event.dependencyManifestHashes;\n for (const served of input.servedAncestors) {\n const containerId = served.state.containerId;\n const cited = verifiedCitedHead({\n cited: citations,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n });\n if (!cited || descendsFrom(input.verifiedByHash, served, cited)) continue;\n throw new KeyingVerificationError(\n \"rollback\",\n `${input.label} cites a head of ancestor container ${containerId} that the served current head does not descend from`,\n );\n }\n}\n"]}
1
+ {"version":3,"file":"containerAncestorCitations.js","sourceRoot":"","sources":["containerAncestorCitations.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,GAGxB,MAAM,mBA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E,KAAK,CAAC,KAAK;YAClB,cAAc,EAAE,KAAK,CAAC,cAAc;SACrC,CAAC,CAAC;QACH,IAAI,CAAC,KAAK,IAAI,YAAY,CAAC,KAAK,CAAC,cAAc,EAAE,MAAM,EAAE,KAAK,CAAC;YAAE,SAAS;QAC1E,MAAM,IAAI,uBAAuB,CAC/B,UAAU,EACV,GAAG,KAAK,CAAC,KAAK,uCAAuC,WAAW,qDAAqD,CACtH,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import {\n KeyingVerificationError,\n type VerifiedAccessEvent,\n type VerifiedContainerAccessManifest,\n} from \"@tearleads/crypto\";\nimport type { AccessManifestBundleWireResponse } from \"@tearleads/validators/response\";\nimport { readCanonicalRecord } from \"../../keying/canonicalJson\";\nimport { matchesVerifiedBundleBytes } from \"../checkpoints/verifiedBundleBytes\";\nimport { readKeyingVerificationShape } from \"../error\";\nimport { readRecordString } from \"../readers\";\n\n/**\n * A container manifest pins the parent manifest it was created or moved\n * under, and successors inherit that pin, so the pin says nothing about the\n * ancestor heads a later grant, revoke, or rekey was actually authorized\n * under. Those heads are in the event: every container event signs the\n * manifest hashes of the path it was committed against, and the API refuses\n * an event whose citations are not the current heads at commit time. So a\n * head's authorization path is rebuilt here from its citations, root to\n * parent, and the signer is checked against those heads rather than against\n * whatever path the server pairs with the manifest.\n *\n * A head must also cite, for every ancestor, a head that is or descends from\n * the head an earlier signed statement already established, so an ancestor\n * head one signed statement established can never be rolled back or forked\n * away for a later one.\n *\n * As with principal policies, a successor new to a device need not cite the\n * authority's served current head. An honest server serves a\n * child head citing the ancestor head that was current when it was\n * committed, signed by a member since revoked at that ancestor, and refusing\n * that shape would leave every device holding the child unable to supersede\n * it. What can be refused is the opposite disagreement: a served current\n * ancestor head that does not descend from a head the child's signed event\n * proves exists is a stale or forked ancestor, whatever the server calls\n * current.\n */\n\ninterface CitedAncestorResolutionInput {\n readonly bundlesByHash: ReadonlyMap<string, AccessManifestBundleWireResponse>;\n readonly label: string;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n readonly verifyHistoryBundle: (\n bundle: AccessManifestBundleWireResponse,\n label: string,\n ) => Promise<VerifiedContainerAccessManifest>;\n}\n\n/**\n * The container a served bundle's manifest names, before it verifies. The\n * manifest hash commits to it, and verification binds it to the signed event\n * and the derived state, so a selection made here is checked there.\n */\nfunction bundleContainerId(\n bundle: AccessManifestBundleWireResponse,\n label: string,\n): string | null {\n return readKeyingVerificationShape(() => {\n const manifest = readCanonicalRecord(bundle.manifest, `${label} manifest`);\n return readRecordString(manifest, \"objectKind\", `${label} manifest`) ===\n \"container\"\n ? readRecordString(manifest, \"objectId\", `${label} manifest`)\n : null;\n });\n}\n\nfunction citedContainerId(\n input: CitedLineageInput,\n manifestHash: string,\n): string | null {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified) return verified.state.containerId;\n const bundle = input.bundlesByHash.get(manifestHash);\n return bundle ? bundleContainerId(bundle, input.label) : null;\n}\n\nfunction citedManifestHashForContainer(\n input: CitedAncestorResolutionInput,\n cited: readonly string[],\n containerId: string,\n): string {\n const hashes = cited.filter(\n (manifestHash) => citedContainerId(input, manifestHash) === containerId,\n );\n const [manifestHash] = hashes;\n if (manifestHash === undefined) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} does not cite a served head of its parent container ${containerId}`,\n );\n }\n if (hashes.length > 1) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `${input.label} cites more than one head of container ${containerId}`,\n );\n }\n return manifestHash;\n}\n\nasync function resolveCitedManifest(\n input: CitedAncestorResolutionInput,\n manifestHash: string,\n containerId: string,\n): Promise<VerifiedContainerAccessManifest> {\n // The cache answers only for the bytes it verified (a match is frozen, so\n // each ancestor is serialized once however many descendants cite it); a\n // served ancestor that differs is verified as a cold device would.\n const verified = input.verifiedByHash.get(manifestHash);\n const bundle = input.bundlesByHash.get(manifestHash);\n if (verified && (!bundle || matchesVerifiedBundleBytes(verified, bundle))) {\n return verified;\n }\n if (!bundle) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n `${input.label} cites a head of container ${containerId} that the projection does not serve`,\n );\n }\n return input.verifyHistoryBundle(\n bundle,\n `${input.label} cited ancestor ${containerId}`,\n );\n}\n\n/**\n * The ancestor path, root first, that a container event cites, ending at the\n * head of `parentContainerId`. Empty for a root container.\n */\nexport async function resolveCitedAncestorPath(\n input: CitedAncestorResolutionInput & {\n readonly event: VerifiedAccessEvent;\n readonly parentContainerId: string | null;\n },\n): Promise<VerifiedContainerAccessManifest[]> {\n const cited = input.event.event.dependencyManifestHashes;\n const chain: VerifiedContainerAccessManifest[] = [];\n const seen = new Set<string>();\n let containerId = input.parentContainerId;\n while (containerId !== null) {\n if (seen.has(containerId)) {\n throw new KeyingVerificationError(\n \"object_mismatch\",\n `${input.label} cited ancestors form a cycle at ${containerId}`,\n );\n }\n seen.add(containerId);\n const ancestor = await resolveCitedManifest(\n input,\n citedManifestHashForContainer(input, cited, containerId),\n containerId,\n );\n chain.unshift(ancestor);\n containerId = ancestor.state.parentContainerId;\n }\n return chain;\n}\n\n/** What the lineage rules read: the served and the verified bundles. */\nexport type CitedLineageInput = Pick<\n CitedAncestorResolutionInput,\n \"bundlesByHash\" | \"label\" | \"verifiedByHash\"\n>;\n\n/**\n * The verified head of `containerId` among the cited hashes, if any. Reads\n * verified manifests only: a cited hash the pass has not verified is not a\n * head to reason about, and every caller runs after the cited ancestor path\n * resolved and verified the chain. An event cites one head per container,\n * so a second verified one is a served citation set that was tampered with,\n * not a choice to make.\n */\nexport function verifiedCitedHead(input: {\n readonly cited: readonly string[];\n readonly containerId: string;\n readonly label: string;\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): VerifiedContainerAccessManifest | undefined {\n let found: VerifiedContainerAccessManifest | undefined;\n for (const manifestHash of input.cited) {\n const verified = input.verifiedByHash.get(manifestHash);\n if (verified?.state.containerId !== input.containerId) continue;\n if (found && found.manifestHash !== verified.manifestHash) {\n throw new KeyingVerificationError(\n \"duplicate_entry\",\n `${input.label} cites more than one head of container ${input.containerId}`,\n );\n }\n found = verified;\n }\n return found;\n}\n\n/**\n * Whether `head` is `floor` or descends from it through verified\n * predecessors. Epochs alone would let a same-epoch fork signed under an\n * older head pass; lineage cannot be forged without the chain. Every\n * predecessor of a verified manifest was verified with it, so a hop that is\n * not in the verified set means the chain was not served.\n */\nfunction descendsFrom(\n verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>,\n head: VerifiedContainerAccessManifest,\n floor: VerifiedContainerAccessManifest,\n): boolean {\n let current: VerifiedContainerAccessManifest | undefined = head;\n while (current && current.state.epoch >= floor.state.epoch) {\n if (current.manifestHash === floor.manifestHash) return true;\n const previousHash: string | null = current.state.previousManifestHash;\n current =\n previousHash === null ? undefined : verifiedByHash.get(previousHash);\n }\n return false;\n}\n\n/** The cited head must be the established head or descend from it. */\nfunction assertCitedHeadDescendsFrom(\n input: CitedLineageInput,\n cited: VerifiedContainerAccessManifest,\n floor: VerifiedContainerAccessManifest,\n): void {\n if (descendsFrom(input.verifiedByHash, cited, floor)) return;\n throw new KeyingVerificationError(\n \"rollback\",\n `${input.label} cites a head of container ${cited.state.containerId} that does not descend from the head an earlier signed statement already proved current`,\n );\n}\n\n/**\n * A head must not cite a head of any ancestor that does not descend from the\n * head an earlier signed statement already established: the manifest before\n * it cited that ancestor, the previous manifest's own pin when this is its\n * parent, or a cited child of that ancestor was created or moved under it and\n * cited it. Ancestors no statement establishes are skipped.\n */\nexport function assertCitedAncestorsDoNotRegress(\n input: CitedLineageInput & {\n readonly citedAncestors: readonly VerifiedContainerAccessManifest[];\n readonly previousManifest: VerifiedContainerAccessManifest | null;\n },\n): void {\n const previous = input.previousManifest;\n const previousCited = previous?.event.event.dependencyManifestHashes ?? [];\n input.citedAncestors.forEach((ancestor, index) => {\n const containerId = ancestor.state.containerId;\n const citedChild = input.citedAncestors[index + 1] ?? previous;\n const floors = [\n verifiedCitedHead({\n cited: previousCited,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n }),\n ...(citedChild\n ? [\n input.verifiedByHash.get(citedChild.state.parentManifestHash ?? \"\"),\n verifiedCitedHead({\n cited: citedChild.event.event.dependencyManifestHashes,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n }),\n ]\n : []),\n ];\n for (const floor of floors) {\n if (floor && floor.state.containerId === containerId) {\n assertCitedHeadDescendsFrom(input, ancestor, floor);\n }\n }\n });\n}\n\n/**\n * Every served current ancestor head must be, or descend through verified\n * predecessors from, the head of that container the head's signed event\n * cites. A served head older than the cited one, or a same-epoch fork of it,\n * is a rollback the signature proves: the cited head exists. A served head\n * newer than the cited one is the ordinary lag of a descendant behind its\n * ancestors, and an ancestor the head does not cite at all joined the path\n * when an ancestor between them moved; neither is refused.\n */\nexport function assertServedAncestorsDescendFromCitations(input: {\n readonly head: VerifiedContainerAccessManifest;\n readonly label: string;\n readonly servedAncestors: readonly VerifiedContainerAccessManifest[];\n readonly verifiedByHash: ReadonlyMap<string, VerifiedContainerAccessManifest>;\n}): void {\n const citations = input.head.event.event.dependencyManifestHashes;\n for (const served of input.servedAncestors) {\n const containerId = served.state.containerId;\n const cited = verifiedCitedHead({\n cited: citations,\n containerId,\n label: input.label,\n verifiedByHash: input.verifiedByHash,\n });\n if (!cited || descendsFrom(input.verifiedByHash, served, cited)) continue;\n throw new KeyingVerificationError(\n \"rollback\",\n `${input.label} cites a head of ancestor container ${containerId} that the served current head does not descend from`,\n );\n }\n}\n"]}
@@ -1,12 +1,11 @@
1
1
  import { KeyingVerificationError, principalPolicyMatchesReference, readKeyingCanonicalJson, verifyContainerAccessManifest, } from "../../../internal/crypto/index.js";
2
- import { readCanonicalRecord } from "../../keying/canonicalJson.js";
3
2
  import { assertCanonicalEqual, verifyAccessEventBundle, } from "../checkpoints/bundleVerification.js";
4
3
  import { loadManifestCheckpointVerification, verifyCachedManifestCheckpoint, } from "../checkpoints/manifestCheckpointVerification.js";
5
- import { recordVerifiedBundleBytes } from "../checkpoints/verifiedBundleBytes.js";
6
- import { readKeyingVerificationShape } from "../error.js";
4
+ import { assertUnchangedSinceVerification, matchesVerifiedBundleBytes, recordVerifiedBundleBytes, } from "../checkpoints/verifiedBundleBytes.js";
7
5
  import { collectReferencedPrincipalPolicies } from "../principalPolicy/principalPolicyVerification.js";
8
- import { readAccessManifest, readRecordNullableString } from "../readers.js";
6
+ import { readAccessManifest } from "../readers.js";
9
7
  import { assertCitedAncestorsDoNotRegress, resolveCitedAncestorPath, } from "./containerAncestorCitations.js";
8
+ import { assertSignedContainerParentPin, readContainerEventBodyParentReference, readSignedContainerParentReference, } from "./containerSignedParentReference.js";
10
9
  async function collectManifestAuthorizationPolicies(input) {
11
10
  const missingPrincipalHeads = input.referencedPrincipalHeads.filter((reference) => !input.authorizationEvidence.some((policy) => principalPolicyMatchesReference({ policy, reference })));
12
11
  if (input.requireAuthorizationEvidence && missingPrincipalHeads.length > 0) {
@@ -29,7 +28,11 @@ async function collectManifestAuthorizationPolicies(input) {
29
28
  export async function verifyContainerManifestBundle(input) {
30
29
  const parentPath = await resolveContainerManifestVerificationParentPath(input);
31
30
  const cached = input.verifiedByHash.get(input.bundle.manifestHash);
32
- if (cached) {
31
+ // A cache hit vouches for the bytes it verified: a copy that differs is
32
+ // verified afresh, so a warm cache neither vouches for bytes no
33
+ // verification saw nor refuses a copy a cold one would accept.
34
+ if (cached && matchesVerifiedBundleBytes(cached, input.bundle)) {
35
+ assertVerifiedState(input, cached);
33
36
  assertContainerParentPathMatches({
34
37
  label: input.label,
35
38
  parentPath,
@@ -42,6 +45,9 @@ export async function verifyContainerManifestBundle(input) {
42
45
  localCheckpoints: input.checkpointContext.localCheckpoints,
43
46
  verifiedManifests: input.verifiedByHash,
44
47
  });
48
+ // The caller reads this bundle on return, after the checkpoint read.
49
+ assertUnchangedSinceVerification(cached, input.bundle, input.label);
50
+ assertVerifiedState(input, cached);
45
51
  }
46
52
  return cached;
47
53
  }
@@ -57,7 +63,10 @@ export async function verifyContainerManifestBundle(input) {
57
63
  verifying.delete(input.bundle.manifestHash);
58
64
  }
59
65
  }
60
- async function verifyFreshContainerManifestBundle(input, parentPath) {
66
+ async function verifyFreshContainerManifestBundle(served, parentPath) {
67
+ // Verify and record one copy taken before the first await, so the bytes
68
+ // recorded as verified are exactly the bytes verified.
69
+ const input = { ...served, bundle: structuredClone(served.bundle) };
61
70
  const event = await verifyAccessEventBundle(input);
62
71
  const manifest = readAccessManifest(input.bundle.manifest, `${input.label} manifest`);
63
72
  const authorization = await resolveContainerManifestAuthorization(input, event, parentPath);
@@ -104,14 +113,20 @@ async function verifyFreshContainerManifestBundle(input, parentPath) {
104
113
  if (!verified.ok) {
105
114
  throw new KeyingVerificationError(verified.error.code, `${input.label} manifest verification failed: ${verified.error.message}`);
106
115
  }
116
+ assertSignedContainerParentPin(input, verified.value);
117
+ assertVerifiedState(input, verified.value);
118
+ input.verifiedByHash.set(input.bundle.manifestHash, verified.value);
119
+ recordVerifiedBundleBytes(verified.value, input.bundle);
120
+ assertUnchangedSinceVerification(verified.value, served.bundle, input.label, input.bundle);
121
+ assertVerifiedState(served, verified.value);
122
+ return verified.value;
123
+ }
124
+ function assertVerifiedState(input, verified) {
107
125
  assertCanonicalEqual({
108
126
  actual: input.bundle.state,
109
- expected: readKeyingCanonicalJson(verified.value.state, `${input.label} state`),
127
+ expected: readKeyingCanonicalJson(verified.state, `${input.label} state`),
110
128
  label: `${input.label} state`,
111
129
  });
112
- input.verifiedByHash.set(input.bundle.manifestHash, verified.value);
113
- recordVerifiedBundleBytes(verified.value, input.bundle);
114
- return verified.value;
115
130
  }
116
131
  /**
117
132
  * The paths a container event is authorized against: its previous manifest
@@ -209,26 +224,14 @@ function assertContainerParentPathMatches(input) {
209
224
  throw new KeyingVerificationError("object_mismatch", `${input.label} parent path mismatch`);
210
225
  }
211
226
  }
212
- function readParentReference(value, label) {
213
- return readKeyingVerificationShape(() => {
214
- const record = readCanonicalRecord(value, label);
215
- return {
216
- parentContainerId: readRecordNullableString(record, "parentContainerId", label),
217
- parentManifestHash: readRecordNullableString(record, "parentManifestHash", label),
218
- };
219
- });
220
- }
221
- function readContainerManifestParentReference(bundle, label) {
222
- return readParentReference(bundle.state, `${label} state`);
223
- }
224
- /** The parent a create or move body pins, read from the signed body. */
225
- function readContainerEventBodyParentReference(event, label) {
226
- return readParentReference(event.body, `${label} event body`);
227
- }
228
227
  async function resolveContainerManifestVerificationParentPath(input) {
228
+ const resolvingParents = input.resolvingParents ?? new Set();
229
+ if (resolvingParents.has(input.bundle.manifestHash)) {
230
+ throw new KeyingVerificationError("object_mismatch", `${input.label} parent pins form a cycle`);
231
+ }
229
232
  // Descendants keep the parent manifest hash they were created or moved under;
230
233
  // a later parent share/rekey must not require rewriting descendant manifests.
231
- const { parentContainerId, parentManifestHash } = readContainerManifestParentReference(input.bundle, input.label);
234
+ const { parentContainerId, parentManifestHash } = readSignedContainerParentReference(input);
232
235
  if (parentContainerId === null || parentManifestHash === null) {
233
236
  return [];
234
237
  }
@@ -241,11 +244,19 @@ async function resolveContainerManifestVerificationParentPath(input) {
241
244
  if (!parentBundle) {
242
245
  return input.parentPath;
243
246
  }
244
- const parentParentPath = await resolveContainerManifestVerificationParentPath({
245
- ...input,
246
- bundle: parentBundle,
247
- label: `${input.label} parent manifest`,
248
- });
247
+ resolvingParents.add(input.bundle.manifestHash);
248
+ let parentParentPath;
249
+ try {
250
+ parentParentPath = await resolveContainerManifestVerificationParentPath({
251
+ ...input,
252
+ bundle: parentBundle,
253
+ label: `${input.label} parent manifest`,
254
+ resolvingParents,
255
+ });
256
+ }
257
+ finally {
258
+ resolvingParents.delete(input.bundle.manifestHash);
259
+ }
249
260
  const verifiedParent = await verifyContainerManifestBundle({
250
261
  ...input,
251
262
  bundle: parentBundle,