# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-distrust-a-capability-it-itself-issued-stale-authority-resurrection-in-trust-broker-mediated-capability-exchange.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-distrust-a-capability-it-itself-issued-stale-authority-resurrection-in-trust-broker-mediated-capability-exchange.warrant.json
# Markdown SHA-256:   e5c9cce56a555662031ce90a3bd2ec4f3fd6f9a75927b7a44fb431a51a77be76
# Code AST SHA-256:   ddfabe4c1a8eca76aeb2ed024c0254f6a5c3ca5ed740969e641e8d8635a50161
# Verified Classes:   StaleAuthorityError, CapabilityVerifier
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StaleAuthorityError(RuntimeError):
    """Raised when a capability is signature-valid but predates the issuer's current policy epoch."""
    pass


class CapabilityVerifier:
    def __init__(self, epoch_floor_by_issuer: dict[str, int], strict_scopes: set[str]):
        # epoch_floor_by_issuer: last known-good policy epoch per broker, refreshed out-of-band
        self.epoch_floor_by_issuer = epoch_floor_by_issuer
        self.strict_scopes = strict_scopes

    def verify(self, token: dict, replay_cache: set[str]) -> None:
        # Standard checks: signature, TTL, nonce uniqueness.
        if not token.get("sig_valid", False):
            raise StaleAuthorityError("signature invalid")
        if token["expires_at"] <= token["now"]:
            raise StaleAuthorityError("token expired")
        if token["nonce"] in replay_cache:
            raise StaleAuthorityError("replay detected")
        replay_cache.add(token["nonce"])

        # The non-obvious check: freshness relative to issuer epoch, for strict scopes only.
        if token["scope"] in self.strict_scopes:
            floor = self.epoch_floor_by_issuer.get(token["issuer"])
            if floor is None:
                raise StaleAuthorityError(
                    f"no epoch floor known for issuer {token['issuer']}; "
                    f"cannot establish present authority for scope {token['scope']}"
                )
            if token["minted_epoch"] < floor:
                raise StaleAuthorityError(
                    f"resurrection: token minted at epoch {token['minted_epoch']} "
                    f"< issuer floor {floor} for scope {token['scope']}"
                )
