import base64
import hashlib
import ipaddress
import json
import re
import socket
import threading
import time
import urllib.error
import urllib.parse
import urllib.request

REASONS = {
    'no_signature_headers': ('tap_missing', 'The request has no Signature-Input and Signature headers.'),
    'signature_input_format': ('tap_malformed', 'Signature-Input must be label sig2, then the covered components, created, expires, keyid, alg, nonce and tag="agent-browser-auth", in that order. The nonce is 32 bytes of base64.'),
    'signature_header_format': ('tap_malformed', 'Signature must be sig2=:<base64>:.'),
    'components_invalid': ('tap_malformed', 'The covered components are unreadable or repeated.'),
    'directory_components_missing': ('tap_malformed', 'A key named by directory ID must also cover @query, accept and content-type when sent.'),
    'required_components_missing': ('tap_malformed', 'The signature must cover @method, @scheme, @authority, @path, @query and content-digest first, in that order.'),
    'credential_header_present': ('tap_malformed', 'Authorization, Cookie, X-Payment and Payment-Signature are refused. Authenticate first and remove them before this check.'),
    'method_not_allowed': ('tap_malformed', 'Only GET, HEAD and POST can be signed.'),
    'signed_header_invalid': ('tap_malformed', 'A covered header is out of order, absent, starts or ends with a space, is not printable ASCII, is over 4096 characters, or is one this profile never signs, such as Origin, Host or X-Forwarded-For. At most 38 components and 16384 characters of signed headers.'),
    'uncovered_header': ('tap_malformed', 'The request carries a header the signature does not cover. Only transport headers may go unsigned.'),
    'nonce_format': ('tap_malformed', 'The nonce must be exactly 32 bytes of canonical base64.'),
    'body_too_large': ('tap_malformed', 'The body is over 1 MiB.'),
    'digest_format': ('tap_malformed', 'Content-Digest must be sha-256=:<base64>:.'),
    'not_yet_valid': ('tap_expired', 'The signature was created in the future. Check the clock.'),
    'expired': ('tap_expired', 'The signature has expired. Sign a new request.'),
    'lifetime_too_long': ('tap_expired', 'The signature lives longer than 60 seconds.'),
    'nonce_reused': ('tap_replayed', 'This key and nonce were already used. Sign a new request.'),
    'key_not_listed': ('tap_key_unknown', 'This key has no live listing. It may be unknown, paused or revoked; the registry does not say which.'),
    'agent_not_live': ('tap_key_inactive', 'The registry reports this agent as not live.'),
    'key_not_live': ('tap_key_inactive', "This key is not one of the agent's live keys: it was replaced, or its expirationDate has passed."),
    'body_digest_mismatch': ('tap_signature_invalid', 'The body does not match the signed Content-Digest. Digest the raw bytes, before anything parses them.'),
    'signature_mismatch': ('tap_signature_invalid', 'The signature does not verify for this exact request. Check that your pinned origin is what the agent signed for.'),
    'algorithm_mismatch': ('tap_signature_invalid', "The signature's alg is not the algorithm of the listed key."),
    'signature_agent_not_accepted': ('tap_signature_agent_not_accepted', 'Signature-Agent is not on your allowlist.'),
    'signature_agent_other_directory': ('tap_signature_agent_not_accepted', 'Signature-Agent names a different directory from the one this verifier reads.'),
    'key_not_in_directory': ('tap_key_unknown', "Visa's directory names keys by UUID, and this keyid is a thumbprint."),
    'simulated_listing': ('tap_simulated_not_accepted', 'This key belongs to a simulated test listing, which this verifier does not accept.'),
    'listing_unusable': ('tap_trust_invalid', 'The registry returned an unusable answer. The agent has not been judged.'),
    'registry_unavailable': ('tap_trust_unavailable', 'The registry could not be reached. The agent has not been judged; retry later.'),
    'nonce_store_unavailable': ('tap_trust_unavailable', 'The nonce store could not be reached. The agent has not been judged; retry later.'),
    'request_target_invalid': ('tap_malformed', 'The request target is not in normal form: it does not start with a single /, or it has dot segments, encoded dots, slashes or backslashes, a fragment, or does not parse. The signature covers the host and path exactly, so it is refused rather than normalized.'),
    'request_unreadable': ('tap_malformed', 'The request could not be read.'),
    'origin_not_https': ('tap_malformed', 'The pinned public origin is not https. Agents only sign https URLs, so pin an https origin.'),
    'origin_not_normal': ('tap_malformed', 'The pinned public origin is not in normal form: write the host in lowercase, as plain DNS labels or an IP address, with no default port, trailing dot or trailing slash, such as https://market.example. pinned_origin() does this for you.'),
}
COULD_NOT_CHECK = {'tap_trust_invalid', 'tap_trust_unavailable'}

INPUT = re.compile(r'sig2=\(([^)]+)\);created=(\d+);expires=(\d+);keyid="([A-Za-z0-9_-]{43}|[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})";alg="(ed25519|Ed25519|ecdsa-p256-sha256)";nonce="([A-Za-z0-9+/]{43}=)";tag="agent-browser-auth"')
SIGNATURE = re.compile(r'sig2=:((?:[A-Za-z0-9+/]{4})+(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?|[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=):')
CORE = ['@method', '@scheme', '@authority', '@path', '@query', 'content-digest']
TRANSPORT_HEADERS = {
    'host', 'content-length', 'connection', 'transfer-encoding', 'keep-alive', 'accept', 'accept-language', 'accept-encoding', 'user-agent',
    'forwarded', 'via', 'x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host', 'x-forwarded-port', 'x-forwarded-ssl', 'x-real-ip',
    'true-client-ip', 'cdn-loop', 'traceparent', 'tracestate', 'x-request-id', 'x-amzn-trace-id', 'x-cloud-trace-context',
    'b3', 'x-b3-traceid', 'x-b3-spanid', 'x-b3-parentspanid', 'x-b3-sampled',
    'cf-ray', 'cf-connecting-ip', 'cf-connecting-ipv6', 'cf-pseudo-ipv4', 'cf-connecting-o2o', 'cf-ew-via', 'cf-worker', 'cf-visitor',
    'cf-ipcountry', 'cf-ipcity', 'cf-ipcontinent', 'cf-iplatitude', 'cf-iplongitude', 'cf-region', 'cf-region-code', 'cf-metro-code',
    'cf-postal-code', 'cf-timezone',
    'x-vercel-id', 'x-vercel-forwarded-for', 'x-vercel-deployment-url', 'x-vercel-ip-continent', 'x-vercel-ip-country',
    'x-vercel-ip-country-region', 'x-vercel-ip-city', 'x-vercel-ip-latitude', 'x-vercel-ip-longitude', 'x-vercel-ip-timezone',
    'x-vercel-ip-postal-code',
    'fly-client-ip', 'fly-forwarded-port', 'fly-region', 'fly-request-id',
    'signature', 'signature-input', 'content-digest',
}
CREDENTIALS = ['authorization', 'cookie', 'x-payment', 'payment-signature']
NEVER_SIGNED = {
    'authorization', 'proxy-authorization', 'cookie', 'set-cookie', 'host', 'connection', 'content-length', 'transfer-encoding', 'te',
    'trailer', 'upgrade', 'keep-alive', 'expect', 'via', 'forwarded', 'origin', 'referer', 'content-digest', 'signature', 'signature-input',
    'agent-payer-auth', 'payment', 'payment-signature', 'payment-required', 'payment-receipt', 'payment-response',
}
NEVER_SIGNED_PREFIX = re.compile(r'proxy-|sec-|x-forwarded-|x-visa(?:$|-)|x-stamp(?:$|-)|x-payment(?:$|-)')
HEADER_NAME = re.compile(r"[!#$%&'*+.^_`|~0-9a-z-]{1,128}")
DIGEST = re.compile(r'sha-256=:[A-Za-z0-9+/]+={0,2}:')
EXPIRY = re.compile(r'([0-9]{4})-([0-9]{2})-([0-9]{2})[Tt]([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.([0-9]+))?(?:[Zz]|([+-])([0-9]{2}):([0-9]{2}))')
MAX_LIFETIME_SECONDS = 60
CLOCK_SKEW_SECONDS = 30
MAX_BODY_BYTES = 1024 * 1024
ED25519_SPKI = bytes.fromhex('302a300506032b6570032100')
HOST = re.compile(r'([a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*|\[[0-9a-f:]+\])(:[1-9][0-9]{0,4})?')
PATH = re.compile(r"/[!$%&'()*+,\-./0-9:;=@A-Z\[\]_a-z|~]*")
QUERY = re.compile(r"\?[!$%&()*+,\-./0-9:;=?@A-Z\[\\\]^_`a-z{|}~]+")

P = 2**255 - 19
L = 2**252 + 27742317777372353535851937790883648493
D = -121665 * pow(121666, P - 2, P) % P
SQRT_M1 = pow(2, (P - 1) // 4, P)


def _recover_x(y, sign):
    if y >= P:
        return None
    x2 = (y * y - 1) * pow(D * y * y + 1, P - 2, P)
    if x2 % P == 0:
        return None if sign else 0
    x = pow(x2, (P + 3) // 8, P)
    if (x * x - x2) % P:
        x = x * SQRT_M1 % P
    if (x * x - x2) % P:
        return None
    return P - x if (x & 1) != sign else x


def _decompress(data):
    if len(data) != 32:
        return None
    y = int.from_bytes(data, 'little')
    sign, y = y >> 255, y & ((1 << 255) - 1)
    x = _recover_x(y, sign)
    return None if x is None else (x, y, 1, x * y % P)


def _add(a, b):
    e = (a[1] - a[0]) * (b[1] - b[0]) % P
    f = (a[1] + a[0]) * (b[1] + b[0]) % P
    g = 2 * a[3] * b[3] * D % P
    h = 2 * a[2] * b[2] % P
    e, f, g, h = f - e, h - g, h + g, f + e
    return (e * f % P, g * h % P, f * g % P, e * h % P)


def _multiply(scalar, point):
    result = (0, 1, 1, 0)
    while scalar:
        if scalar & 1:
            result = _add(result, point)
        point = _add(point, point)
        scalar >>= 1
    return result


def _same(a, b):
    return (a[0] * b[2] - b[0] * a[2]) % P == 0 and (a[1] * b[2] - b[1] * a[2]) % P == 0


_BASE_Y = 4 * pow(5, P - 2, P) % P
_BASE = (_recover_x(_BASE_Y, 0), _BASE_Y, 1, _recover_x(_BASE_Y, 0) * _BASE_Y % P)


def ed25519_verify(public, message, signature):
    if len(signature) != 64:
        return False
    a, r = _decompress(public), _decompress(signature[:32])
    s = int.from_bytes(signature[32:], 'little')
    if a is None or r is None or s >= L:
        return False
    h = int.from_bytes(hashlib.sha512(signature[:32] + public + message).digest(), 'little') % L
    return _same(_multiply(s, _BASE), _add(r, _multiply(h, a)))


P256_P = 2**256 - 2**224 + 2**192 + 2**96 - 1
P256_N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551
P256_B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b
P256_G = (0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296, 0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5)


def _p256_point(x, y):
    if not (0 <= x < P256_P and 0 <= y < P256_P) or (y * y - x * x * x + 3 * x - P256_B) % P256_P:
        return None
    return (x, y)


def _p256_add(a, b):
    if a is None:
        return b
    if b is None:
        return a
    if a[0] == b[0] and (a[1] + b[1]) % P256_P == 0:
        return None
    if a == b:
        m = (3 * a[0] * a[0] - 3) * pow(2 * a[1], -1, P256_P) % P256_P
    else:
        m = (b[1] - a[1]) * pow(b[0] - a[0], -1, P256_P) % P256_P
    x = (m * m - a[0] - b[0]) % P256_P
    return (x, (m * (a[0] - x) - a[1]) % P256_P)


def _p256_multiply(scalar, point):
    result = None
    while scalar:
        if scalar & 1:
            result = _p256_add(result, point)
        point = _p256_add(point, point)
        scalar >>= 1
    return result


def p256_verify(public, message, signature):
    if len(signature) != 64:
        return False
    r, s = int.from_bytes(signature[:32], 'big'), int.from_bytes(signature[32:], 'big')
    if not (0 < r < P256_N and 0 < s < P256_N):
        return False
    e = int.from_bytes(hashlib.sha256(message).digest(), 'big')
    w = pow(s, -1, P256_N)
    point = _p256_add(_p256_multiply(e * w % P256_N, P256_G), _p256_multiply(r * w % P256_N, public))
    return point is not None and point[0] % P256_N == r


def _signature_verifies(found, message, signature):
    if found['algorithm'] == 'ecdsa-p256-sha256':
        return p256_verify(found['raw'], message, signature)
    return ed25519_verify(found['raw'], message, signature)


def refusal(reason, retry_after_seconds=None, header=None):
    code, message = REASONS[reason]
    judged = code not in COULD_NOT_CHECK
    result = {'ok': False, 'code': code, 'reason': reason, 'message': f'{message} Header: {header}.' if header else message, 'judged': judged, 'status': 403 if judged else 503, 'retryAfterSeconds': retry_after_seconds}
    if header:
        result['header'] = header
    return result


def _canonical_host(host):
    if '%' in host:
        return None
    if ':' in host:
        try:
            number = int(ipaddress.IPv6Address(host))
        except ValueError:
            return None
        pieces = [(number >> (112 - 16 * i)) & 0xffff for i in range(8)]
        run, best = 0, (0, 8)
        for i, piece in enumerate(pieces):
            run = run + 1 if piece == 0 else 0
            if run > best[0]:
                best = (run, i - run + 1)
        text = lambda part: ':'.join(f'{piece:x}' for piece in part)
        if best[0] < 2:
            return f'[{text(pieces)}]'
        return f'[{text(pieces[:best[1]])}::{text(pieces[best[1] + best[0]:])}]'
    if re.fullmatch(r'[0-9]+|0x[0-9a-f]*', host.rsplit('.', 1)[-1]):
        try:
            return socket.inet_ntoa(socket.inet_aton(host))
        except OSError:
            return None
    return host


def _origin(value, schemes):
    if not isinstance(value, str) or re.search(r'[^\x21-\x7e]', value):
        return None
    try:
        parts = urllib.parse.urlsplit(value)
        port = parts.port
    except ValueError:
        return None
    if parts.scheme not in schemes or not parts.hostname or parts.username or parts.password or parts.path not in ('', '/') or parts.query or parts.fragment or value.endswith(('?', '#')):
        return None
    host = _canonical_host(parts.hostname)
    if not host:
        return None
    default = 443 if parts.scheme == 'https' else 80
    return parts.scheme, host, f'{parts.scheme}://{host}' + (f':{port}' if port is not None and port != default else '')


def pinned_origin(value):
    found = _origin(value, ('https',))
    if not found or not HOST.fullmatch(found[2][len('https://'):]):
        raise ValueError(f'The public origin must be an https origin with a plain host name and no path, such as https://market.example. Got: {value}')
    return found[2]


def registry_origin_from(value):
    found = _origin(value, ('https', 'http'))
    if not found or (found[0] == 'http' and found[1] not in ('localhost', '127.0.0.1', '[::1]')):
        raise ValueError(f'The registry origin must be https, such as https://auth.visacli.sh. Plain http is only for localhost, 127.0.0.1 or [::1]. Got: {value}')
    return found[2]


def _origin_is_normal(public_origin):
    found = _origin(public_origin, ('https',))
    return bool(found) and found[2] == public_origin and bool(HOST.fullmatch(public_origin[len('https://'):]))


def _split_target(target):
    if not isinstance(target, str) or not target.startswith('/') or target.startswith('//'):
        return None
    path, _, query = target.partition('?')
    query = f'?{query}' if '?' in target else ''
    if '#' in target or not PATH.fullmatch(path) or (query and not QUERY.fullmatch(query)):
        return None
    if re.search(r'%2e|%2f|%5c', path, re.IGNORECASE) or any(segment in ('.', '..') for segment in path.split('/')):
        return None
    return path, query


def _b64url(data):
    return base64.urlsafe_b64encode(data).rstrip(b'=').decode()


def _thumbprint(raw):
    if isinstance(raw, tuple):
        members = {'crv': 'P-256', 'kty': 'EC', 'x': _b64url(raw[0].to_bytes(32, 'big')), 'y': _b64url(raw[1].to_bytes(32, 'big'))}
    else:
        members = {'crv': 'Ed25519', 'kty': 'OKP', 'x': _b64url(raw)}
    return _b64url(hashlib.sha256(json.dumps(members, separators=(',', ':')).encode()).digest())


def _raw_key(public_key):
    pem = base64.b64decode(public_key, validate=True).decode()
    lines = pem.strip().splitlines()
    if lines[0] != '-----BEGIN PUBLIC KEY-----' or lines[-1] != '-----END PUBLIC KEY-----':
        return None
    der = base64.b64decode(''.join(lines[1:-1]), validate=True)
    if len(der) != 44 or not der.startswith(ED25519_SPKI):
        return None
    return der[len(ED25519_SPKI):]


def _expiry_seconds(value):
    found = EXPIRY.fullmatch(value) if isinstance(value, str) else None
    if not found:
        return None
    year, month, day, hour, minute, second = (int(part) for part in found.groups()[:6])
    offset_hours, offset_minutes = int(found.group(9) or 0), int(found.group(10) or 0)
    leap = year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
    month_days = (31, 29 if leap else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)[month - 1] if 1 <= month <= 12 else 0
    if not month_days or not 1 <= day <= month_days or hour > 23 or minute > 59 or second > 59 or offset_hours > 23 or offset_minutes > 59:
        return None
    y = year - 1 if month <= 2 else year
    era = y // 400
    year_of_era = y - era * 400
    day_of_year = (153 * (month + (-3 if month > 2 else 9)) + 2) // 5 + day - 1
    days = era * 146097 + year_of_era * 365 + year_of_era // 4 - year_of_era // 100 + day_of_year - 719468
    offset = (-1 if found.group(8) == '-' else 1) * (offset_hours * 3600 + offset_minutes * 60)
    return days * 86400 + hour * 3600 + minute * 60 + second - offset + int((found.group(7) or '')[:3].ljust(3, '0')) / 1000


def _read_listing(key_id, doc):
    if not isinstance(doc, dict) or not isinstance(doc.get('id'), str) or not isinstance(doc.get('name'), str) or not isinstance(doc.get('isActive'), bool) or not isinstance(doc.get('keys'), list):
        return None
    for key in doc['keys']:
        if not isinstance(key, dict) or not isinstance(key.get('publicKey'), str) or not isinstance(key.get('jkt'), str) or not re.fullmatch(r'[A-Za-z0-9_-]{43}', key['jkt']) or key.get('agentId') != doc['id']:
            return None
        if key.get('status') != 'active' or key.get('algorithm') != 'ed25519':
            return None
        if key.get('expirationDate') is not None and _expiry_seconds(key['expirationDate']) is None:
            return None
    key = None if key_id is None else next((k for k in doc['keys'] if k.get('id') == key_id or k['jkt'] == key_id), None)
    if not key:
        return {'agent': doc}
    raw = _raw_key(key['publicKey'])
    if raw is None or _decompress(raw) is None:
        return None
    return {'agent': doc, 'key': key, 'raw': raw, 'algorithm': 'ed25519', 'thumbprint': _thumbprint(raw)}


class _NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, *args, **kwargs):
        return None


_OPENER = urllib.request.build_opener(_NoRedirect)


def http_get(url):
    try:
        with _OPENER.open(urllib.request.Request(url, headers={'accept': 'application/json'}), timeout=5) as response:
            return response.status, dict(response.headers), response.read()
    except urllib.error.HTTPError as error:
        return error.code, dict(error.headers or {}), error.read()


P256_ALGORITHMS = ('ecdsa-p256', 'ecdsa-p256-sha256', 'es256', 'p-256')


def _directory_key(algorithm, jwk):
    def coordinate(name):
        value = jwk.get(name)
        return base64.urlsafe_b64decode(value + '=') if isinstance(value, str) and re.fullmatch(r'[A-Za-z0-9_-]{43}', value) else None

    if not isinstance(jwk, dict) or not isinstance(algorithm, str):
        return None
    if algorithm in ('ed25519', 'Ed25519') and jwk.get('kty') == 'OKP' and jwk.get('crv') == 'Ed25519' and coordinate('x'):
        raw = coordinate('x')
        return ('ed25519', raw) if _decompress(raw) is not None else None
    if algorithm.lower() in P256_ALGORITHMS and jwk.get('kty') == 'EC' and jwk.get('crv') == 'P-256' and coordinate('x') and coordinate('y'):
        point = _p256_point(int.from_bytes(coordinate('x'), 'big'), int.from_bytes(coordinate('y'), 'big'))
        return ('ecdsa-p256-sha256', point) if point else None
    return None


def _read_directory_entry(key_id, doc):
    key = doc.get('key') if isinstance(doc, dict) else None
    agent = doc.get('agent') if isinstance(doc, dict) else None
    if not isinstance(agent, dict) or not isinstance(agent.get('name'), str) or not isinstance(key, dict) or not isinstance(key.get('id'), str) or key.get('status') != 'active':
        return None
    usable = _directory_key(key.get('algorithm'), key.get('publicKeyJwk'))
    if not usable:
        return None
    if key['id'] != key_id or (key.get('expirationDate') is not None and _expiry_seconds(key['expirationDate']) is None):
        return None
    algorithm, raw = usable
    computed = _thumbprint(raw)
    found_agent = {'id': None, 'name': agent['name'], 'isActive': True, 'tokenRequestorId': agent['tokenRequestorId'] if isinstance(agent.get('tokenRequestorId'), str) else None}
    return {'agent': found_agent, 'key': {'id': key['id'], 'jkt': computed, 'expirationDate': key.get('expirationDate')}, 'raw': raw, 'algorithm': algorithm, 'thumbprint': computed}


def _read_registry(url, parse, fetch):
    try:
        status, headers, body = fetch(url)
    except Exception:
        return {'unavailable': True, 'retryAfterSeconds': None}
    if status == 404:
        return {'notListed': True}
    if status != 200:
        retry = {name.lower(): value for name, value in headers.items()}.get('retry-after', '')
        return {'unavailable': True, 'retryAfterSeconds': int(retry) if re.fullmatch(r'[0-9]+', str(retry)) and int(retry) > 0 else None}
    try:
        listing = parse(json.loads(body))
    except Exception:
        return {'invalid': True}
    return {'listed': True, **listing} if listing else {'invalid': True}


def read_key(registry_origin, key_id, fetch=http_get):
    return _read_registry(f'{registry_origin_from(registry_origin)}/v1/tap/registry/keys/{urllib.parse.quote(key_id, safe="")}', lambda doc: _read_listing(key_id, doc), fetch)


def read_agent(registry_origin, agent_id, fetch=http_get):
    return _read_registry(f'{registry_origin_from(registry_origin)}/v1/tap/registry/agents/{urllib.parse.quote(agent_id, safe="")}', lambda doc: _read_listing(None, doc), fetch)


def read_directory_key(directory_origin, key_id, fetch=http_get):
    return _read_registry(f'{registry_origin_from(directory_origin)}/.well-known/jwks/keys/{urllib.parse.quote(key_id, safe="")}', lambda doc: _read_directory_entry(key_id, doc), fetch)


def judge_key(key_id, answer, accept_simulated=False, now=None):
    if answer.get('unavailable'):
        return refusal('registry_unavailable', answer['retryAfterSeconds'])
    if answer.get('invalid'):
        return refusal('listing_unusable')
    if answer.get('notListed'):
        return refusal('key_not_listed')
    if answer['agent'].get('simulated') is True and not accept_simulated:
        return refusal('simulated_listing')
    if not answer['agent']['isActive']:
        return refusal('agent_not_live')
    if not answer.get('key'):
        return refusal('key_not_live')
    computed = answer['thumbprint']
    if computed != key_id and (len(key_id) != 36 or answer['key'].get('id') != key_id or answer['key']['jkt'] != computed):
        return refusal('key_not_live')
    if answer['key'].get('expirationDate') is not None and _expiry_seconds(answer['key']['expirationDate']) <= (int(time.time()) if now is None else now):
        return refusal('key_not_live')
    return None


def memory_nonce_store(now=lambda: int(time.time())):
    seen = {}
    lock = threading.Lock()

    def reserve(nonce_id, expires):
        with lock:
            for key, until in list(seen.items()):
                if until <= now():
                    del seen[key]
            if nonce_id in seen:
                return False
            seen[nonce_id] = expires
            return True

    return reserve


def read_own_key(key_id, lookup_key):
    try:
        found = lookup_key(key_id)
    except Exception:
        return {'unavailable': True, 'retryAfterSeconds': None}
    if found is None:
        return {'notListed': True}
    if not isinstance(found, dict):
        return {'invalid': True}
    if found.get('unavailable') is True:
        return {'unavailable': True, 'retryAfterSeconds': None}
    usable = _directory_key(found.get('algorithm'), found.get('publicKeyJwk')) if isinstance(found.get('name'), str) else None
    if not usable:
        return {'invalid': True}
    algorithm, raw = usable
    computed = _thumbprint(raw)
    return {'listed': True, 'agent': {'id': None, 'name': found['name'], 'isActive': True, 'tokenRequestorId': None}, 'key': {'id': key_id, 'jkt': computed, 'expirationDate': None}, 'raw': raw, 'algorithm': algorithm, 'thumbprint': computed}


def create_verifier(registry_origin=None, reserve_nonce=None, allowed_signature_agents=('"https://sbx.agenticdirectory.visa.com"', '"https://agenticdirectory.visa.com"'), accept_simulated=False, now=lambda: int(time.time()), fetch=http_get, cache_seconds=60, extra_transport_headers=(), directory_origin=None, lookup_key=None):
    directory = registry_origin_from(directory_origin) if directory_origin and not lookup_key else None
    registry = None if directory or lookup_key else registry_origin_from(registry_origin)
    cache = {}
    transport_headers = TRANSPORT_HEADERS | {name.lower() for name in extra_transport_headers}

    def lookup(key_id, fresh=False):
        hit = cache.get(key_id)
        if not fresh and hit and hit[1] > now():
            return hit[0]
        answer = read_own_key(key_id, lookup_key) if lookup_key else read_directory_key(directory, key_id, fetch) if directory else read_key(registry, key_id, fetch)
        if answer.get('unavailable') or answer.get('invalid'):
            return answer
        cache.pop(key_id, None)
        if answer.get('listed') and answer['agent']['isActive'] and answer.get('key'):
            cache[key_id] = (answer, now() + cache_seconds)
        return answer

    def check(method, public_origin, target, headers, raw_body):
        signature_input = headers.get('signature-input')
        signature_header = headers.get('signature')
        if not signature_input or not signature_header:
            return refusal('no_signature_headers')
        parsed = INPUT.fullmatch(signature_input)
        if not parsed:
            return refusal('signature_input_format')
        signed = SIGNATURE.fullmatch(signature_header)
        if not signed:
            return refusal('signature_header_format')

        parts = parsed[1].split()
        if not all(re.fullmatch(r'"[^"]+"', part) for part in parts):
            return refusal('components_invalid')
        components = [part[1:-1].lower() for part in parts]
        if len(set(components)) != len(components):
            return refusal('components_invalid')

        created, expires, key_id, nonce = int(parsed[2]), int(parsed[3]), parsed[4], parsed[6]
        alg = 'ecdsa-p256-sha256' if parsed[5] == 'ecdsa-p256-sha256' else 'ed25519'
        if not str(public_origin).startswith('https://'):
            return refusal('origin_not_https')
        if not _origin_is_normal(public_origin):
            return refusal('origin_not_normal')
        split = _split_target(target)
        if not split:
            return refusal('request_target_invalid')
        authority = public_origin[len('https://'):]
        path, query = split
        if len(key_id) == 36:
            needed = (['@query'] if query else []) + [name for name in ('accept', 'content-type') if name in headers]
            if any(name not in components for name in needed):
                return refusal('directory_components_missing')

        t = now()
        if created > t + CLOCK_SKEW_SECONDS:
            return refusal('not_yet_valid')
        if expires <= t or expires <= created:
            return refusal('expired')
        if expires - created > MAX_LIFETIME_SECONDS:
            return refusal('lifetime_too_long')

        if components[:len(CORE)] != CORE:
            return refusal('required_components_missing')
        if method not in ('GET', 'HEAD', 'POST'):
            return refusal('method_not_allowed')
        if any(name in headers for name in CREDENTIALS):
            return refusal('credential_header_present')

        if len(components) > 38:
            return refusal('signed_header_invalid')
        previous, size = '', 0
        for name in components[len(CORE):]:
            value = headers.get(name)
            if not HEADER_NAME.fullmatch(name) or name <= previous or not isinstance(value, str) or value.strip() != value or len(value) > 4096 or re.search(r'[^\x20-\x7e]', value):
                return refusal('signed_header_invalid')
            if name in NEVER_SIGNED or NEVER_SIGNED_PREFIX.match(name):
                return refusal('signed_header_invalid')
            previous = name
            size += len(name) + len(value)
        if size > 16384:
            return refusal('signed_header_invalid')
        for name in headers:
            if name not in components and name not in transport_headers and not name.startswith('sec-fetch-'):
                return refusal('uncovered_header', None, name)
        if base64.b64encode(base64.b64decode(nonce)).decode() != nonce:
            return refusal('nonce_format')

        if len(raw_body) > MAX_BODY_BYTES:
            return refusal('body_too_large')
        if not DIGEST.fullmatch(headers.get('content-digest') or ''):
            return refusal('digest_format')
        digest = 'sha-256=:' + base64.b64encode(hashlib.sha256(raw_body).digest()).decode() + ':'
        if headers.get('content-digest') != digest:
            return refusal('body_digest_mismatch')

        signature_agent = headers.get('signature-agent')
        if signature_agent is not None and signature_agent not in allowed_signature_agents:
            return refusal('signature_agent_not_accepted')
        if directory and len(key_id) != 36:
            return refusal('key_not_in_directory')
        if directory and signature_agent is not None and signature_agent != f'"{directory}"':
            return refusal('signature_agent_other_directory')

        found = lookup(key_id)
        refused = judge_key(key_id, found, accept_simulated, now())
        if refused:
            return refused

        derived = {'@method': method, '@scheme': 'https', '@authority': authority, '@path': path, '@query': query or '?'}
        lines = [f'"{name}": {derived[name] if name.startswith("@") else headers[name]}' for name in components]
        lines.append(f'"@signature-params": {signature_input[len("sig2="):]}')
        base = '\n'.join(lines).encode()
        signature = base64.b64decode(signed[1])

        if found['algorithm'] != alg or not _signature_verifies(found, base, signature):
            found = lookup(key_id, fresh=True)
            refused = judge_key(key_id, found, accept_simulated, now())
            if refused:
                return refused
            if found['algorithm'] != alg:
                return refusal('algorithm_mismatch')
            if not _signature_verifies(found, base, signature):
                return refusal('signature_mismatch')

        try:
            reserved = reserve_nonce(f'{key_id}:{nonce}', expires)
        except Exception:
            return refusal('nonce_store_unavailable')
        if not reserved:
            return refusal('nonce_reused')

        return {'ok': True, 'keyId': key_id, 'jkt': found['key']['jkt'], 'agentId': found['agent']['id'], 'agentName': found['agent']['name'], 'simulated': found['agent'].get('simulated') is True, 'covered': components, 'expires': expires, **({'tokenRequestorId': found['agent']['tokenRequestorId']} if directory else {}), **({'selfKey': True} if lookup_key else {})}

    def verify_request(method, public_origin, target, headers, raw_body):
        try:
            return check(method, public_origin, target, headers, raw_body)
        except Exception:
            return refusal('request_unreadable')

    return verify_request
