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(security): bind a local target's DNS pin to its port; fix meta charset scan

Agrici Daniel5240957e6d87
diff --git a/SECURITY.md b/SECURITY.md
index ac50651..4d022fe 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -61,7 +61,7 @@ claude-seo is a research and audit toolkit that runs on a user's workstation. It
- **Windows file permissions.** `os.fchmod(fd, 0o600)` is a no-op on Windows for non-ACL filesystems. Users on Windows should rely on per-user directory ACLs instead of POSIX mode bits. `scripts/backlinks_auth.py` additionally makes a best-effort `icacls <path> /inheritance:r /grant:r "%USERNAME%:F"` call after every write to (and load-time remediation of) `~/.config/claude-seo/backlinks-api.json`, restricting it to the current user on NTFS. This is best-effort only: a failure (missing `icacls`, a non-NTFS volume, a restricted shell) is logged as a warning and does not block the credential read or write, so on a failure the file's effective protection on Windows falls back to whatever the containing directory's ACLs already provide.
- **RFC 6598 (100.64.0.0/10) is refused by default.** Cloud providers serve instance metadata in this range, so `url_safety` treats it like RFC 1918. Tailscale also allocates from it, so a staging site reached over Tailscale is refused under the default policy. The escape hatch is `CLAUDE_SEO_LOCAL_TARGETS`, a comma-separated allowlist of `host` or `host:port` entries (for example `localhost:3000,127.0.0.1:8080,100.101.102.103`, the last being a Tailscale address). Its scope is deliberately narrow:
- - It is consulted **only** for the first, top-level URL passed to `validate_url` / `validate_url_strict`. Redirect targets, embedded subresources, and every request the Playwright route handler sees stay fail-closed, so a page served from an allowlisted dev server still cannot pull anything else off the local network. Rendering an allowlisted host through Playwright is therefore not supported; the raw-HTTP path is.
+ - It is consulted **only** for the first, top-level URL passed to `validate_url` / `validate_url_strict`. Redirect targets, embedded subresources, and every request the Playwright route handler sees stay fail-closed, so a page served from an allowlisted dev server still cannot pull anything else off the local network. A `host:port` entry holds for the whole request: a redirect to another port on that same host is followed only when the allowlist also names that port. Rendering an allowlisted host through Playwright is therefore not supported; the raw-HTTP path is.
- A host must be named exactly. There is no range, wildcard, or "allow private" mode, `host:port` matches that port only, and a bare `host` matches any port on that host.
- Cloud metadata endpoints are refused even when listed, by name (`metadata.google.internal` and its siblings) and by address (169.254.169.254, `fd00:ec2::254`, and Alibaba's 100.100.100.200, which sits inside the Tailscale range). Link-local, multicast, unspecified, and reserved addresses are never allowlistable.
- `is_safe_ip` is unchanged and reads no environment, so every fail-closed path downstream of the first connection is unaffected.
diff --git a/scripts/url_safety.py b/scripts/url_safety.py
index 7d9d488..24af86b 100644
--- a/scripts/url_safety.py
+++ b/scripts/url_safety.py
@@ -55,7 +55,9 @@ audit a dev server, a staging host, or a machine reached over Tailscale.
It is consulted **only** for the first, top-level URL handed to
``validate_url`` / ``validate_url_strict``. Redirect targets, embedded
subresources, and browser-issued requests never consult it, and cloud
-metadata endpoints are refused even when listed. Unset, the policy is
+metadata endpoints are refused even when listed. The one later read is the
+DNS pin's port check: a redirect to another port on the admitted host is
+followed only if the allowlist names that port too. Unset, the policy is
exactly what it is without the feature.
Threading
@@ -246,6 +248,8 @@ def is_safe_ip(ip_str: str) -> bool:
# free of any environment dependency.
# * A host must be named. There is no range, wildcard, or "all private".
# * ``host:port`` matches that port only. A bare ``host`` matches any port.
+# ``_pin_dns`` holds the admitted host to the same rule for the whole
+# request chain: see ``_local_pin_allows_port``.
# * Cloud metadata endpoints are refused even when listed. This is the
# trapdoor every "allow local" flag falls through: 169.254.169.254 is
# link-local, 100.100.100.200 sits inside the Tailscale range this
@@ -490,8 +494,9 @@ def validate_url_strict(url: str) -> tuple[str, str]:
if port is None:
raise URLSafetyError(f"Invalid port in URL authority: {url!r}")
- # The CLAUDE_SEO_LOCAL_TARGETS allowlist is read here and nowhere the
- # request chain can reach later, which is what keeps it top-level only.
+ # The CLAUDE_SEO_LOCAL_TARGETS allowlist is read here, which is what keeps
+ # it top-level only. The request chain reaches it again in one place, the
+ # pin's port check for this same host (``_local_pin_allows_port``).
allowlisted = _is_allowlisted_local_target(hostname, port)
if hostname in _BLOCKED_HOSTNAMES and not allowlisted:
raise URLSafetyError(f"Blocked hostname: {hostname}")
@@ -638,6 +643,30 @@ def _validated_proxy_hosts(url: str, proxies: Optional[dict] = None) -> frozense
)
+def _local_pin_allows_port(hostname: str, validated_port: int, requested_port) -> bool:
+ """Whether a pin on a non-public address may answer for ``requested_port``.
+
+ The validated port always may. Any other port on the pinned host (a
+ redirect hop, a second request on a session) is a new target and goes
+ through ``CLAUDE_SEO_LOCAL_TARGETS`` again: a ``host:port`` entry reaches
+ that port only, while a bare ``host`` entry keeps matching every port.
+ A port that cannot be read as a number is refused.
+ """
+ if not requested_port:
+ return True # No port named: the caller is handed the validated one.
+ try:
+ requested = int(requested_port)
+ except (TypeError, ValueError):
+ return False
+ if requested == validated_port:
+ return True
+ try:
+ normalized = normalize_hostname(hostname)
+ except URLSafetyError:
+ return False
+ return _is_allowlisted_local_target(normalized, requested)
+
+
# A single non-blocking lock guards the global getaddrinfo monkey-patch.
# This is a deliberate choice: claude-seo scripts run one URL fetch at a
# time, and we'd rather raise loudly than silently corrupt resolver state
@@ -660,6 +689,12 @@ def _pin_dns(
which ``requests`` surfaces as ``ConnectionError``: the caller's
existing error path.
+ A public ``pinned_ip`` answers for every port on the named host, so an
+ http to https redirect keeps the pin. A non-public ``pinned_ip`` (a
+ ``CLAUDE_SEO_LOCAL_TARGETS`` target) answers for ``port`` only, plus any
+ other port the allowlist names for that host; see
+ :func:`_local_pin_allows_port`.
+
``exempt_hosts`` are resolved by the real resolver without the
fall-through check. It carries the configured HTTP proxy, if any: the
proxy is the process's own egress, and requests must resolve it to open
@@ -686,11 +721,22 @@ def _pin_dns(
original_getaddrinfo = socket.getaddrinfo
target = hostname.lower()
+ # A pinned address that is not public was admitted through
+ # CLAUDE_SEO_LOCAL_TARGETS, where ``host:port`` allows that port only.
+ # Such a pin must not answer for the host's other ports, or a redirect
+ # from the allowed dev server reaches every service on that address.
+ port_bound = not is_safe_ip(pinned_ip)
def patched(host, requested_port, *args, **kwargs):
# Branch 1: the originally-pinned host returns the validated IP
# without any further resolver call.
if host and host.lower() == target:
+ if port_bound and not _local_pin_allows_port(target, port, requested_port):
+ raise socket.gaierror(
+ socket.EAI_FAIL,
+ f"url_safety: refused port {requested_port!r} on pinned "
+ f"non-public host {host}; validated port is {port}",
+ )
family = kwargs.get("family", args[0] if args else 0)
if family in (0, socket.AF_UNSPEC, socket.AF_INET):
return [(
@@ -784,8 +830,12 @@ DEFAULT_REQUEST_HEADERS = {
_CONTENT_TYPE_CHARSET_RE = re.compile(r"charset\s*=\s*['\"]?([^;,'\"\s>]+)", re.IGNORECASE)
# HTML's encoding prescan reads attributes, not the substring "charset=".
_META_TAG_RE = re.compile(r"<meta\b([^>]*)>", re.IGNORECASE)
+# An unquoted value runs to whitespace or ">", as in HTML, so
+# ``content=text/html;charset=windows-1252`` is one value. The value part is
+# optional so a run of name characters with no "=" is consumed in one step
+# instead of being rescanned from every offset (quadratic on hostile input).
_META_ATTR_RE = re.compile(
- r"([^\s=/>]+)\s*=\s*(?:\"([^\"]*)\"|'([^']*)'|([^\s\"'=<>`/]+))",
+ r"([^\s=/>]+)(?:\s*=\s*(?:\"([^\"]*)\"|'([^']*)'|([^\s>]+)))?",
re.IGNORECASE,
)
_BOMS = (
@@ -840,11 +890,14 @@ def _extract_meta_charset(raw: bytes) -> str | None:
elif name == "charset":
charset = value.strip()
need_pragma = False
+ # An unquoted value keeps the "/" of a self-closing tag
+ # (``<meta charset=utf-8/>``); no encoding label ends in one.
+ charset = (charset or "").strip().rstrip("/")
if not charset or need_pragma is None:
continue
if need_pragma and not got_pragma:
continue
- return charset.strip()
+ return charset
return None
diff --git a/tests/test_fetch_page_decoding.py b/tests/test_fetch_page_decoding.py
index e78606f..a368378 100644
--- a/tests/test_fetch_page_decoding.py
+++ b/tests/test_fetch_page_decoding.py
@@ -65,6 +65,60 @@ def test_charset_attribute_wins_when_it_is_the_encoding() -> None:
assert "Smart quote: “" in decoded
+ "meta",
+ [
+ "<meta http-equiv=content-type content=text/html;charset=windows-1252>",
+ "<meta content=text/html;charset=windows-1252 http-equiv=Content-Type>",
+ "<meta http-equiv=content-type content=text/html;charset=windows-1252/>",
+ ],
+)
+def test_unquoted_content_type_pragma_is_detected(meta: str) -> None:
+ """An unquoted value runs to whitespace or ">", so the whole
+ ``text/html;charset=...`` is the content attribute."""
+ html = (meta + "<p>Smart quote: “</p>").encode("windows-1252")
+ decoded = fetch_page._decode_response_content(FakeResponse(html, "text/html"))
+ assert "Smart quote: “" in decoded
+
+
+ "meta",
+ ["<meta charset=windows-1252/>", "<meta charset=windows-1252 />", "<meta charset=windows-1252>"],
+)
+def test_self_closing_unquoted_charset_is_detected(meta: str) -> None:
+ html = (meta + "<p>Smart quote: “</p>").encode("windows-1252")
+ decoded = fetch_page._decode_response_content(FakeResponse(html, "text/html"))
+ assert "Smart quote: “" in decoded
+
+
+def test_charset_inside_an_unquoted_url_is_not_the_encoding() -> None:
+ """The og:image case again, with the URL unquoted and the text after a "/"."""
+ html = (
+ "<meta property=og:image content=https://cdn.example/charset=iso-8859-1>"
+ "<meta name=description content=text/html;charset=iso-8859-1>"
+ "<p>Café</p>"
+ )
+ decoded = fetch_page._decode_response_content(FakeResponse(html.encode("utf-8"), "text/html"))
+ assert "Café" in decoded
+
+
+def test_meta_scan_stays_fast_on_a_hostile_head() -> None:
+ """A 4096-byte run with no "=" must not be rescanned from every offset."""
+ import time
+
+ from url_safety import _extract_meta_charset
+
+ for filler in (b"a" * 4096, b"\"'" * 2048, b'a="' + b"x" * 4093):
+ raw = (b"<meta " + filler)[:4095] + b">"
+ best = float("inf")
+ for _ in range(3):
+ start = time.perf_counter()
+ assert _extract_meta_charset(raw) is None
+ best = min(best, time.perf_counter() - start)
+ # Linear is well under a millisecond; the quadratic scan took 90 ms or more.
+ assert best < 0.02, filler[:8]
+
+
def test_invalid_bytes_are_replaced_not_dropped() -> None:
response = FakeResponse(b"valid utf8 then invalid: \x8f")
decoded = fetch_page._decode_response_content(response)
diff --git a/tests/test_url_safety_port_pin.py b/tests/test_url_safety_port_pin.py
new file mode 100644
index 0000000..926608a
--- /dev/null
+++ b/tests/test_url_safety_port_pin.py
@@ -0,0 +1,340 @@
+"""
+Port-bound DNS pin for CLAUDE_SEO_LOCAL_TARGETS (scripts/url_safety.py).
+
+A ``host:port`` allowlist entry admits that port only. These tests drive the
+real ``requests`` and ``urllib3`` stack through ``safe_requests_get`` with
+the resolver and ``socket.socket`` replaced, so a redirect is followed the
+way it is in production and every connection attempt is recorded. No test
+here touches the network.
+"""
+
+from __future__ import annotations
+
+import io
+import os
+import socket
+import sys
+from unittest.mock import patch
+
+import pytest
+
+_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)
+
+requests = pytest.importorskip("requests")
+import url_safety # noqa: E402
+
+PUBLIC_IP = "93.184.216.34"
+
+
+def _redirect(location: str) -> bytes:
+ return (
+ f"HTTP/1.1 302 Found\r\nLocation: {location}\r\n"
+ "Content-Length: 0\r\nConnection: close\r\n\r\n"
+ ).encode("ascii")
+
+
+def _ok(body: str) -> bytes:
+ return (
+ f"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\n"
+ f"Content-Length: {len(body)}\r\nConnection: close\r\n\r\n{body}"
+ ).encode("ascii")
+
+
+class _FakeNet:
+ """Canned HTTP servers keyed by ``(ip, port)``, plus a connection log."""
+
+ def __init__(self, hosts: dict, servers: dict) -> None:
+ self.hosts = hosts
+ self.servers = servers
+ self.connections: list = []
+
+ def getaddrinfo(self, host, port, *args, **kwargs):
+ if host in self.hosts:
+ ip = self.hosts[host]
+ else:
+ try:
+ socket.inet_aton(host)
+ except (OSError, TypeError):
+ raise socket.gaierror(socket.EAI_NONAME, f"unmocked host {host!r}") from None
+ ip = host
+ return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port or 0))]
+
+ def socket(self, *args, **kwargs):
+ return _FakeSocket(self)
+
+
+class _FakeSocket:
+ """The slice of ``socket.socket`` that urllib3 and http.client use."""
+
+ def __init__(self, net: _FakeNet) -> None:
+ self._net = net
+ self._address = None
+
+ def connect(self, address) -> None:
+ self._net.connections.append(address)
+ if address not in self._net.servers:
+ raise ConnectionRefusedError(111, "no fake server on this port")
+ self._address = address
+
+ def makefile(self, *args, **kwargs):
+ return io.BytesIO(self._net.servers[self._address])
+
+ def sendall(self, data) -> None:
+ pass
+
+ def setsockopt(self, *args) -> None:
+ pass
+
+ def settimeout(self, value) -> None:
+ pass
+
+ def shutdown(self, how) -> None:
+ pass
+
+ def close(self) -> None:
+ pass
+
+
[email protected](autouse=True)
+def _isolated(monkeypatch):
+ """No developer allowlist, no developer proxy."""
+ monkeypatch.delenv("CLAUDE_SEO_LOCAL_TARGETS", raising=False)
+ monkeypatch.setattr(url_safety.requests.utils, "getproxies", lambda: {})
+
+
+def _get(url: str, net: _FakeNet):
+ with patch.object(url_safety.socket, "getaddrinfo", side_effect=net.getaddrinfo), \
+ patch.object(url_safety.socket, "socket", side_effect=net.socket):
+ return url_safety.safe_requests_get(url, timeout=5)
+
+
+# ---------------------------------------------------------------------------
+# Local targets admitted through a host:port entry
+# ---------------------------------------------------------------------------
+
+
+def test_allowed_local_target_still_fetches(monkeypatch) -> None:
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", "localhost:3000")
+ net = _FakeNet({"localhost": "127.0.0.1"}, {("127.0.0.1", 3000): _ok("dev server")})
+
+ response = _get("http://localhost:3000/", net)
+
+ assert response.status_code == 200
+ assert response.content == b"dev server"
+ assert net.connections == [("127.0.0.1", 3000)]
+
+
[email protected]("requested_port", [3000, "3000", None, 0])
+def test_pin_on_a_non_public_address_answers_for_the_validated_port(
+ monkeypatch, requested_port
+) -> None:
+ """A lookup that names no port gets the validated one, as before."""
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", "localhost:3000")
+ with url_safety._pin_dns("localhost", "127.0.0.1", 3000):
+ sockaddr = socket.getaddrinfo("localhost", requested_port)[0][4]
+ assert sockaddr == ("127.0.0.1", requested_port or 3000)
+
+
+ "allowlist,start,hosts,first,location",
+ [
+ (
+ "localhost:3000",
+ "http://localhost:3000/",
+ {"localhost": "127.0.0.1"},
+ ("127.0.0.1", 3000),
+ "http://localhost:6379/",
+ ),
+ (
+ "localhost:3000",
+ "http://localhost:3000/",
+ {"localhost": "127.0.0.1"},
+ ("127.0.0.1", 3000),
+ "http://localhost/",
+ ),
+ (
+ "127.0.0.1:8080",
+ "http://127.0.0.1:8080/",
+ {},
+ ("127.0.0.1", 8080),
+ "http://127.0.0.1:6379/",
+ ),
+ (
+ "staging.internal:8080",
+ "http://staging.internal:8080/",
+ {"staging.internal": "10.0.0.5"},
+ ("10.0.0.5", 8080),
+ "http://staging.internal:9200/",
+ ),
+ ],
+)
+def test_redirect_to_another_port_on_an_allowed_local_host_is_refused(
+ monkeypatch, allowlist, start, hosts, first, location
+) -> None:
+ """``host:port`` allows that port only, on every hop."""
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", allowlist)
+ servers = {first: _redirect(location)}
+ # Every other port on the address answers, so only the pin can stop it.
+ for port in (80, 6379, 9200):
+ servers[(first[0], port)] = _ok("internal service")
+ net = _FakeNet(hosts, servers)
+
+ with pytest.raises(requests.exceptions.ConnectionError, match="validated port"):
+ _get(start, net)
+
+ assert net.connections == [first]
+
+
+def test_session_cannot_reach_another_port_on_an_allowed_local_host(monkeypatch) -> None:
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", "localhost:3000")
+ net = _FakeNet(
+ {"localhost": "127.0.0.1"},
+ {("127.0.0.1", 3000): _ok("dev server"), ("127.0.0.1", 6379): _ok("internal service")},
+ )
+ with patch.object(url_safety.socket, "getaddrinfo", side_effect=net.getaddrinfo), \
+ patch.object(url_safety.socket, "socket", side_effect=net.socket):
+ with url_safety.safe_requests_session("http://localhost:3000/") as session:
+ assert session.get("http://localhost:3000/", timeout=5).content == b"dev server"
+ with pytest.raises(requests.exceptions.ConnectionError, match="validated port"):
+ session.get("http://localhost:6379/", timeout=5)
+
+ assert net.connections == [("127.0.0.1", 3000)]
+
+
+def test_redirect_to_a_port_the_allowlist_also_names_is_followed(monkeypatch) -> None:
+ """The other port is checked as a new target, and the operator named it."""
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", "localhost:3000,localhost:3001")
+ net = _FakeNet(
+ {"localhost": "127.0.0.1"},
+ {
+ ("127.0.0.1", 3000): _redirect("http://localhost:3001/"),
+ ("127.0.0.1", 3001): _ok("second dev server"),
+ ("127.0.0.1", 6379): _ok("internal service"),
+ },
+ )
+
+ assert _get("http://localhost:3000/", net).content == b"second dev server"
+ assert net.connections == [("127.0.0.1", 3000), ("127.0.0.1", 3001)]
+
+ net.servers[("127.0.0.1", 3001)] = _redirect("http://localhost:6379/")
+ net.connections.clear()
+ with pytest.raises(requests.exceptions.ConnectionError, match="validated port"):
+ _get("http://localhost:3000/", net)
+ assert net.connections == [("127.0.0.1", 3000), ("127.0.0.1", 3001)]
+
+
+def test_bare_host_entry_still_matches_any_port_on_redirect(monkeypatch) -> None:
+ """A bare ``host`` entry matches any port, so its redirects keep working."""
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", "100.101.102.103")
+ net = _FakeNet(
+ {},
+ {
+ ("100.101.102.103", 80): _redirect("http://100.101.102.103:8080/"),
+ ("100.101.102.103", 8080): _ok("staging"),
+ },
+ )
+
+ assert _get("http://100.101.102.103/", net).content == b"staging"
+ assert net.connections == [("100.101.102.103", 80), ("100.101.102.103", 8080)]
+
+
[email protected]("requested_port", [6379, "6379", "redis", 80, 443, 3001])
+def test_pin_on_a_non_public_address_answers_for_the_validated_port_only(
+ monkeypatch, requested_port
+) -> None:
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", "localhost:3000")
+ with url_safety._pin_dns("localhost", "127.0.0.1", 3000):
+ with pytest.raises(socket.gaierror, match="validated port is 3000"):
+ socket.getaddrinfo("localhost", requested_port)
+ with pytest.raises(socket.gaierror, match="validated port is 3000"):
+ socket.getaddrinfo("LOCALHOST", requested_port)
+
+
+def test_pin_on_a_non_public_address_is_port_bound_without_an_allowlist() -> None:
+ """Fail closed: the binding follows the pinned address, not the environment."""
+ with url_safety._pin_dns("internal.example", "10.0.0.5", 8080):
+ assert socket.getaddrinfo("internal.example", 8080)[0][4] == ("10.0.0.5", 8080)
+ with pytest.raises(socket.gaierror, match="validated port is 8080"):
+ socket.getaddrinfo("internal.example", 9200)
+
+
+# ---------------------------------------------------------------------------
+# Public hosts and the default policy are unchanged
+# ---------------------------------------------------------------------------
+
+
+def test_public_host_redirecting_http_to_https_still_connects() -> None:
+ """The most common redirect on the web. TLS itself is out of scope here:
+ the fake server refuses the connection, after the pin has answered for
+ port 443 with the validated address."""
+ net = _FakeNet(
+ {"example.com": PUBLIC_IP},
+ {(PUBLIC_IP, 80): _redirect("https://example.com/")},
+ )
+
+ with pytest.raises(requests.exceptions.ConnectionError) as excinfo:
+ _get("http://example.com/", net)
+
+ assert "url_safety" not in str(excinfo.value)
+ assert net.connections == [(PUBLIC_IP, 80), (PUBLIC_IP, 443)]
+
+
+def test_public_host_redirect_to_another_port_is_followed() -> None:
+ net = _FakeNet(
+ {"example.com": PUBLIC_IP},
+ {
+ (PUBLIC_IP, 80): _redirect("http://example.com:8080/app"),
+ (PUBLIC_IP, 8080): _ok("public app"),
+ },
+ )
+
+ assert _get("http://example.com/", net).content == b"public app"
+ assert net.connections == [(PUBLIC_IP, 80), (PUBLIC_IP, 8080)]
+
+
[email protected]("requested_port", [80, 443, 8080, "8443", None, 0])
+def test_pin_on_a_public_address_answers_for_any_port(requested_port) -> None:
+ with url_safety._pin_dns("example.com", PUBLIC_IP, 80):
+ sockaddr = socket.getaddrinfo("example.com", requested_port)[0][4]
+ assert sockaddr == (PUBLIC_IP, requested_port or 80)
+
+
+def test_public_pin_never_consults_the_allowlist(monkeypatch) -> None:
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", "example.com:80")
+ with patch.object(
+ url_safety, "_is_allowlisted_local_target", side_effect=AssertionError("consulted")
+ ):
+ with url_safety._pin_dns("example.com", PUBLIC_IP, 80):
+ assert socket.getaddrinfo("example.com", 443)[0][4] == (PUBLIC_IP, 443)
+
+
+def test_without_local_targets_local_hosts_are_refused_before_any_connection() -> None:
+ net = _FakeNet({"localhost": "127.0.0.1"}, {("127.0.0.1", 3000): _ok("dev server")})
+
+ with pytest.raises(url_safety.URLSafetyError, match="Blocked hostname"):
+ _get("http://localhost:3000/", net)
+ with pytest.raises(url_safety.URLSafetyError, match="Blocked hostname"):
+ _get("http://127.0.0.1:3000/", net)
+
+ assert net.connections == []
+
+
[email protected]("allowlist", [None, "localhost:3000"])
+def test_public_host_redirecting_to_a_local_port_is_refused(monkeypatch, allowlist) -> None:
+ """The allowlist never applies to a redirect target on another host."""
+ if allowlist:
+ monkeypatch.setenv("CLAUDE_SEO_LOCAL_TARGETS", allowlist)
+ net = _FakeNet(
+ {"example.com": PUBLIC_IP, "localhost": "127.0.0.1"},
+ {
+ (PUBLIC_IP, 80): _redirect("http://localhost:3000/"),
+ ("127.0.0.1", 3000): _ok("dev server"),
+ },
+ )
+
+ with pytest.raises(requests.exceptions.ConnectionError, match="non-public IP"):
+ _get("http://example.com/", net)
+
+ assert net.connections == [(PUBLIC_IP, 80)]