# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-manifest-replay-attacks-from-surviving-mcp-capability-re-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-manifest-replay-attacks-from-surviving-mcp-capability-re-attestation.warrant.json
# Markdown SHA-256:   eeb8eeab893521e4eb588449c3ffcb68c206ac5945fa84ac005d202443715e75
# Code AST SHA-256:   33c2f1450c468a682678f53d8f9a432da28aaf5ad4a979726110096cf2d73651
# Verified Classes:   ManifestReplayError, AttestationEpochError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import json


class ManifestReplayError(RuntimeError):
    pass


class AttestationEpochError(RuntimeError):
    pass


def canonical_digest(manifest_body: dict) -> str:
    canonical = json.dumps(manifest_body, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(canonical.encode("utf-8")).hexdigest()


def verify_attestation(
    manifest_body: dict,
    token: dict,
    last_seen_epoch: dict,
) -> bool:
    publisher = token.get("publisher")
    if publisher is None:
        raise ManifestReplayError("token missing publisher identity")

    actual_digest = canonical_digest(manifest_body)

    if token.get("manifest_digest") != actual_digest:
        raise ManifestReplayError(
            f"token digest {token.get('manifest_digest')} does not match "
            f"manifest body digest {actual_digest}"
        )

    if token.get("capabilities") != manifest_body.get("capabilities"):
        raise ManifestReplayError(
            "token capability set does not match manifest body capability set"
        )

    prior_epoch = last_seen_epoch.get(publisher, -1)
    if token.get("epoch", -1) <= prior_epoch:
        raise AttestationEpochError(
            f"epoch {token.get('epoch')} not greater than prior epoch "
            f"{prior_epoch} for publisher {publisher}"
        )

    last_seen_epoch[publisher] = token["epoch"]
    return True
