#!/usr/bin/env python3 # MIT License. Copyright (c) 2026 neomorphic.io. Contact: contact@neomorphic.io """Block a coding agent when an x402 HTTP 402 breaks a Commons check. Stdlib only. On an HTTP 402 the script reads https://neomorphic.io/commons/units.json unless --units-file is set. It fails when Access-Control-Expose-Headers omits PAYMENT-REQUIRED or PAYMENT-RESPONSE, when resource.tags is over the cap or invalid, or when a header line reaches 8192 bytes. """ from __future__ import annotations import argparse import base64 import json import re import socket import sys import urllib.error import urllib.parse import urllib.request from pathlib import Path TOOL = "x402-hook" VERSION = "1.0" USER_AGENT = "x402-hook/1.0" UNITS_URL = "https://neomorphic.io/commons/units.json" HEADER_LIMIT = 8192 TAG_CAP = 5 CATALOG_MAX_BODY = 8_000_000 REQUIRED_EXPOSE = ("payment-required", "payment-response") SIGNATURES = { "cors": "x402/x402/cors-payment-headers-not-exposed", "header": "x402/x402-http/payment-required-header-too-large", } URL_RE = re.compile(r"https?://[^\s\"'<>]+") CONTACT = "contact@neomorphic.io" class CatalogError(Exception): def __init__(self, message: str, status: int | None = None) -> None: super().__init__(message) self.message = message self.status = status class _Redirects(urllib.request.HTTPRedirectHandler): max_redirections = 5 def unit_id(unit: dict | None) -> str | None: if not isinstance(unit, dict): return None ident = unit.get("id") return ident if isinstance(ident, str) and ident else None def fix_summary(unit: dict | None) -> str | None: if not isinstance(unit, dict): return None extensions = unit.get("extensions") if isinstance(unit.get("extensions"), dict) else {} fix = extensions.get("neomorphic:fix") if isinstance(extensions.get("neomorphic:fix"), dict) else {} summary = fix.get("summary") if isinstance(summary, str) and summary.strip(): return summary.strip() insight = unit.get("insight") if isinstance(unit.get("insight"), dict) else {} action = insight.get("action") if isinstance(action, str) and action.strip(): return action.strip().splitlines()[0].strip() return None def bind_units(units: list) -> dict: found = {"cors": None, "header": None} want = {signature: slot for slot, signature in SIGNATURES.items()} for unit in units: if not isinstance(unit, dict): continue extensions = unit.get("extensions") if not isinstance(extensions, dict): continue signature = extensions.get("neomorphic:signature") if not isinstance(signature, dict): continue slot = want.get(signature.get("key")) if slot and found[slot] is None: found[slot] = unit return found def _units_from_doc(doc: object, status: int | None) -> tuple[list, int | None]: if not isinstance(doc, dict) or not isinstance(doc.get("data"), list): raise CatalogError("units catalog data must be an array", status) return doc["data"], status def load_units_file(path: str) -> tuple[list, int | None]: try: text = Path(path).read_text(encoding="utf-8") doc = json.loads(text) except (OSError, UnicodeError, json.JSONDecodeError) as exc: raise CatalogError(f"units file could not be read ({exc})", None) from exc return _units_from_doc(doc, None) def load_units_url(url: str, timeout: float) -> tuple[list, int | None]: request = urllib.request.Request( url, headers={"Accept": "application/json", "User-Agent": USER_AGENT}, method="GET", ) try: with urllib.request.urlopen(request, timeout=timeout) as response: status = getattr(response, "status", None) or response.getcode() body = response.read(CATALOG_MAX_BODY + 1) except urllib.error.HTTPError as exc: raise CatalogError(f"units catalog returned HTTP {exc.code}", exc.code) from exc except (urllib.error.URLError, TimeoutError, socket.timeout) as exc: reason = getattr(exc, "reason", exc) raise CatalogError(f"units catalog request failed ({reason})", None) from exc if status != 200: raise CatalogError(f"units catalog returned HTTP {status}", status) if len(body) > CATALOG_MAX_BODY: raise CatalogError("units catalog exceeded the read limit", status) try: doc = json.loads(body.decode("utf-8")) except (UnicodeError, json.JSONDecodeError) as exc: raise CatalogError("units catalog body was not JSON", status) from exc return _units_from_doc(doc, status) def load_catalog(units_file: str | None, units_url: str, timeout: float) -> tuple[list, int | None, str]: if units_file: units, status = load_units_file(units_file) return units, status, "file" units, status = load_units_url(units_url, timeout) return units, status, "url" def header_map(pairs: list[tuple[str, str]]) -> dict[str, str]: grouped: dict[str, list[str]] = {} order: list[str] = [] for name, value in pairs: key = name.lower() if key not in grouped: order.append(key) grouped[key] = [] grouped[key].append(value) return {key: ", ".join(grouped[key]) for key in order} def decode_payment_required(value: str) -> object: raw = "".join(value.split()) if raw.startswith("{"): return json.loads(raw) padded = raw + ("=" * ((-len(raw)) % 4)) try: data = base64.b64decode(padded, validate=True) return json.loads(data.decode("utf-8")) except (ValueError, UnicodeError, json.JSONDecodeError) as exc: raise ValueError("unreadable") from exc def valid_tag(tag: str) -> bool: if not 1 <= len(tag) <= 32: return False return all(32 <= ord(char) <= 126 for char in tag) def check_tags(payment_header: str | None) -> tuple[str | None, int | None]: if payment_header is None: return None, None try: payload = decode_payment_required(payment_header) except ValueError: return "PAYMENT-REQUIRED did not decode, so resource.tags could not be counted.", None if not isinstance(payload, dict): return "PAYMENT-REQUIRED did not decode to an object, so resource.tags could not be counted.", None resource = payload.get("resource") if not isinstance(resource, dict) or "tags" not in resource: return None, 0 if isinstance(resource, dict) else None tags = resource.get("tags") if not isinstance(tags, list): return "resource.tags must be an array of strings.", None problems = [] if len(tags) > TAG_CAP: problems.append(f"resource.tags has {len(tags)} entries. The cap is {TAG_CAP}.") seen: set[str] = set() for index, tag in enumerate(tags): if not isinstance(tag, str) or not valid_tag(tag): problems.append(f"resource.tags[{index}] must be printable ASCII, 1 to 32 characters.") continue key = tag.lower() if key in seen: problems.append(f"resource.tags[{index}] repeats an earlier tag, ignoring case.") seen.add(key) if problems: return " ".join(problems), len(tags) return None, len(tags) def evaluate(status: int, pairs: list[tuple[str, str]], bound: dict) -> dict: lines = [f"{name}: {value}" for name, value in pairs] max_line = max((len(line.encode("utf-8")) for line in lines), default=0) headers = header_map(pairs) expose = headers.get("access-control-expose-headers", "") payment = headers.get("payment-required") base = { "max_header_line_bytes": max_line, "access_control_expose_headers": expose, "header_limit_bytes": HEADER_LIMIT, "tag_cap": TAG_CAP, "status": status, } if status != 402: return {**base, "outcome": "no_402", "failures": [], "tag_count": None} failures = [] names = [part.strip().lower() for part in expose.split(",") if part.strip()] if any(name not in names for name in REQUIRED_EXPOSE): unit = bound.get("cors") failures.append( { "rule": "cors-expose", "unit_id": unit_id(unit), "signature_key": SIGNATURES["cors"], "fix_summary": fix_summary(unit), "message": "Access-Control-Expose-Headers must name PAYMENT-REQUIRED and PAYMENT-RESPONSE.", } ) if max_line >= HEADER_LIMIT: unit = bound.get("header") failures.append( { "rule": "header-limit", "unit_id": unit_id(unit), "signature_key": SIGNATURES["header"], "fix_summary": fix_summary(unit), "message": f"A header line is {max_line} bytes. The limit is {HEADER_LIMIT} bytes.", } ) tag_message, tag_count = check_tags(payment) if tag_message: failures.append( { "rule": "tags", "unit_id": None, "signature_key": None, "fix_summary": None, "message": tag_message, } ) return { **base, "outcome": "fail" if failures else "pass", "failures": failures, "tag_count": tag_count, } def probe(url: str, timeout: float) -> tuple[int | None, list[tuple[str, str]], str | None, str | None]: parts = urllib.parse.urlsplit(url) if parts.scheme not in ("http", "https") or not parts.hostname or parts.username or parts.password: return None, [], "URL scheme must be http or https and include a host", None opener = urllib.request.build_opener(_Redirects) request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT, "Accept": "*/*"}, method="GET") try: with opener.open(request, timeout=timeout) as response: status = getattr(response, "status", None) or response.getcode() pairs = list(response.headers.items()) final_url = response.geturl() response.read(1024) return status, pairs, None, final_url except urllib.error.HTTPError as exc: pairs = list(exc.headers.items()) if exc.headers is not None else [] try: exc.read(1024) except Exception: pass return exc.code, pairs, None, exc.geturl() except (urllib.error.URLError, TimeoutError, socket.timeout) as exc: reason = getattr(exc, "reason", exc) return None, [], f"request failed ({reason})", None def load_fixture(path: str) -> tuple[str, int, list[tuple[str, str]]]: try: doc = json.loads(Path(path).read_text(encoding="utf-8")) except (OSError, UnicodeError, json.JSONDecodeError) as exc: raise ValueError(f"fixture could not be read ({exc})") from exc if not isinstance(doc, dict): raise ValueError("fixture must be a JSON object") status = doc.get("status") if not isinstance(status, int): raise ValueError("fixture status must be an integer") raw_headers = doc.get("headers") or {} pairs: list[tuple[str, str]] = [] if isinstance(raw_headers, dict): pairs = [(str(name), str(value)) for name, value in raw_headers.items()] elif isinstance(raw_headers, list): for item in raw_headers: if not isinstance(item, (list, tuple)) or len(item) != 2: raise ValueError("fixture header list entries must be name, value pairs") pairs.append((str(item[0]), str(item[1]))) else: raise ValueError("fixture headers must be an object or a list of pairs") url = doc.get("url") if isinstance(doc.get("url"), str) else "fixture://local" return url, status, pairs def extract_urls(event: object) -> list[str]: if not isinstance(event, dict): return [] blobs: list[str] = [] tool_input = event.get("tool_input") if isinstance(tool_input, str): blobs.append(tool_input) elif isinstance(tool_input, dict): for key in ("command", "url", "uri", "href"): value = tool_input.get(key) if isinstance(value, str): blobs.append(value) urls: list[str] = [] seen: set[str] = set() for blob in blobs: for match in URL_RE.findall(blob): url = match.rstrip(").,;]") parts = urllib.parse.urlsplit(url) if parts.scheme not in ("http", "https") or not parts.hostname or parts.username or parts.password: continue if url in seen: continue seen.add(url) urls.append(url) if len(urls) >= 5: return urls return urls def attach_catalog(report: dict, bound: dict, catalog_status: int | None, source: str, units_url: str) -> dict: report["units_url"] = units_url report["units_source"] = source report["catalog_http_status"] = catalog_status report["units"] = { "cors": unit_id(bound.get("cors")), "header": unit_id(bound.get("header")), "tags": None, } report["tool"] = TOOL report["version"] = VERSION return report def catalog_failure_report(url: str, status: int | None, error: CatalogError, units_url: str) -> dict: return { "tool": TOOL, "version": VERSION, "url": url, "final_url": url, "status": status, "outcome": "catalog_error", "exit_code": 2, "units_url": units_url, "units_source": "url", "catalog_http_status": error.status, "units": {"cors": None, "header": None, "tags": None}, "failures": [], "errors": [error.message], "header_limit_bytes": HEADER_LIMIT, "tag_cap": TAG_CAP, } def render_human(report: dict) -> str: lines = [f"x402-hook: {report.get('outcome')}", f"URL: {report.get('url') or ''}"] if report.get("status") is not None: lines.append(f"HTTP {report['status']}") for failure in report.get("failures") or []: unit = failure.get("unit_id") suffix = f" Unit {unit}." if unit else "" lines.append(f"{failure['rule']}: {failure['message']}{suffix}") for error in report.get("errors") or []: lines.append(error) if report.get("outcome") == "pass": lines.append("Access-Control-Expose-Headers names PAYMENT-REQUIRED and PAYMENT-RESPONSE.") if report.get("tag_count") is None: lines.append("resource.tags is absent on this response.") else: lines.append(f"resource.tags has {report['tag_count']} entries.") lines.append(f"Header lines stay under {HEADER_LIMIT} bytes.") cited = [item for item in (report.get("units") or {}).values() if item] if cited: lines.append("Commons units: " + ", ".join(cited)) lines.append(f"Contact: {CONTACT}") return "\n".join(lines) + "\n" def deny_reason(reports: list[dict]) -> str: parts: list[str] = [] for report in reports: for failure in report.get("failures") or []: unit = failure.get("unit_id") text = failure["message"] if unit: text = f"{text} Unit {unit}." parts.append(text) for error in report.get("errors") or []: parts.append(error) reason = " ".join(parts) or "The x402 paywall failed a Commons check." if len(reason) > 700: reason = reason[:697] + "..." return reason def render_deny(reports: list[dict]) -> dict: return { "hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": deny_reason(reports), } } def finish_checked(url: str, final_url: str | None, status: int, pairs: list, args, bound, catalog_status, source) -> dict: report = evaluate(status, pairs, bound) report["url"] = url report["final_url"] = final_url or url report["exit_code"] = 4 if report["outcome"] == "fail" else 0 report["errors"] = [] return attach_catalog(report, bound, catalog_status, source, args.units_url) def ensure_catalog(args): units, status, source = load_catalog(args.units_file, args.units_url, args.timeout) return bind_units(units), status, source def run_hook(args, urls: list[str]) -> int: denies = [] bound = None catalog_status = None source = "url" for url in urls: status, pairs, error, final_url = probe(url, args.timeout) if error or status is None or status != 402: continue if bound is None: try: bound, catalog_status, source = ensure_catalog(args) except CatalogError as exc: denies.append(catalog_failure_report(url, status, exc, args.units_url)) continue report = finish_checked(url, final_url, status, pairs, args, bound, catalog_status, source) if report["outcome"] == "fail": denies.append(report) if not denies: return 0 sys.stdout.write(json.dumps(render_deny(denies), indent=2) + "\n") return 0 def emit_cli(report: dict, json_mode: bool) -> int: payload = json.dumps(report, indent=2) + "\n" human = render_human(report) if json_mode: sys.stdout.write(payload) sys.stderr.write(human) else: sys.stdout.write(human) return int(report.get("exit_code") or 0) def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog=TOOL, description=( "Check an x402 HTTP 402 against the Commons catalog.\n" "\n" "The check is free and runs on your machine.\n" "Access-Control-Expose-Headers must name PAYMENT-REQUIRED and PAYMENT-RESPONSE.\n" "resource.tags holds at most 5 entries.\n" "Each header line stays under 8192 bytes.\n" "\n" f"Contact: {CONTACT}" ), formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument("url", nargs="?") parser.add_argument("--fixture", help="JSON response fixture. Skips the network probe") parser.add_argument("--units-file", help="local units.json. Skips the catalog request") parser.add_argument("--units-url", default=UNITS_URL, help=f"catalog URL (default {UNITS_URL})") parser.add_argument("--timeout", type=float, default=20, help="seconds for each connection (default 20)") parser.add_argument("--json", action="store_true", help="write JSON to stdout and the text report to stderr") parser.add_argument("--hook", action="store_true", help="Claude Code PreToolUse mode. JSON decision on stdout") parser.add_argument("--version", action="version", version=f"{TOOL} {VERSION}") return parser def main(argv: list[str] | None = None) -> int: if argv is None: argv = sys.argv[1:] parser = build_parser() try: args = parser.parse_args(argv) except SystemExit as exc: code = exc.code return 0 if code in (None, 0) else 1 if args.timeout <= 0: sys.stderr.write(f"{TOOL}: timeout must be greater than 0\n") return 1 if args.fixture and args.url: sys.stderr.write(f"{TOOL}: pass a URL or --fixture, not both\n") return 1 if args.hook and not args.fixture and not args.url: raw = sys.stdin.read() if not raw.strip(): return 0 try: event = json.loads(raw) except json.JSONDecodeError: return 0 return run_hook(args, extract_urls(event)) if args.fixture: try: url, status, pairs = load_fixture(args.fixture) except ValueError as exc: sys.stderr.write(f"{TOOL}: {exc}\n") return 1 final_url = url error = None elif args.url: url = args.url status, pairs, error, final_url = probe(url, args.timeout) else: sys.stderr.write(f"{TOOL}: a URL is required\n") return 1 if error or status is None: report = { "tool": TOOL, "version": VERSION, "url": url, "final_url": final_url, "status": status, "outcome": "network_error", "exit_code": 2, "units_url": args.units_url, "units_source": None, "catalog_http_status": None, "units": {"cors": None, "header": None, "tags": None}, "failures": [], "errors": [error or "request failed"], "header_limit_bytes": HEADER_LIMIT, "tag_cap": TAG_CAP, } if args.hook: return 0 return emit_cli(report, args.json) if status != 402: report = evaluate(status, pairs, {"cors": None, "header": None}) report.update( { "url": url, "final_url": final_url or url, "exit_code": 0, "errors": [], "units_url": args.units_url, "units_source": "skipped", "catalog_http_status": None, "units": {"cors": None, "header": None, "tags": None}, "tool": TOOL, "version": VERSION, } ) if args.hook: return 0 return emit_cli(report, args.json) try: bound, catalog_status, source = ensure_catalog(args) except CatalogError as exc: report = catalog_failure_report(url, status, exc, args.units_url) if args.hook: sys.stdout.write(json.dumps(render_deny([report]), indent=2) + "\n") return 0 return emit_cli(report, args.json) report = finish_checked(url, final_url, status, pairs, args, bound, catalog_status, source) if args.hook: if report["outcome"] == "fail": sys.stdout.write(json.dumps(render_deny([report]), indent=2) + "\n") return 0 return emit_cli(report, args.json) if __name__ == "__main__": sys.exit(main())