fix(app): collection connects only to the addresses it checked, within 15 s, logging no address

- the fetcher resolves once, requires every address to be public and connects only to those
  (TLS still checks the name), so DNS rebinding cannot reach the local network; redirects too
- 15 s for the whole fetch also against servers that send slowly; no URL in any log line
- a site whose title alone changed is kept again
- target names that differ only in case are refused (one Windows folder)
- the worker always gets the collection file, so results older than the keep days go also
  with no targets or the feature off
- the results screen lists every target with results, not only those in the newest 100

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-13 21:39:04 +09:00
parent b94e9dc112
commit 9185265010
10 changed files with 273 additions and 66 deletions

View File

@@ -4,8 +4,10 @@ collection"). Results go only to day files in the data folder; logs carry target
from __future__ import annotations
import hashlib
import ipaddress
import json
import re
import socket
import threading
import time
import urllib.parse
@@ -18,7 +20,9 @@ from typing import Callable, Optional
from .log import debug_log, notice
MAX_BYTES = 1024 * 1024
TIMEOUT_S = 15
TOTAL_S = 15.0
CONNECT_S = 10.0
READ_S = 5.0
MAX_REDIRECTS = 5
SITE_CHARS = 20_000
SUMMARY_CHARS = 2_000
@@ -49,28 +53,88 @@ def load_config(path) -> Config:
[Target(t["name"], t["kind"], t["value"], float(t["everyMinutes"]) * 60) for t in raw.get("targets", [])])
def safe_get(url: str) -> bytes:
"""GET a public http(s) address: every redirect checked again, at most ``MAX_BYTES``."""
import requests
from jarvis.tools.builtin.web_search import _is_public_url
def _is_public_ip(ip) -> bool:
return not (ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_reserved
or ip.is_multicast or ip.is_unspecified)
def _public_ips(host: str, port: int) -> list:
"""The addresses to connect to: every address the name resolves to must be public. The caller
connects only to these, so a second lookup cannot point elsewhere. Nothing about the address
is logged (it is the user's collection target)."""
try:
addrs = [str(ipaddress.ip_address(host))]
except ValueError:
try:
addrs = list(dict.fromkeys(i[4][0] for i in socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)))
except OSError:
raise ValueError("name not found") from None
if not addrs or not all(_is_public_ip(ipaddress.ip_address(a.split("%")[0])) for a in addrs):
raise ValueError("not a public address")
return addrs
def _open(p, port: int, ips: list, host: str, path: str, deadline: float):
"""(pool, response) from the first checked address that connects before `deadline`."""
import certifi
import urllib3
from urllib3.exceptions import ConnectTimeoutError
for i, ip in enumerate(ips):
left = deadline - time.monotonic()
if left <= 0:
raise TimeoutError("took too long")
timeout = urllib3.Timeout(connect=min(CONNECT_S, left), read=READ_S)
if p.scheme == "https":
pool = urllib3.HTTPSConnectionPool(ip, port, timeout=timeout, retries=False, cert_reqs="CERT_REQUIRED",
ca_certs=certifi.where(), server_hostname=p.hostname,
assert_hostname=p.hostname)
else:
pool = urllib3.HTTPConnectionPool(ip, port, timeout=timeout, retries=False)
try:
return pool, pool.urlopen("GET", path, headers={"Host": host, "User-Agent": USER_AGENT,
"Accept-Encoding": "identity"},
redirect=False, retries=False, preload_content=False)
except ConnectTimeoutError: # also a refused connection (NewConnectionError)
pool.close()
if i == len(ips) - 1:
raise
def safe_get(url: str) -> bytes:
"""GET a public http(s) address: every hop's address checked and connected to as checked, at
most ``MAX_BYTES`` and ``TOTAL_S`` seconds in all."""
# Each socket wait is at most READ_S and none starts after `deadline`, so the whole fetch
# (redirects included) ends within TOTAL_S.
deadline = time.monotonic() + TOTAL_S - READ_S
for _ in range(MAX_REDIRECTS + 1):
if not _is_public_url(url):
raise ValueError("not a public address")
with requests.get(url, headers={"User-Agent": USER_AGENT}, timeout=TIMEOUT_S,
allow_redirects=False, stream=True) as r:
if r.is_redirect or r.is_permanent_redirect:
p = urllib.parse.urlsplit(url)
if p.scheme not in ("http", "https") or not p.hostname:
raise ValueError("not an http(s) address")
port = p.port or (443 if p.scheme == "https" else 80)
ips = _public_ips(p.hostname, port)
host = p.hostname if p.port is None else f"{p.hostname}:{p.port}"
if ":" in p.hostname:
host = f"[{p.hostname}]" + ("" if p.port is None else f":{p.port}")
path = (p.path or "/") + (f"?{p.query}" if p.query else "")
pool, r = _open(p, port, ips, host, path, deadline)
try:
if r.status in (301, 302, 303, 307, 308):
url = urllib.parse.urljoin(url, r.headers.get("Location", ""))
continue
r.raise_for_status()
if r.status_code != 200: # e.g. DuckDuckGo's 202 challenge
raise ValueError(f"status {r.status_code}")
if r.status != 200: # e.g. DuckDuckGo's 202 challenge
raise ValueError(f"status {r.status}")
body = b""
for chunk in r.iter_content(64 * 1024):
while chunk := r.read1(64 * 1024):
body += chunk
if len(body) > MAX_BYTES:
raise ValueError("response too large")
if time.monotonic() > deadline:
raise TimeoutError("took too long")
return body
finally:
r.release_conn()
pool.close()
raise ValueError("too many redirects")
@@ -186,7 +250,7 @@ class Collector:
def _run(self, t: Target, state: dict) -> int:
if t.kind == "site":
[page] = _site(self.fetch(t.value))
digest = hashlib.sha256(page["text"].encode()).hexdigest()
digest = hashlib.sha256(json.dumps([page["title"], page["text"]]).encode()).hexdigest()
if digest == state.get("hash"):
return 0
state["hash"] = digest

View File

@@ -322,17 +322,21 @@ which carry Discord's own time.
With `JARVIS_COLLECT_PATH` set, the worker collects on its own thread, apart from the voice and the
brain (`app/src/admin.spec.md`, "Background collection"). The file is
`{"dir": "<data>/collect", "keepDays": 30, "targets": [{"name", "kind", "value", "everyMinutes"}]}`;
the app writes only enabled targets. Nothing is collected without targets.
the app writes only enabled targets. Nothing is collected without targets, but old day files are
still deleted (below).
- A target runs when `everyMinutes` passed since its last run (also across restarts; the last run is
kept in `<dir>/<name>/state.json`), one target at a time, checked every 30 s. A failed run counts
as a run, so a broken site is tried again only at its next interval.
- Kinds: `site` keeps the page's title and text (at most 20,000 characters) when it differs from the
last kept one; `rss` (RSS or Atom) keeps each new item (title, link, time, summary of at most 2,000
- Kinds: `site` keeps the page's title and text (at most 20,000 characters) when either differs from
the last kept ones; `rss` (RSS or Atom) keeps each new item (title, link, time, summary of at most 2,000
characters, new by its id or link); `search` keeps each new web search result (title and link) for
the words, from DuckDuckGo's lite page, which needs no key (its bot challenge is a failed run, not "no results").
- Every request goes through the web search's address check (`web_search.spec.md`): only public
http(s) addresses, every redirect checked again, at most 1 MB, 15 s. The collected text is web
- Every request checks its address like the web search (`web_search.spec.md`): only http(s), and
every address the name resolves to must be public; the connection goes only to the checked
addresses in their order (TLS still checks the name), so a second lookup cannot lead into the
local network. Every redirect is checked the same way. At most 1 MB and 15 s in all (redirects included); a server
that sends slowly is cut off. The check logs nothing about the address. The collected text is web
content: it goes only to `<dir>/<name>/<YYYY-MM-DD>.jsonl` (one JSON object per line: `at`, then
`title`, `url`, `text` as the kind has them), never to the brain or a log.
- Day files older than `keepDays` are deleted in every folder of `dir` at each check, also of