# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-aaif-scoped-short-lived-token-as-non-transferable-across-a-delegation-hop-and-how-does-proof-of-posses.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-aaif-scoped-short-lived-token-as-non-transferable-across-a-delegation-hop-and-how-does-proof-of-posses.warrant.json
# Markdown SHA-256:   299db3d80b873cafb7f1f8e890a5e0565cbb198b43a9e6a6c4effb0261a6c202
# Code AST SHA-256:   d90b0348d8e0e9b70e02f3020985b2ad6eb3d5b5cf35fb920420e13f147fcd26
# Verified Classes:   PoPBindingViolation
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class PoPBindingViolation(RuntimeError):
    """Raised when a presented AAIF token's proof-of-possession binding does not
    match the presenting agent's key, i.e. the token is being passed through by a
    non-bound holder. This is a hard fail-closed condition, never a warning."""
    pass


def verify_aaif_hop(token: dict, presented_jwk: dict, nonce: bytes,
                    detached_sig: bytes, now: int) -> str:
    # 1. Standard claims.
    if token.get("exp", 0) <= now:
        raise PoPBindingViolation("token expired at hop")
    if token.get("aud") != "tool-runner":
        raise PoPBindingViolation("audience mismatch at hop")

    # 2. Proof signature validity (necessary, not sufficient).
    if not _verify_sig(presented_jwk, nonce, detached_sig):
        raise PoPBindingViolation("detached JWS over nonce invalid")

    # 3. THE BINDING CHECK — the step that is silently skipped in the field.
    cnf = token.get("cnf")
    if cnf is None:
        # A delegated token with no cnf is not a bearer grant; it is a defect.
        raise PoPBindingViolation(
            "delegated token lacks cnf claim; refusing bearer fallback")
    presented_jkt = _jwk_thumbprint(presented_jwk)
    if cnf.get("jkt") != presented_jkt:
        raise PoPBindingViolation(
            f"cnf.jkt={cnf.get('jkt')} != presented_jkt={presented_jkt}; "
            "token is being forwarded by a non-bound holder")

    return token["sub"]


def _verify_sig(jwk: dict, nonce: bytes, sig: bytes) -> bool:
    ...


def _jwk_thumbprint(jwk: dict) -> str:
    ...
