Skip to content

Give your AI agent eyes to see the entire internet. Read & search Twitter, Reddit, YouTube, GitHub, Bilibili, XiaoHongShu — one CLI, zero API fees.

fix(web): harden reader input and response boundaries

Pnantb62efd0f0a50
diff --git a/agent_reach/channels/web.py b/agent_reach/channels/web.py
index 9d10dfe1..dfbea213 100644
--- a/agent_reach/channels/web.py
+++ b/agent_reach/channels/web.py
@@ -2,9 +2,33 @@
"""Web — any URL via Jina Reader. Always available."""
import urllib.request
+
+from agent_reach.utils.url import normalize_public_http_url
+
from .base import Channel
_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36"
+_MAX_RESPONSE_BYTES = 5 * 1024 * 1024
+_ANTIBOT_SCAN_BYTES = 4096
+
+
+def _is_antibot_page(body: bytes) -> bool:
+ """Recognize high-confidence Jina/Cloudflare challenge responses."""
+ sample = body[:_ANTIBOT_SCAN_BYTES].decode("utf-8", errors="ignore").casefold()
+
+ jina_captcha_warning = "warning:" in sample and "requiring captcha" in sample
+ challenge_structure = any(
+ marker in sample
+ for marker in (
+ "title: just a moment...",
+ "## performing security verification",
+ "title: attention required! | cloudflare",
+ )
+ )
+ cloudflare_block = "title: attention required! | cloudflare" in sample and (
+ "ray id" in sample or "/cdn-cgi/challenge-platform/" in sample
+ )
+ return (jina_captcha_warning and challenge_structure) or cloudflare_block
class WebChannel(Channel):
@@ -23,12 +47,21 @@ class WebChannel(Channel):
def read(self, url: str) -> str:
"""通过 Jina Reader 读取网页,返回 Markdown 全文。"""
- if not url.startswith(("http://", "https://")):
- url = "https://" + url
+ url = normalize_public_http_url(url)
jina_url = f"https://r.jina.ai/{url}"
req = urllib.request.Request(
jina_url,
headers={"User-Agent": _UA, "Accept": "text/plain"},
)
with urllib.request.urlopen(req, timeout=30) as resp:
- return resp.read().decode("utf-8")
+ body = resp.read(_MAX_RESPONSE_BYTES + 1)
+ if len(body) > _MAX_RESPONSE_BYTES:
+ raise ValueError(
+ f"Jina Reader response exceeds {_MAX_RESPONSE_BYTES} byte limit"
+ )
+ if _is_antibot_page(body):
+ raise RuntimeError(
+ "Jina Reader 返回了反爬验证页,未获取到目标内容;"
+ "请改用站点专用工具或浏览器读取"
+ )
+ return body.decode("utf-8")
diff --git a/agent_reach/utils/url.py b/agent_reach/utils/url.py
index b31f6e82..c88ac22b 100644
--- a/agent_reach/utils/url.py
+++ b/agent_reach/utils/url.py
@@ -2,8 +2,87 @@
from __future__ import annotations
+import ipaddress
+import socket
from urllib.parse import urlsplit
+_BLOCKED_PUBLIC_FETCH_HOSTS = {
+ "home.arpa",
+ "instance-data",
+ "internal",
+ "ip6-localhost",
+ "ip6-loopback",
+ "lan",
+ "local",
+ "localdomain",
+ "localhost",
+ "metadata.google.internal",
+}
+_BLOCKED_PUBLIC_FETCH_SUFFIXES = (
+ ".home.arpa",
+ ".internal",
+ ".lan",
+ ".local",
+ ".localdomain",
+ ".localhost",
+)
+
+
+def _literal_ip_address(
+ host: str,
+) -> ipaddress.IPv4Address | ipaddress.IPv6Address | None:
+ """Parse canonical and legacy IPv4 literal spellings without DNS."""
+ try:
+ return ipaddress.ip_address(host)
+ except ValueError:
+ pass
+
+ try:
+ packed = socket.inet_aton(host)
+ except OSError:
+ return None
+ return ipaddress.IPv4Address(packed)
+
+
+def normalize_public_http_url(url: str) -> str:
+ """Normalize a URL or reject targets that are not clearly public HTTP(S)."""
+ candidate = str(url or "").strip()
+ if (
+ not candidate
+ or "\\" in candidate
+ or any(
+ character.isspace() or ord(character) < 0x20 or ord(character) == 0x7F
+ for character in candidate
+ )
+ ):
+ raise ValueError("only public HTTP(S) URLs are allowed")
+ if "://" not in candidate:
+ candidate = f"https://{candidate}"
+
+ try:
+ parsed = urlsplit(candidate)
+ host = (parsed.hostname or "").lower().rstrip(".")
+ # Accessing the port rejects malformed or out-of-range authorities.
+ _ = parsed.port
+ except (TypeError, ValueError):
+ raise ValueError("only public HTTP(S) URLs are allowed") from None
+
+ literal_address = _literal_ip_address(host)
+ if (
+ parsed.scheme.lower() not in {"http", "https"}
+ or not host
+ or parsed.username is not None
+ or parsed.password is not None
+ or "%" in host
+ or host in _BLOCKED_PUBLIC_FETCH_HOSTS
+ or host.endswith(_BLOCKED_PUBLIC_FETCH_SUFFIXES)
+ or ("." not in host and literal_address is None)
+ or (literal_address is not None and not literal_address.is_global)
+ ):
+ raise ValueError("only public HTTP(S) URLs are allowed")
+
+ return parsed.geturl()
+
def domain_matches(host: str, *domains: str) -> bool:
"""Match a hostname/cookie domain exactly or as a real subdomain."""
diff --git a/tests/test_web_channel.py b/tests/test_web_channel.py
index 2529c784..91606ef1 100644
--- a/tests/test_web_channel.py
+++ b/tests/test_web_channel.py
@@ -10,7 +10,11 @@ completing dedicated coverage for the channels that still lacked it.
from unittest.mock import MagicMock, patch
-from agent_reach.channels.web import WebChannel, _UA
+import pytest
+
+from agent_reach.channels.web import _UA, WebChannel
+
+_MAX_RESPONSE_BYTES = 5 * 1024 * 1024
def _resp(body=b"# Example\nfull text\n"):
@@ -90,3 +94,132 @@ def test_read_decodes_utf8_body():
with patch("urllib.request.urlopen", return_value=_resp("café ☕\n".encode("utf-8"))):
out = channel.read("https://example.com")
assert out == "café ☕\n"
+
+
+ "url",
+ [
+ "file:///etc/passwd",
+ "ftp://example.com/file",
+ "http://localhost/admin",
+ "http://intranet/admin",
+ "http://home.arpa/admin",
+ "http://metadata.google.internal/latest/meta-data",
+ "http://127.0.0.1/private",
+ "http://127.1/private",
+ "http://169.254.169.254/latest/meta-data",
+ "http://192.168.1/private",
+ "http://0/private",
+ "http://2130706433/private",
+ "http://0x7f000001/private",
+ "http://0177.0.0.1/private",
+ "http://2852039166/latest/meta-data",
+ "http://0xA9FEA9FE/latest/meta-data",
+ "http://[::1]/private",
+ "http://[::ffff:127.0.0.1]/private",
+ "http://localhost./admin",
+ "http://127.0.0.1\\example.com/private",
+ "https://user:[email protected]/private",
+ ],
+)
+def test_read_rejects_non_public_urls_before_network(url):
+ channel = WebChannel()
+
+ with patch("urllib.request.urlopen") as mock_open:
+ with pytest.raises(ValueError, match="public HTTP"):
+ channel.read(url)
+
+ mock_open.assert_not_called()
+
+
[email protected]("url", ["https://8.8.8.8/page", "http://010.010.010.010/page"])
+def test_read_allows_public_literal_addresses(url):
+ channel = WebChannel()
+ with patch("urllib.request.urlopen", return_value=_resp()) as mock_open:
+ channel.read(url)
+ mock_open.assert_called_once()
+
+
+def test_read_accepts_response_at_exact_size_limit():
+ channel = WebChannel()
+ response = _resp(b"x" * _MAX_RESPONSE_BYTES)
+
+ with patch("urllib.request.urlopen", return_value=response):
+ out = channel.read("https://example.com/exact")
+
+ assert len(out) == _MAX_RESPONSE_BYTES
+ response.__enter__.return_value.read.assert_called_once_with(
+ _MAX_RESPONSE_BYTES + 1
+ )
+
+
+def test_read_rejects_oversized_reader_response():
+ channel = WebChannel()
+ response = _resp(b"x" * (_MAX_RESPONSE_BYTES + 1))
+
+ with patch("urllib.request.urlopen", return_value=response):
+ with pytest.raises(ValueError, match="response exceeds"):
+ channel.read("https://example.com/large")
+
+ response.__enter__.return_value.read.assert_called_once_with(
+ _MAX_RESPONSE_BYTES + 1
+ )
+
+
+ "body",
+ [
+ (
+ "Title: Just a moment...\n\n"
+ "URL Source: https://imginn.com/instagram/\n\n"
+ "Warning: This page maybe requiring CAPTCHA\n\n"
+ "Markdown Content:\n\n"
+ "## Performing security verification\n"
+ ),
+ (
+ "Title: Attention Required! | Cloudflare\n\n"
+ "Sorry, you have been blocked.\n\nRay ID: 1234567890abcdef\n"
+ ),
+ ],
+)
+def test_read_rejects_high_confidence_antibot_pages(body):
+ channel = WebChannel()
+
+ with patch(
+ "urllib.request.urlopen", return_value=_resp(body.encode("utf-8"))
+ ) as mock_open:
+ with pytest.raises(RuntimeError, match="反爬验证页"):
+ channel.read("https://example.com/protected")
+
+ mock_open.assert_called_once()
+
+
+ "body",
+ [
+ "# A guide to security verification\n",
+ "# DDoS protection explained\n",
+ "# Checking your browser automation\n",
+ "# Please turn JavaScript on for progressive enhancement\n",
+ "# A history of cf-browser-verify\n",
+ "Title: Just a moment...\n\nA short-story review.\n",
+ ],
+)
+def test_read_does_not_reject_single_generic_antibot_terms(body):
+ channel = WebChannel()
+
+ with patch("urllib.request.urlopen", return_value=_resp(body.encode("utf-8"))):
+ assert channel.read("https://example.com/article") == body
+
+
+def test_antibot_detection_has_a_fixed_scan_window():
+ channel = WebChannel()
+ body = (
+ "x" * 4096
+ + "Warning: requiring CAPTCHA\n"
+ + "Title: Just a moment...\n"
+ + "## Performing security verification\n"
+ )
+
+ with patch("urllib.request.urlopen", return_value=_resp(body.encode("utf-8"))):
+ assert channel.read("https://example.com/long-article") == body