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(security): harden URL and Google API key handling
Daniel373746826904
diff --git a/scripts/crux_history.py b/scripts/crux_history.pyindex 0f41454..2dfab2a 100644--- a/scripts/crux_history.py+++ b/scripts/crux_history.py@@ -24,11 +24,21 @@ except ImportError:sys.exit(1)try:- from google_auth import get_api_key, validate_url+ from google_auth import (+ get_api_key,+ google_api_key_headers,+ redact_google_api_key,+ validate_url,+ )except ImportError:import ossys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))- from google_auth import get_api_key, validate_url+ from google_auth import (+ get_api_key,+ google_api_key_headers,+ redact_google_api_key,+ validate_url,+ )CRUX_HISTORY_ENDPOINT = "https://chromeuxreport.googleapis.com/v1/records:queryHistoryRecord"@@ -84,7 +94,8 @@ def query_history(try:resp = requests.post(- f"{CRUX_HISTORY_ENDPOINT}?key={api_key}",+ CRUX_HISTORY_ENDPOINT,+ headers=google_api_key_headers(api_key),json=body,timeout=30,)@@ -104,7 +115,7 @@ def query_history(resp.raise_for_status()data = resp.json()except requests.exceptions.RequestException as e:- result["error"] = f"CrUX History API request failed: {e}"+ result["error"] = f"CrUX History API request failed: {redact_google_api_key(e)}"return resultrecord = data.get("record", {})diff --git a/scripts/google_auth.py b/scripts/google_auth.pyindex bb5e695..cc63223 100644--- a/scripts/google_auth.py+++ b/scripts/google_auth.py@@ -18,6 +18,7 @@ Usage:import argparseimport jsonimport os+import reimport sysimport timefrom typing import Optional@@ -60,6 +61,32 @@ SERVICE_NAMES = {"ga4": "GA4 Data API v1beta",}+_GOOGLE_API_KEY_RE = re.compile(r"AIza[0-9A-Za-z_-]+")+_GOOGLE_KEY_QUERY_RE = re.compile(r"([?&])key=[^&\s'\"<>)]*(&?)")+_GOOGLE_KEY_BARE_RE = re.compile(r"\bkey=[^&\s'\"<>)]*")+++def google_api_key_headers(api_key: str) -> dict:+ """Return the canonical header form for Google API key auth."""+ return {"X-Goog-Api-Key": api_key}+++def redact_google_api_key(value: object) -> str:+ """Remove Google API keys from exception/output strings."""+ text = str(value)+ def drop_query_key(match: re.Match) -> str:+ separator, trailing_amp = match.groups()+ if separator == "?" and trailing_amp:+ return "?"+ if separator == "&" and trailing_amp:+ return "&"+ return ""++ text = _GOOGLE_KEY_QUERY_RE.sub(drop_query_key, text)+ text = text.replace("?&", "?")+ text = _GOOGLE_KEY_BARE_RE.sub("google_api_key_redacted", text)+ return _GOOGLE_API_KEY_RE.sub("GOOGLE_API_KEY_REDACTED", text)+def load_config() -> dict:"""diff --git a/scripts/lcp_subparts.py b/scripts/lcp_subparts.pyindex 57e1146..bc90fd0 100644--- a/scripts/lcp_subparts.py+++ b/scripts/lcp_subparts.py@@ -36,7 +36,7 @@ _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, validate_url_strict # noqa: E402-from google_auth import get_api_key # noqa: E402+from google_auth import get_api_key, google_api_key_headers, redact_google_api_key # noqa: E402CRUX_ENDPOINT = "https://chromeuxreport.googleapis.com/v1/records:queryRecord"@@ -57,20 +57,24 @@ def _query_crux(url: str, form_factor: str, api_key: str) -> dict:"metrics": _LCP_SUBPART_METRICS + ["largest_contentful_paint"],}body = json.dumps(payload).encode("utf-8")+ headers = {"Content-Type": "application/json", **google_api_key_headers(api_key)}request = urllib.request.Request(- f"{CRUX_ENDPOINT}?key={api_key}",+ CRUX_ENDPOINT,data=body,- headers={"Content-Type": "application/json"},+ headers=headers,)try:with urllib.request.urlopen(request, timeout=30) as resp:return json.loads(resp.read().decode("utf-8"))except urllib.error.HTTPError as exc:return {- "error": f"CrUX HTTP {exc.code}: {exc.read().decode('utf-8', 'replace')}"+ "error": (+ f"CrUX HTTP {exc.code}: "+ f"{redact_google_api_key(exc.read().decode('utf-8', 'replace'))}"+ )}except urllib.error.URLError as exc:- return {"error": f"CrUX request failed: {exc.reason}"}+ return {"error": f"CrUX request failed: {redact_google_api_key(exc.reason)}"}def _percentile(metric: dict) -> float | None:diff --git a/scripts/nlp_analyze.py b/scripts/nlp_analyze.pyindex 20756bb..fa4b85b 100644--- a/scripts/nlp_analyze.py+++ b/scripts/nlp_analyze.py@@ -23,11 +23,23 @@ except ImportError:sys.exit(1)try:- from google_auth import get_api_key, validate_url+ from google_auth import (+ get_api_key,+ google_api_key_headers,+ redact_google_api_key,+ validate_url,+ )+ from url_safety import URLSafetyError, safe_requests_getexcept ImportError:import ossys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))- from google_auth import get_api_key, validate_url+ from google_auth import (+ get_api_key,+ google_api_key_headers,+ redact_google_api_key,+ validate_url,+ )+ from url_safety import URLSafetyError, safe_requests_getNLP_ENDPOINT = "https://language.googleapis.com/v2/documents:annotateText"@@ -97,7 +109,8 @@ def analyze_text(try:resp = requests.post(- f"{NLP_ENDPOINT}?key={key}",+ NLP_ENDPOINT,+ headers=google_api_key_headers(key),json=body,timeout=30,)@@ -117,7 +130,7 @@ def analyze_text(resp.raise_for_status()data = resp.json()except requests.exceptions.RequestException as e:- result["error"] = f"NLP API request failed: {e}"+ result["error"] = f"NLP API request failed: {redact_google_api_key(e)}"return result# Entities@@ -207,13 +220,17 @@ def analyze_url(# Fetch the page texttry:- resp = requests.get(url, timeout=30, headers={- "User-Agent": "Mozilla/5.0 (compatible; ClaudeSEO/1.7 NLP Analyzer)"- })+ resp = safe_requests_get(+ url,+ timeout=30,+ headers={"User-Agent": "Mozilla/5.0 (compatible; ClaudeSEO/1.7 NLP Analyzer)"},+ )resp.raise_for_status()html = resp.text+ except URLSafetyError as e:+ return {"error": f"URL blocked by SSRF protection: {e}"}except requests.exceptions.RequestException as e:- return {"error": f"Could not fetch URL: {e}"}+ return {"error": f"Could not fetch URL: {redact_google_api_key(e)}"}# Extract text from HTML (simple approach)try:diff --git a/scripts/pagespeed_check.py b/scripts/pagespeed_check.pyindex f3a2adf..70ce520 100644--- a/scripts/pagespeed_check.py+++ b/scripts/pagespeed_check.py@@ -26,12 +26,24 @@ except ImportError:# Import credential helper (same directory)try:- from google_auth import get_api_key, load_config, validate_url+ from google_auth import (+ get_api_key,+ google_api_key_headers,+ load_config,+ redact_google_api_key,+ validate_url,+ )except ImportError:# Fallback: try relative import from scripts/import ossys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))- from google_auth import get_api_key, load_config, validate_url+ from google_auth import (+ get_api_key,+ google_api_key_headers,+ load_config,+ redact_google_api_key,+ validate_url,+ )PSI_ENDPOINT = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed"CRUX_ENDPOINT = "https://chromeuxreport.googleapis.com/v1/records:queryRecord"@@ -119,11 +131,10 @@ def run_pagespeed(if isinstance(params["category"], list):params["category"].append(cat)- if api_key:- params["key"] = api_key+ headers = google_api_key_headers(api_key) if api_key else Nonetry:- resp = requests.get(PSI_ENDPOINT, params=params, timeout=120)+ resp = requests.get(PSI_ENDPOINT, params=params, headers=headers, timeout=120)resp.raise_for_status()data = resp.json()except requests.exceptions.Timeout:@@ -133,12 +144,12 @@ def run_pagespeed(if resp.status_code == 429:result["error"] = "PSI rate limit exceeded (240 QPM / 25,000 QPD). Wait and retry."elif resp.status_code == 400:- result["error"] = f"Invalid URL or parameters: {resp.text}"+ result["error"] = f"Invalid URL or parameters: {redact_google_api_key(resp.text)}"else:- result["error"] = f"PSI API error {resp.status_code}: {e}"+ result["error"] = f"PSI API error {resp.status_code}: {redact_google_api_key(e)}"return resultexcept requests.exceptions.RequestException as e:- result["error"] = f"Request failed: {e}"+ result["error"] = f"Request failed: {redact_google_api_key(e)}"return resultresult["analysis_timestamp"] = data.get("analysisUTCTimestamp")@@ -341,7 +352,8 @@ def query_crux(try:resp = requests.post(- f"{CRUX_ENDPOINT}?key={api_key}",+ CRUX_ENDPOINT,+ headers=google_api_key_headers(api_key),json=body,timeout=30,)@@ -361,7 +373,7 @@ def query_crux(resp.raise_for_status()data = resp.json()except requests.exceptions.RequestException as e:- result["error"] = f"CrUX API request failed: {e}"+ result["error"] = f"CrUX API request failed: {redact_google_api_key(e)}"return resultrecord = data.get("record", {})diff --git a/scripts/url_safety.py b/scripts/url_safety.pyindex 73bef2d..8fd0d55 100644--- a/scripts/url_safety.py+++ b/scripts/url_safety.py@@ -31,6 +31,10 @@ safe_requests_get(url, *, timeout=30, **kwargs) -> requests.Responseheader and TLS SNI; only the connect() target is forced to the pinnedaddress.+safe_requests_head(url, *, timeout=30, **kwargs) -> requests.Response+ Same protection as ``safe_requests_get`` for callers that only need a+ HEAD preflight.+safe_requests_session(url) -> context manager yielding requests.SessionSame protection as ``safe_requests_get`` for callers that need asession (cookies, redirect chains, multiple requests to one host).@@ -92,6 +96,7 @@ __all__ = ["validate_url","validate_url_strict","safe_requests_get",+ "safe_requests_head","safe_requests_session","make_safe_playwright_route_handler",]@@ -147,6 +152,32 @@ class URLSafetyError(ValueError):"""Raised when a URL fails SSRF safety checks."""+def _raw_authority(url: str) -> str:+ """Return the undecoded authority substring between scheme and path."""+ match = re.match(r"^[A-Za-z][A-Za-z0-9+.-]*://([^/?#]*)", url)+ return match.group(1) if match else ""+++def _reject_authority_confusion(url: str, parsed) -> None:+ """Reject forms where URL parsers or HTTP stacks can disagree.++ Backslashes, userinfo, and fragment/userinfo ambiguity have all been+ used to make one parser see a public host while another connects to a+ private host. claude-seo never needs credentials in audit URLs, so+ userinfo is refused outright.+ """+ authority = _raw_authority(url)+ authority_lower = authority.lower()+ url_lower = url.lower()++ if "\\" in authority or "%5c" in authority_lower:+ raise URLSafetyError("URL authority contains a backslash")+ if parsed.username is not None or parsed.password is not None or "@" in authority:+ raise URLSafetyError("URL userinfo is not allowed")+ if "#@" in url or "%23@" in url_lower:+ raise URLSafetyError("URL fragment/userinfo confusion refused")++def is_safe_ip(ip_str: str) -> bool:"""Return True iff ``ip_str`` is a public unicast address.@@ -231,12 +262,13 @@ def validate_url(url: str) -> bool:caller will open a socket — only the strict form catches a DNSrecord that resolves to a non-public IP at connect time."""- parsed = urlparse(url)- if parsed.scheme not in ("http", "https"):- return False- if not parsed.hostname:- return Falsetry:+ parsed = urlparse(url)+ _reject_authority_confusion(url, parsed)+ if parsed.scheme not in ("http", "https"):+ return False+ if not parsed.hostname:+ return Falsehostname = normalize_hostname(parsed.hostname)except URLSafetyError:return False@@ -264,6 +296,7 @@ def validate_url_strict(url: str) -> tuple[str, str]:attacker cannot race the resolver between validate and connect."""parsed = urlparse(url)+ _reject_authority_confusion(url, parsed)if parsed.scheme not in ("http", "https"):raise URLSafetyError(f"Invalid URL scheme: {parsed.scheme!r}")if not parsed.hostname:@@ -409,6 +442,26 @@ def safe_requests_get(return requests.get(norm_url, timeout=timeout, **kwargs)+def safe_requests_head(+ url: str,+ *,+ timeout: int = 30,+ **kwargs,+) -> requests.Response:+ """+ ``requests.head`` with DNS-rebinding protection.++ The request's hostname is pinned to a pre-validated IP for the+ duration of the call. Standard ``requests`` semantics otherwise.+ """+ norm_url, pinned_ip = validate_url_strict(url)+ parsed = urlparse(norm_url)+ port = parsed.port or (443 if parsed.scheme == "https" else 80)+ assert parsed.hostname is not None+ with _pin_dns(parsed.hostname, pinned_ip, port):+ return requests.head(norm_url, timeout=timeout, **kwargs)++@contextmanagerdef safe_requests_session(url: str) -> Iterator[requests.Session]:"""diff --git a/scripts/verify_backlinks.py b/scripts/verify_backlinks.pyindex 9603795..8e34a26 100644--- a/scripts/verify_backlinks.py+++ b/scripts/verify_backlinks.py@@ -32,6 +32,7 @@ try:from fetch_page import fetch_pagefrom parse_html import parse_htmlfrom google_auth import validate_url+ from url_safety import URLSafetyError, safe_requests_headexcept ImportError as e:print(f"Error: Required scripts not found in scripts/: {e}", file=sys.stderr)sys.exit(1)@@ -59,7 +60,7 @@ def _head_check(url: str, timeout: int = 15) -> dict:Dict with status_code, exists (bool), redirect_url (if redirected)."""try:- resp = requests.head(+ resp = safe_requests_head(url,timeout=timeout,allow_redirects=True,@@ -71,6 +72,13 @@ def _head_check(url: str, timeout: int = 15) -> dict:"redirect_url": str(resp.url) if str(resp.url) != url else None,"error": None,}+ except URLSafetyError as e:+ return {+ "status_code": None,+ "exists": False,+ "redirect_url": None,+ "error": f"blocked by SSRF protection: {e}",+ }except requests.exceptions.Timeout:return {"status_code": None, "exists": False, "redirect_url": None, "error": "timeout"}except requests.exceptions.RequestException as e:diff --git a/tests/test_google_api_key_safety.py b/tests/test_google_api_key_safety.pynew file mode 100644index 0000000..72a3191--- /dev/null+++ b/tests/test_google_api_key_safety.py@@ -0,0 +1,143 @@+"""Regression tests for Google API key handling.++These tests ensure API keys are passed in headers, not URLs, and that+exception text cannot leak bearer credentials into CLI output.+"""++from __future__ import annotations++import json+import os+import sys+from types import SimpleNamespace+from unittest.mock import patch++import requests++_SCRIPTS = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "scripts")+if _SCRIPTS not in sys.path:+ sys.path.insert(0, _SCRIPTS)++import crux_history # noqa: E402+import google_auth # noqa: E402+import lcp_subparts # noqa: E402+import nlp_analyze # noqa: E402+import pagespeed_check # noqa: E402+++SECRET = "AIzaSyDUMMYSECRET"+++class _ErrorResponse:+ def __init__(self, url: str, status_code: int = 500, text: str = "boom") -> None:+ self.url = url+ self.status_code = status_code+ self.text = text++ def raise_for_status(self) -> None:+ raise requests.exceptions.HTTPError(+ f"{self.status_code} Server Error for url: {self.url}?key={SECRET}"+ )++ def json(self) -> dict:+ return {}+++def _dump(result: dict) -> str:+ return json.dumps(result, sort_keys=True, default=str)+++def test_redact_google_api_key_scrubs_query_params_and_key_literals() -> None:+ leaked = f"https://example.test/path?foo=1&key={SECRET} failed with {SECRET}"+ redacted = google_auth.redact_google_api_key(leaked)+ assert SECRET not in redacted+ assert "key=" not in redacted+ assert "AIza" not in redacted+++def test_pagespeed_uses_header_and_redacts_errors() -> None:+ captured: dict = {}++ def fake_get(url: str, **kwargs):+ captured.update({"url": url, **kwargs})+ return _ErrorResponse(url)++ with patch.object(pagespeed_check.requests, "get", side_effect=fake_get):+ result = pagespeed_check.run_pagespeed(+ "https://example.com/", strategy="mobile", api_key=SECRET+ )++ assert captured["url"] == pagespeed_check.PSI_ENDPOINT+ assert captured["headers"]["X-Goog-Api-Key"] == SECRET+ assert "key" not in captured["params"]+ assert SECRET not in _dump(result)+ assert "key=" not in _dump(result)+++def test_crux_uses_header_and_redacts_errors() -> None:+ captured: dict = {}++ def fake_post(url: str, **kwargs):+ captured.update({"url": url, **kwargs})+ return _ErrorResponse(url)++ with patch.object(pagespeed_check.requests, "post", side_effect=fake_post):+ result = pagespeed_check.query_crux("https://example.com/", SECRET)++ assert captured["url"] == pagespeed_check.CRUX_ENDPOINT+ assert captured["headers"]["X-Goog-Api-Key"] == SECRET+ assert SECRET not in _dump(result)+ assert "key=" not in _dump(result)+++def test_crux_history_uses_header_and_redacts_errors() -> None:+ captured: dict = {}++ def fake_post(url: str, **kwargs):+ captured.update({"url": url, **kwargs})+ return _ErrorResponse(url)++ with patch.object(crux_history.requests, "post", side_effect=fake_post):+ result = crux_history.query_history("https://example.com/", SECRET)++ assert captured["url"] == crux_history.CRUX_HISTORY_ENDPOINT+ assert captured["headers"]["X-Goog-Api-Key"] == SECRET+ assert SECRET not in _dump(result)+ assert "key=" not in _dump(result)+++def test_nlp_uses_header_and_redacts_errors() -> None:+ captured: dict = {}++ def fake_post(url: str, **kwargs):+ captured.update({"url": url, **kwargs})+ return _ErrorResponse(url)++ with patch.object(nlp_analyze.requests, "post", side_effect=fake_post):+ result = nlp_analyze.analyze_text("Kenya has marathon runners.", api_key=SECRET)++ assert captured["url"] == nlp_analyze.NLP_ENDPOINT+ assert captured["headers"]["X-Goog-Api-Key"] == SECRET+ assert SECRET not in _dump(result)+ assert "key=" not in _dump(result)+++def test_lcp_subparts_uses_header_not_query_key() -> None:+ captured: dict = {}++ def fake_request(url: str, **kwargs):+ captured.update({"url": url, **kwargs})+ return SimpleNamespace()++ with patch.object(lcp_subparts.urllib.request, "Request", side_effect=fake_request), \+ patch.object(+ lcp_subparts.urllib.request,+ "urlopen",+ side_effect=lcp_subparts.urllib.error.URLError(f"for url key={SECRET}"),+ ):+ result = lcp_subparts._query_crux("https://example.com/", "PHONE", SECRET)++ assert captured["url"] == lcp_subparts.CRUX_ENDPOINT+ assert captured["headers"]["X-Goog-Api-Key"] == SECRET+ assert SECRET not in _dump(result)+ assert "key=" not in _dump(result)diff --git a/tests/test_url_safety.py b/tests/test_url_safety.pyindex 9ebdb01..45f00e8 100644--- a/tests/test_url_safety.py+++ b/tests/test_url_safety.py@@ -15,6 +15,8 @@ import osimport socketimport sysimport threading+from contextlib import contextmanager+from types import SimpleNamespacefrom unittest.mock import patchimport pytest@@ -95,6 +97,24 @@ def test_validate_url_blocks_obfuscated_bypasses(url: str) -> None:assert url_safety.validate_url(url) is False+ "url",+ [+ "http://127.0.0.1:6666\\@1.1.1.1/",+ "https://169.254.169.254\\@example.com/latest/meta-data/",+ "https://user:[email protected]/",+ "https://127.0.0.1#@example.com/",+ "https://example.com%[email protected]/",+ ],+)+def test_validate_url_blocks_authority_confusion(url: str) -> None:+ """Reject URL forms where urllib and the eventual HTTP stack can+ disagree about the connection target."""+ assert url_safety.validate_url(url) is False+ with pytest.raises(url_safety.URLSafetyError):+ url_safety.validate_url_strict(url)++# ---------------------------------------------------------------------------# is_safe_ip# ---------------------------------------------------------------------------@@ -286,6 +306,44 @@ def test_pin_dns_restores_getaddrinfo_on_normal_exit() -> None:assert socket.getaddrinfo is before+def test_safe_requests_head_uses_strict_validation_and_dns_pin() -> None:+ captured: dict = {}+ response = SimpleNamespace(status_code=200)++ @contextmanager+ def fake_pin(hostname: str, pinned_ip: str, port: int):+ captured["pin"] = (hostname, pinned_ip, port)+ yield++ with patch.object(+ url_safety,+ "validate_url_strict",+ return_value=("https://safe.example/path", "1.1.1.1"),+ ) as validate, patch.object(+ url_safety,+ "_pin_dns",+ side_effect=fake_pin,+ ), patch.object(+ url_safety.requests,+ "head",+ return_value=response,+ ) as request_head:+ result = url_safety.safe_requests_head(+ "https://safe.example/path",+ timeout=7,+ allow_redirects=True,+ )++ validate.assert_called_once_with("https://safe.example/path")+ request_head.assert_called_once_with(+ "https://safe.example/path",+ timeout=7,+ allow_redirects=True,+ )+ assert captured["pin"] == ("safe.example", "1.1.1.1", 443)+ assert result is response++def test_pin_dns_restores_getaddrinfo_on_exception() -> None:before = socket.getaddrinfowith pytest.raises(RuntimeError):