Skip to content

Universal SEO skill for Claude Code. 26 sub-skills + 19 sub-agents covering technical SEO, E-E-A-T, schema, GEO/AEO, agent readiness (Lighthouse Agentic Browsing, WebMCP, llms.txt), backlinks, local SEO, e-commerce, international SEO, Google APIs, and PDF/Excel reporting. 9 optional extensions for live SEO data.

fix: hostile input yields a finding, never a traceback or a leaked key

Agrici Daniel02fbc28d82a4
diff --git a/scripts/agentic_check.py b/scripts/agentic_check.py
index 3967853..009cdd4 100644
--- a/scripts/agentic_check.py
+++ b/scripts/agentic_check.py
@@ -64,7 +64,7 @@ from urllib.parse import urljoin, urlparse
_SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
if _SCRIPTS_DIR not in sys.path:
sys.path.insert(0, _SCRIPTS_DIR)
-from url_safety import URLSafetyError, safe_requests_get # noqa: E402
+from url_safety import URLSafetyError, decode_body, safe_requests_get # noqa: E402
CHECKED_ON = "2026-09-23"
MAX_BODY = 2_000_000
@@ -172,24 +172,8 @@ def fetch(url: str, *, headers: Optional[dict] = None, timeout: int = 15) -> dic
def _decode(body: bytes, content_type: str) -> str:
- """Decode with the declared charset, else UTF-8; drop a leading BOM.
-
- ``requests`` would assume ISO-8859-1 for text/* without a charset, which
- garbles UTF-8 robots.txt and llms.txt files, so the header is read here.
- """
- match = re.search(r"charset=[\"']?([\w.:-]+)", content_type, re.I)
- meta = re.search(rb"<meta[^>]+charset\s*=\s*[\"']?([\w.:-]+)", body[:4096], re.I)
- if match:
- encoding = match.group(1)
- elif meta:
- encoding = meta.group(1).decode("ascii", "ignore")
- else:
- encoding = "utf-8"
- try:
- text = body.decode(encoding, errors="replace")
- except LookupError:
- text = body.decode("utf-8", errors="replace")
- return text.lstrip("\ufeff")
+ """Decode streamed bytes with url_safety's shared rules (#314), minus any BOM."""
+ return decode_body(body, content_type).lstrip("\ufeff")
def _ctype(rec: dict) -> str:
@@ -649,8 +633,9 @@ def validate_ai_catalog(raw: str) -> dict:
errors, warnings = [], []
try:
data = json.loads(raw)
- except ValueError as exc:
- return {"errors": [f"malformed JSON: {exc}"], "warnings": [], "entries": 0}
+ except (ValueError, RecursionError) as exc: # RecursionError: absurdly deep nesting
+ return {"errors": [f"malformed JSON: {type(exc).__name__}: {str(exc)[:200]}"],
+ "warnings": [], "entries": 0}
if not isinstance(data, dict):
return {"errors": ["root must be a JSON object"], "warnings": [], "entries": 0}
spec = data.get("specVersion")
@@ -764,7 +749,7 @@ def audit_well_known(root: str) -> tuple[list, dict]:
row["valid_json"] = True
status = "pass" if want in ctype else "warn"
fix = None if status == "pass" else f"Serve with a content type containing '{want}'."
- except ValueError:
+ except (ValueError, RecursionError):
row["valid_json"] = False
status, fix = "fail", "Document is not valid JSON."
else:
diff --git a/scripts/keywordseverywhere_api.py b/scripts/keywordseverywhere_api.py
index cf6990e..675cc86 100644
--- a/scripts/keywordseverywhere_api.py
+++ b/scripts/keywordseverywhere_api.py
@@ -85,6 +85,24 @@ def get_rank(domains: list, api_key: str) -> dict:
Returns:
Standard response dict with rank data per domain.
"""
+ raw_key = api_key or ""
+ api_key = raw_key.strip()
+ if not api_key or any(ord(ch) < 33 for ch in api_key):
+ return {
+ "status": "error",
+ "data": None,
+ "error": "The configured Keywords Everywhere API key contains spaces or control "
+ "characters. Re-enter it with backlinks_auth.py --setup.",
+ "metadata": {"source": "keywordseverywhere"},
+ }
+
+ def _redact(text: object) -> str:
+ text = str(text)
+ for secret in {raw_key, api_key}:
+ if secret:
+ text = text.replace(secret, "<redacted>")
+ return text[:500]
+
headers = {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
payload = {"domains": domains, "include_history": False}
@@ -111,12 +129,12 @@ def get_rank(domains: list, api_key: str) -> dict:
try:
err_body = response.json()
err = err_body.get("error") if isinstance(err_body, dict) else None
- err_msg = (err.get("message") if isinstance(err, dict) else err) or f"HTTP {response.status_code}"
+ err_msg = (err.get("message") if isinstance(err, dict) else err) or "no error message"
except ValueError:
# Never echo an HTML error page; the status code says enough.
- err_msg = f"HTTP {response.status_code}"
+ err_msg = "no JSON error body"
# Never echo the key back through an upstream error body.
- err_msg = str(err_msg).replace(api_key, "<redacted>")[:500]
+ err_msg = _redact(err_msg)
return {
"status": "error",
"data": None,
@@ -140,7 +158,14 @@ def get_rank(domains: list, api_key: str) -> dict:
"error": f"HTTP {response.status_code}: response was not JSON",
"metadata": {"source": "keywordseverywhere"},
}
- results = body.get("results") or []
+ if not isinstance(body, dict) or not isinstance(body.get("results", []), list):
+ return {
+ "status": "error",
+ "data": None,
+ "error": "Unexpected response shape from the API (no results list).",
+ "metadata": {"source": "keywordseverywhere"},
+ }
+ results = [item for item in body.get("results") or [] if isinstance(item, dict)]
ranks = [
{
"domain": item.get("domain"),
@@ -183,7 +208,7 @@ def get_rank(domains: list, api_key: str) -> dict:
return {
"status": "error",
"data": None,
- "error": str(e),
+ "error": _redact(e),
"metadata": {"source": "keywordseverywhere"},
}
diff --git a/scripts/lighthouse_agentic.py b/scripts/lighthouse_agentic.py
index 90ec1d9..4b66cd5 100644
--- a/scripts/lighthouse_agentic.py
+++ b/scripts/lighthouse_agentic.py
@@ -118,7 +118,10 @@ def classify_audit(audit_ref: dict, audit: dict) -> str:
score = audit.get("score")
if mode == "error" or score is None:
return "fail"
- return "pass" if float(score) >= PASS_MIN_SCORE else "fail"
+ try:
+ return "pass" if float(score) >= PASS_MIN_SCORE else "fail"
+ except (TypeError, ValueError):
+ return "fail"
def calculate_fraction(lhr: dict) -> dict:
@@ -298,10 +301,20 @@ def summarize(lhr: dict, source: str) -> dict:
def extract_lhr(data: dict) -> dict:
- """Accept either a raw Lighthouse result or a PSI v5 response."""
- if "lighthouseResult" in data:
- return data["lighthouseResult"]
- return data
+ """Accept either a raw Lighthouse result or a PSI v5 response.
+
+ Anything malformed (a null lighthouseResult, non-object audits) is reduced
+ to what can be read, so callers report "no category" instead of crashing.
+ """
+ lhr = data.get("lighthouseResult", data) if isinstance(data, dict) else {}
+ if not isinstance(lhr, dict):
+ return {}
+ audits = lhr.get("audits")
+ categories = lhr.get("categories")
+ return {**lhr,
+ "audits": {k: v for k, v in (audits or {}).items() if isinstance(v, dict)}
+ if isinstance(audits, dict) else {},
+ "categories": categories if isinstance(categories, dict) else {}}
def run_psi(url: str, strategy: str, api_key: Optional[str], timeout: int = 180) -> dict:
@@ -365,7 +378,7 @@ def main() -> None:
reports = []
if args.from_json:
try:
- with open(args.from_json, encoding="utf-8") as fh:
+ with open(args.from_json, encoding="utf-8-sig") as fh: # PowerShell writes a BOM
data = json.load(fh)
except (OSError, ValueError) as exc:
parser.exit(1, f"Could not read {args.from_json}: {exc}\n")
diff --git a/scripts/ucp_check.py b/scripts/ucp_check.py
index 9b358e7..e386dd3 100644
--- a/scripts/ucp_check.py
+++ b/scripts/ucp_check.py
@@ -100,6 +100,9 @@ def parse_profile(payload: str) -> dict:
except json.JSONDecodeError as exc:
report["issues"].append(f"invalid-json: {exc.msg} (line {exc.lineno})")
return report
+ except RecursionError:
+ report["issues"].append("invalid-json: nesting too deep")
+ return report
if not isinstance(data, dict):
report["issues"].append("profile-not-object")
return report
@@ -141,7 +144,11 @@ def parse_profile(payload: str) -> dict:
entry["issues"].append("unknown-transport")
if not variant.get("version"):
entry["issues"].append("missing-version")
- if variant.get("transport") in ("rest", "mcp", "a2a") and not variant.get("endpoint"):
+ endpoint = variant.get("endpoint")
+ if endpoint is not None and not isinstance(endpoint, str):
+ entry["issues"].append("endpoint-not-a-string")
+ entry["endpoint"] = None
+ elif variant.get("transport") in ("rest", "mcp", "a2a") and not endpoint:
entry["issues"].append("missing-endpoint")
report["services"].append(entry)
@@ -225,7 +232,7 @@ def audit_site(
if probe_endpoints:
for endpoint in sorted({svc["endpoint"] for svc in parsed.get("services") or []
- if svc.get("endpoint")}):
+ if isinstance(svc.get("endpoint"), str) and svc["endpoint"]}):
report["endpoint_probes"].append(probe_endpoint(endpoint, timeout=timeout))
n_caps = len({cap["id"] for cap in parsed.get("capabilities") or []})
diff --git a/scripts/url_safety.py b/scripts/url_safety.py
index f01c127..545dabe 100644
--- a/scripts/url_safety.py
+++ b/scripts/url_safety.py
@@ -820,12 +820,20 @@ def decode_response_text(response) -> str:
pages (issue #314). Reading ``response.content`` consumes a streamed body,
so streamed callers should decode the bytes they already read.
"""
- raw = response.content or b""
+ content_type = response.headers.get("Content-Type", "") if response.headers else ""
+ return decode_body(response.content or b"", content_type)
+
+
+def decode_body(raw: bytes, content_type: str = "") -> str:
+ """Decode already-read bytes with the same rules as ``decode_response_text``.
+
+ For streamed responses, whose ``.content`` must not be read again.
+ """
+ raw = raw or b""
for marker, encoding in _BOMS:
if raw.startswith(marker):
- return _decode_bytes(raw, encoding)
+ return _decode_bytes(raw[len(marker):], encoding.replace("-sig", ""))
- content_type = response.headers.get("Content-Type", "") if response.headers else ""
charset = _extract_charset_from_content_type(content_type)
if charset:
return _decode_bytes(raw, charset)
diff --git a/tests/test_agentic.py b/tests/test_agentic.py
index a783011..29037d7 100644
--- a/tests/test_agentic.py
+++ b/tests/test_agentic.py
@@ -91,7 +91,8 @@ def test_paths_offer_form_annotation_and_catalog(lhr):
def test_psi_wrapper_and_missing_category(lhr):
- assert la.extract_lhr({"lighthouseResult": lhr}) is lhr
+ assert la.extract_lhr({"lighthouseResult": lhr}) == la.extract_lhr(lhr)
+ assert la.calculate_fraction(la.extract_lhr({"lighthouseResult": lhr}))["display"] == "4/4"
report = la.summarize({"categories": {}, "audits": {}}, "file")
assert report["error"] and not report["fraction"]["available"]
diff --git a/tests/test_hostile_inputs.py b/tests/test_hostile_inputs.py
new file mode 100644
index 0000000..1ed4ba2
--- /dev/null
+++ b/tests/test_hostile_inputs.py
@@ -0,0 +1,109 @@
+"""Hostile or malformed input must yield a finding, never a traceback (audit 2026-09-23).
+
+Each case was reproduced by the post-release code audit against the scripts
+added or changed on the v2.4.0 branch.
+"""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+ROOT = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(ROOT / "scripts"))
+
+pytest.importorskip("requests")
+pytest.importorskip("bs4")
+import agentic_check as ac # noqa: E402
+import keywordseverywhere_api as ke # noqa: E402
+import lighthouse_agentic as la # noqa: E402
+import ucp_check # noqa: E402
+
+DEEP = "[" * 100000 + "]" * 100000
+
+
+def _rec(status, text="", headers=None):
+ return {"url": "u", "status": status, "headers": headers or {}, "text": text,
+ "final_url": "https://e.test/", "error": None}
+
+
+def test_deeply_nested_catalog_is_a_finding_not_a_crash():
+ result = ac.validate_ai_catalog(DEEP)
+ assert result["errors"]
+
+
+def test_deeply_nested_well_known_document_is_a_finding(monkeypatch):
+ monkeypatch.setattr(ac, "fetch", lambda url, headers=None: _rec(200, DEEP, {"content-type": "application/json"}))
+ checks, _ = ac.audit_well_known("https://e.test")
+ assert all(c["status"] == "fail" for c in checks)
+
+
+def test_ucp_profile_hostile_shapes_do_not_crash():
+ assert ucp_check.parse_profile(DEEP)["issues"]
+ profile = {"ucp": {"version": "2026-08-25", "services": {"dev.ucp.shopping": [
+ {"version": "2026-08-25", "transport": "rest", "endpoint": {"url": "x"}},
+ {"version": "2026-08-25", "transport": "rest", "endpoint": "https://e.test/api"}]},
+ "capabilities": {"dev.ucp.shopping.cart": [{"version": "v", "spec": "s", "schema": "s"}]}}}
+ parsed = ucp_check.parse_profile(json.dumps(profile))
+ assert "endpoint-not-a-string" in parsed["services"][0]["issues"]
+ with patch.object(ucp_check, "safe_requests_get") as get, \
+ patch.object(ucp_check, "validate_url_strict", return_value=("https://e.test/.well-known/ucp", "1.2.3.4")), \
+ patch.object(ucp_check, "probe_endpoint", return_value={"url": "p"}):
+ get.return_value.status_code = 200
+ get.return_value.content = json.dumps(profile).encode()
+ get.return_value.headers = {"Content-Type": "application/json"}
+ report = ucp_check.audit_site("https://e.test", probe_endpoints=True)
+ assert report["profile_present"]
+
+
+class _Resp:
+ def __init__(self, status, body):
+ self.status_code, self._body, self.text = status, body, ""
+
+ def json(self):
+ return self._body
+
+
[email protected]("body", [[1, 2], {"results": [1, "x", None]}, {"results": "nope"}])
+def test_keywordseverywhere_odd_success_bodies(body):
+ with patch.object(ke, "_post", return_value=_Resp(200, body)):
+ result = ke.get_rank(["example.com"], "opr_live_testkey")
+ assert result["status"] in ("error", "success")
+ assert "Traceback" not in json.dumps(result)
+
+
+def test_keywordseverywhere_never_echoes_a_malformed_key():
+ result = ke.get_rank(["example.com"], "SECRETKEY123\n")
+ assert "SECRETKEY123" not in json.dumps(result)
+
+
+ {"lighthouseResult": None},
+ {"categories": {"agentic-browsing": {"auditRefs": [{"id": "x"}]}}, "audits": {"x": "not-a-dict"}},
+ {"categories": {"agentic-browsing": {"auditRefs": [{"id": "x"}]}},
+ "audits": {"x": {"scoreDisplayMode": "binary", "score": "high"}}},
+])
+def test_lighthouse_reader_survives_malformed_results(data):
+ report = la.summarize(la.extract_lhr(data), "file")
+ assert isinstance(report, dict)
+
+
+def test_lighthouse_reader_accepts_a_bom_file(tmp_path, monkeypatch, capsys):
+ fixture = (ROOT / "tests/fixtures/lighthouse_agentic_13_5_psi.json").read_text(encoding="utf-8")
+ path = tmp_path / "report.json"
+ path.write_text("" + fixture, encoding="utf-8")
+ monkeypatch.setattr(sys, "argv", ["lighthouse_agentic.py", "--from-json", str(path), "--json"])
+ with pytest.raises(SystemExit) as exc:
+ la.main()
+ assert exc.value.code == 0
+ assert json.loads(capsys.readouterr().out)["fraction"]["display"] == "4/4"
+
+
+def test_agentic_decoder_matches_the_shared_decoder_on_utf16():
+ body = "Café".encode("utf-16-le")
+ body = b"\xff\xfe" + body[2:]
+ assert ac._decode(body, "text/html") == "Café"
diff --git a/tests/test_keywordseverywhere_api.py b/tests/test_keywordseverywhere_api.py
index 9421dc4..a49c360 100644
--- a/tests/test_keywordseverywhere_api.py
+++ b/tests/test_keywordseverywhere_api.py
@@ -109,7 +109,7 @@ def test_get_rank_html_error_page_is_not_echoed() -> None:
fake.text = "<html>opr_live_testkey not found</html>"
with patch.object(keywordseverywhere_api, "_post", return_value=fake):
result = keywordseverywhere_api.get_rank(["example.com"], "opr_live_testkey")
- assert result["error"] == "HTTP 404: HTTP 404"
+ assert result["error"] == "HTTP 404: no JSON error body"
assert "opr_live_testkey" not in result["error"]