AI powered OSINT engine to discover and map 840+ social media identities across the web
Python aiartificial-intelligencedebainhackhackerhackinghackingtoolsinformationinformation-gatheringlinuxlinux-desktoposintpythonpython-scriptpython3social-mediasocialmediahackingtermuxtermux-tool
fix: a Found must survive a second opinion (#22); release 2.7.0
arxhr007709a4c87547a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 535d8c2..87b1eab 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,55 @@# Changelog+## 2.7.0 (2026-10-08)++### Fixed+- **Usernames that don't exist were reported as Found** (#22, reported with rendered-page+ evidence by @vollegrewar). A made-up username came back Found on 11 of 19 sites tried,+ up to 95% confidence. The detector scores how profile-like a page looks, and three kinds+ of page look the part without being one. A Found now has to survive a check for each:+ - **The site's own answer.** HTTP `404` or `410` is reported as Not Found whatever the+ score (chatujme.cz answered 404 and was Found at 84%). Any other error code, such as a+ `403` block page or a `500`, is Maybe at most.+ - **The same page for everyone.** JavaScript apps, soft "no such user" pages and+ redirects to search answer every profile address alike. For each Found, the site is now+ also asked for a username that cannot exist; when both answers are the same page, the+ result is Maybe. One extra request per Found, cached per site, so a full scan takes the+ same time (54 seconds before and after for 858 sites).+ - Bot-check pages, as since 2.5.1.++ Measured on recorded pages from 135 sites the model never trained on, same rows before+ and after:++ | | 2.6.0 | 2.7.0 | change (95% interval) |+ |---|---|---|---|+ | Missing usernames reported Found | 33 of 399 (8.3%) | 4 of 399 (1.0%) | -7.3 points (-11.7 to -3.5) |+ | Real accounts reported Found | 93 of 172 (54%) | 85 of 172 (49%) | -4.7 points (-8.8 to -1.2) |+ | Precision | 0.74 | 0.96 | |++ The accounts no longer reported Found are ones whose page is identical to a missing+ user's: nothing in the response told them apart, so they are a Maybe. Of the 4 false+ hits left, 2 are real accounts: test names meant not to exist that do, on chess.com and+ Discogs. The other 2 are one site whose pages differ slightly on every load.+ The threshold was chosen on the 286 training sites, where the same change takes false+ hits from 7.3% to 0.9%.++ Live, a scan of all sites for a username used on one of them went from 54 Found to 3.++### Added+- `--no-control-check` (and `control_check` in a config file) skips the second request.+- `aliens_eye selfcheck` now scores what a scan reports, with the checks above;+ `--detector-only` scores the detector's verdict alone, as before.++### Removed+- Four sites whose address can never identify an account by username: `pubmed` (a search+ page), `pornmd` (a search aggregator), `literotica` and `empornium` (the address takes a+ numeric id). 854 sites remain.++### Not changed+- The other suggestions in #22: rendering every page in a browser, and searching sites+ that have no profile address. `wikipedia` and `giphy` keep their addresses: with the+ check above, a username that doesn't exist is no longer Found on either.+## 2.6.0 (2026-10-08)### Fixeddiff --git a/README.md b/README.mdindex 40e5c7d..a2529e0 100644--- a/README.md+++ b/README.md@@ -36,6 +36,7 @@- **MCP server** — expose scanning to LLM agents (`aliens_eye serve`, optional extra)- **Proxy & Tor support** — `--proxy socks5://...` or just `--tor`- **Site filtering** — `--site github,reddit`, `--exclude-site`, `--no-nsfw`, plus drop-in `sites.d/` plugin site maps+- **A second opinion on every Found** — the site is also asked for a username that cannot exist; if it shows the same page, the hit is downgraded to Maybe- **Calibrated self-check** — `aliens_eye selfcheck` reports precision / recall / F1 / FPR per site- **Reproducible evaluation** — record a frozen response corpus once, then replay it for identical metrics run to run (`aliens_eye corpus record` / `selfcheck --corpus`)- **Ablations and baselines** — `aliens_eye eval ablate` scores detector configurations with bootstrap confidence intervals; `eval external` compares against Sherlock / Maigret / WhatsMyName rules on the same stored responses@@ -182,7 +183,13 @@ Two judges then vote:The blended probability maps to **Found / Maybe / Not Found** with a confidence percentage. The loaded model supplies both the blend weight and the thresholds — the shipped model uses `0.9 * ml + 0.1 * heuristic`, Found above `0.620`, Not Found below `0.360`. If a model file is missing or invalid, the scanner silently falls back to heuristics with the defaults in `core/detector.py` (`0.4` ML weight, `0.6` / `0.35` thresholds). See [WORKING.md](WORKING.md) for the full table.-> **Treat Found/Maybe as leads to verify, not as findings.** The shipped model was fit on 1,455 samples from 286 platforms and evaluated on 142 platforms it never saw: precision 0.65, recall 0.51, false-positive rate 9% (F1 0.57). It favours fewer false leads over catching every account, and on held-out platforms no configuration -- including this one -- is statistically distinguishable from a plain HTTP-status check on F1.+A **Found** then has to survive three checks, because a page is scored on how profile-like it looks and error pages, challenge pages and empty JavaScript shells can look the part:++- an HTTP `404`/`410` is reported as Not Found, and any other error code as Maybe at most;+- a bot-check or error page is capped at Maybe;+- the site is asked for a username that cannot exist, and if it answers with the same page, the result is capped at Maybe (`--no-control-check` skips this; it costs one extra request per Found).++> **Treat Found/Maybe as leads to verify, not as findings.** The shipped model was fit on 1,455 samples from 286 platforms. On 135 platforms it never saw, a scan reports Found for 1.0% of usernames that don't exist there (4 of 399) and for 49% of accounts that do (85 of 172): precision 0.96, F1 0.65. Before 2.7.0 those figures were 8.3% and 54%. It favours fewer false leads over catching every account: a real account on a site that shows everyone the same page is a Maybe, since nothing in the response tells it apart. On F1 it is still not statistically distinguishable from a plain HTTP-status check (difference -0.02 to +0.10, 95% interval); what it buys is the false-positive rate, 1% against 30%.### Retraining the modeldiff --git a/pyproject.toml b/pyproject.tomlindex ec42374..28941a8 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -4,7 +4,7 @@ build-backend = "hatchling.build"[project]name = "aliens-eye"-version = "2.6.0"+version = "2.7.0"description = "AI-powered OSINT username scanner across 800+ social media and web platforms"readme = "README.md"requires-python = ">=3.10"diff --git a/src/aliens_eye/__init__.py b/src/aliens_eye/__init__.pyindex 68abe08..400b28d 100644--- a/src/aliens_eye/__init__.py+++ b/src/aliens_eye/__init__.py@@ -1,3 +1,3 @@"""Aliens Eye - AI-powered OSINT username scanner."""-__version__ = "2.6.0"+__version__ = "2.7.0"diff --git a/src/aliens_eye/cli.py b/src/aliens_eye/cli.pyindex c04f78f..3561d9e 100644--- a/src/aliens_eye/cli.py+++ b/src/aliens_eye/cli.py@@ -100,6 +100,12 @@ def build_parser() -> ArgumentParser:action="store_true",help="Enable Playwright fallback for Maybe results (requires aliens-eye[browser])",)+ parser.add_argument(+ "--no-control-check",+ action="store_true",+ help="Report Found without first checking that the site shows something else "+ "for a username that doesn't exist (saves one request per Found; more false hits)",+ )parser.add_argument("--proxy", type=str, help="Proxy URL (http://, socks4://, or socks5://)")parser.add_argument("--tor", action="store_true", help=f"Route traffic through Tor ({TOR_PROXY})"@@ -196,6 +202,11 @@ def build_selfcheck_parser() -> ArgumentParser:help="With --corpus, score URLs absent from the corpus as fetch errors ""instead of failing loudly",)+ parser.add_argument(+ "--detector-only", action="store_true",+ help="Score the detector's verdict alone, without the checks a scan applies to "+ "every Found (HTTP errors, challenge pages, the same page as a missing user)",+ )return parser@@ -532,6 +543,7 @@ def apply_config(config: ScannerConfig, data: dict) -> dict:"fingerprints_path": "fingerprints_path","output_dir": "output_dir","use_playwright": "use_playwright",+ "control_check": "control_check","max_fingerprints_per_label": "max_fingerprints_per_label","proxy": "proxy","use_ml": "use_ml",@@ -575,6 +587,8 @@ def apply_cli_overrides(config: ScannerConfig, args) -> None:config.output_dir = Path(args.output)if args.playwright:config.use_playwright = True+ if getattr(args, "no_control_check", False):+ config.control_check = Falseif args.tor:config.proxy = TOR_PROXYelif args.proxy:@@ -926,7 +940,10 @@ async def run_selfcheck_command(args) -> None:args.split, Path(args.ground_truth) if args.ground_truth else None))- jobs = replay.eval_jobs(sites)+ # A scan asks each site what it shows for a made-up username. The corpus+ # answers with one recorded negative per site, which then cannot also be+ # a test row: it would be compared with itself.+ jobs = replay.eval_jobs(sites, exclude_controls=not args.detector_only)if not jobs:console.print(f"[red]Corpus at {args.corpus} holds no labelled records for split "@@ -948,6 +965,7 @@ async def run_selfcheck_command(args) -> None:ground_truth_path=Path(args.ground_truth) if args.ground_truth else None,fetch=fetch,jobs=jobs,+ detector_only=args.detector_only,)diff --git a/src/aliens_eye/core/config.py b/src/aliens_eye/core/config.pyindex 8718a21..fb8ac57 100644--- a/src/aliens_eye/core/config.py+++ b/src/aliens_eye/core/config.py@@ -191,6 +191,10 @@ class ScannerConfig:fingerprints_path: Path = field(default_factory=default_fingerprints_path)output_dir: Path = Path("results")use_playwright: bool = False+ # For every Found, also ask the site for a username that cannot exist, and+ # downgrade to Maybe when both answers are the same page. One extra request+ # per site that reports Found.+ control_check: bool = Truemax_fingerprints_per_label: int = 50proxy: str | None = Noneinclude_sites: list[str] | None = Nonediff --git a/src/aliens_eye/core/control.py b/src/aliens_eye/core/control.pynew file mode 100644index 0000000..ab905b7--- /dev/null+++ b/src/aliens_eye/core/control.py@@ -0,0 +1,120 @@+"""Is this the page a site shows for a user who does not exist?++Many sites answer every profile address with HTTP 200: a JavaScript shell that+fills itself in later, a "no such user" page, a redirect to search. Such a page+names the username and carries profile-shaped markup, so scored on its own it+can look like a hit.++The scanner therefore asks the site a second question: what do you show for a+username that certainly does not exist? If the page for the searched username is+essentially that same page, the site has not told the two apart, and neither+can the scanner. This module is the comparison; the scanner decides what to do+with the answer.+"""++from __future__ import annotations++import re+import secrets+from collections import Counter+from dataclasses import dataclass+from urllib.parse import unquote, urlparse++from selectolax.lexbor import LexborHTMLParser++# A page counts as "the same page" at or above these. On the 286 training sites+# the pages wrongly reported as Found sit almost entirely at a similarity of+# 1.0 (45 of 52), so any threshold from 0.85 to 0.995 removes the same ones;+# 0.95 leaves room for a timestamp or a rotating recommendation. The length+# test is a guard for pages whose text matches while one carries far more data.+SAME_TEXT = 0.95+SAME_LENGTH = 0.85++# The server saying outright that there is no such page.+GONE_CODES = (404, 410)++_PLACEHOLDER = "\x00user\x00"+_TOKEN_RE = re.compile(r"\w+", re.UNICODE)+_META_NAMES = ("description", "og:title", "og:description", "og:image", "og:url",+ "twitter:title", "twitter:description", "twitter:image", "profile:username")+_MAX_TOKENS = 6000+++def control_username() -> str:+ """A handle that will not exist anywhere: 16 random lowercase characters."""+ return "zq" + secrets.token_hex(7)+++@dataclass(frozen=True)+class PageShape:+ """What is compared between two pages of one site."""++ tokens: Counter+ length: int+ final_path: str # where the request ended up, with the username masked+++def _mask(text: str, username: str) -> str:+ """``text`` lowercased, with the username replaced by a fixed marker."""+ text = text.lower()+ name = username.lower()+ return text.replace(name, _PLACEHOLDER) if name else text+++def page_shape(html: str, final_url: str, username: str) -> PageShape:+ """Reduce a page to what should differ between a real and a missing user."""+ parts: list[str] = []+ if html:+ tree = LexborHTMLParser(html)+ title = tree.css_first("title")+ if title is not None:+ parts.append(title.text() or "")+ for node in tree.css("meta[content]"):+ name = (node.attributes.get("property") or node.attributes.get("name") or "").lower()+ if name in _META_NAMES:+ parts.append(node.attributes.get("content") or "")+ for tag in ("script", "style", "noscript", "template", "svg"):+ for node in tree.css(tag):+ node.decompose()+ body = tree.body+ if body is not None:+ parts.append(body.text(separator=" "))+ tokens = _TOKEN_RE.findall(_mask(" ".join(parts), username))[:_MAX_TOKENS]+ try:+ parsed = urlparse(final_url)+ final_path = _mask(unquote(f"{parsed.netloc}{parsed.path}").rstrip("/"), username)+ except ValueError:+ final_path = ""+ return PageShape(Counter(tokens), len(html or ""), final_path)+++def text_similarity(a: PageShape, b: PageShape) -> float:+ """Share of words the two pages have in common, 0 to 1. Two empty pages are equal."""+ total = sum(a.tokens.values()) + sum(b.tokens.values())+ if total == 0:+ return 1.0+ return 2 * sum((a.tokens & b.tokens).values()) / total+++def length_ratio(a: PageShape, b: PageShape) -> float:+ longest = max(a.length, b.length)+ return 1.0 if longest == 0 else min(a.length, b.length) / longest+++def http_overrule(status_code: int) -> tuple[str, str] | None:+ """What an HTTP error code makes of a page scored as Found: ``(status, reason)``.++ A 404 or 410 is the site's own answer and settles it. Any other error (a+ 403 block page, a 500) is not a profile either, but says nothing about+ whether the account exists.+ """+ if status_code in GONE_CODES:+ return "Not Found", "http-gone"+ if status_code >= 400:+ return "Maybe", "http-error"+ return None+++def same_page(page: PageShape, control: PageShape) -> bool:+ """True when ``page`` is, in effect, the page shown for a user who doesn't exist."""+ return text_similarity(page, control) >= SAME_TEXT and length_ratio(page, control) >= SAME_LENGTHdiff --git a/src/aliens_eye/core/scanner.py b/src/aliens_eye/core/scanner.pyindex 83995d9..b17fe1f 100644--- a/src/aliens_eye/core/scanner.py+++ b/src/aliens_eye/core/scanner.py@@ -14,6 +14,7 @@ from aliens_eye.utils.console import ScanView, get_consolefrom .analyzer import FeatureExtractorfrom .browser import BrowserFallbackfrom .config import DEFAULT_HEADERS, MAX_HEADER_SIZE, ScannerConfig+from .control import PageShape, control_username, http_overrule, page_shape, same_pagefrom .detector import Detectorfrom .fingerprints import FingerprintStore, build_fingerprintfrom .http import fetch_url@@ -193,6 +194,22 @@ def build_session()+async def overrule_found(status_code: int, signals: dict[str, Any], same_as_missing_user=None):+ """Whether a page scored Found should be reported as something else.++ Returns ``(status, reason)`` or None. The checks run cheapest first, and+ ``same_as_missing_user`` (an async callable, or None to skip it) is only+ awaited when nothing else has settled the matter, since it costs a request.+ Shared by the scanner and the self-check so that both report the same thing.+ """+ overruled = http_overrule(status_code)+ if overruled is None and _looks_like_bot_wall(signals):+ overruled = ("Maybe", "botwall-capped")+ if overruled is None and same_as_missing_user is not None and await same_as_missing_user():+ overruled = ("Maybe", "same-as-missing-user")+ return overruled++class UsernameScanner:"""Coordinates async scanning across all platforms."""@@ -230,6 +247,10 @@ class UsernameScanner:# without touching the process-wide console.self.console = console or get_console()+ # What each site shows for a username that does not exist, fetched the+ # first time that site reports Found. None: it could not be fetched.+ self._controls: dict[str, PageShape | None] = {}+self.results_dir = config.output_dirself.results_dir.mkdir(parents=True, exist_ok=True)@@ -388,10 +409,48 @@ class UsernameScanner:"""config = self.configbudget = (config.retries + 1) * (config.timeout + config.backoff_cap + config.jitter)+ if config.control_check:+ budget *= 2 # a Found is followed by one more request to the same siteif config.use_playwright and self.browser_fallback is not None:budget += 60.0return budget * 1.5 + 1.0+ async def _same_as_missing_user(+ self,+ site_name: str,+ url_template: str,+ username: str,+ fetch,+ session: aiohttp.ClientSession,+ rate_limiter: DomainRateLimiter,+ ) -> bool:+ """Whether this page is what the site shows for a user who doesn't exist.++ Sites that answer every profile address with the same page (a JavaScript+ shell, a soft "not found", a redirect to search) cannot be read for+ existence from that page. See ``core.control``.+ """+ if site_name not in self._controls:+ shape = None+ # A replayed corpus cannot be asked for a new username; it offers one+ # it recorded instead.+ recorded = getattr(self.fetch, "control_for", None)+ name, url = control_username(), None+ if recorded is not None:+ name, url = recorded(site_name) or (name, None)+ url = url or self._format_url(site_name, url_template, name)+ try:+ control = await self.fetch(session, url, self.config, rate_limiter, self.logger)+ if not control.error:+ shape = page_shape(control.content, control.final_url, name)+ except Exception as exc: # noqa: BLE001 - no control means no second opinion, not a failed scan+ self.logger.debug("Control fetch failed for %s: %s", site_name, exc)+ self._controls[site_name] = shape+ control_shape = self._controls[site_name]+ if control_shape is None:+ return False+ return same_page(page_shape(fetch.content, fetch.final_url, username), control_shape)+async def _scan_site(self,site_name: str,@@ -473,13 +532,23 @@ class UsernameScanner:confidence,)- # A challenge or error page is never a real hit. These pages often- # return 200 and mention "user" or "profile", which reads as Found,- # so they are capped at Maybe.- if status_text == "Found" and _looks_like_bot_wall(bundle.signals):- status_text = "Maybe"- confidence = min(confidence, 55)- ai_analysis["method"] = f"{ai_analysis['method']}-botwall-capped"+ # "Found" claims an account exists, and the score alone cannot carry+ # that: a page is scored on how profile-like it looks, and error+ # pages, challenge pages and empty JavaScript shells can look the part.+ if status_text == "Found":+ async def same_as_missing_user() -> bool:+ return await self._same_as_missing_user(+ site_name, url_template, username, fetch, session, rate_limiter+ )++ overruled = await overrule_found(+ fetch.status, bundle.signals,+ same_as_missing_user if self.config.control_check else None,+ )+ if overruled is not None:+ status_text, reason = overruled+ confidence = 90 if status_text == "Not Found" else min(confidence, 55)+ ai_analysis["method"] = f"{ai_analysis['method']}-{reason}"if status_text in {"Found", "Not Found"} and confidence >= 85:label = "found" if status_text == "Found" else "not_found"diff --git a/src/aliens_eye/corpus/replay.py b/src/aliens_eye/corpus/replay.pyindex dec84ab..5037476 100644--- a/src/aliens_eye/corpus/replay.py+++ b/src/aliens_eye/corpus/replay.py@@ -63,7 +63,26 @@ class ReplayFetcher:def labels_by_url(self) -> dict[str, int | None]:return {url: record.label for url, record in self.records.items()}- def eval_jobs(self, sites: set[str] | None = None) -> list[tuple[str, str, str, int]]:+ def control_for(self, site: str) -> tuple[str, str] | None:+ """``(username, url)`` of a recorded page for a user who doesn't exist on ``site``.++ Live, the scanner invents a username and asks the site. A corpus can+ only answer for what it recorded, so one random-string negative per site+ stands in. Those rows are then no longer fair test rows (each would be+ compared with itself); ``eval_jobs(exclude_controls=True)`` leaves them out.+ """+ if not hasattr(self, "_control_rows"):+ rows: dict[str, tuple[str, str]] = {}+ for record in sorted(self.records.values(), key=lambda r: (r.site, r.username)):+ if (record.label == 0 and not record.error and record.site not in rows+ and (record.notes or {}).get("negative_kind") == "random"):+ rows[record.site] = (record.username, record.url)+ self._control_rows = rows+ return self._control_rows.get(site)++ def eval_jobs(+ self, sites: set[str] | None = None, exclude_controls: bool = False+ ) -> list[tuple[str, str, str, int]]:"""The labelled evaluation set held by this corpus.Returns ``(site, url, username, label)`` for every labelled record, in a@@ -76,6 +95,7 @@ class ReplayFetcher:(r.site, r.url, r.username, int(r.label))for r in self.records.values()if r.label is not None and (sites is None or r.site in sites)+ and not (exclude_controls and (self.control_for(r.site) or ("", ""))[1] == r.url)]return sorted(jobs, key=lambda j: (j[0], j[3], j[2]))diff --git a/src/aliens_eye/data/nsfw_sites.json b/src/aliens_eye/data/nsfw_sites.jsonindex 8ecf932..789cff5 100644--- a/src/aliens_eye/data/nsfw_sites.json+++ b/src/aliens_eye/data/nsfw_sites.json@@ -10,10 +10,7 @@"pornhub","myfreecams","camsoda",- "pornmd","hentaifoundry",- "literotica",- "empornium","pornbox","porn.com","cam4",diff --git a/src/aliens_eye/data/sites.json b/src/aliens_eye/data/sites.jsonindex 5fc988a..b4f0be8 100644--- a/src/aliens_eye/data/sites.json+++ b/src/aliens_eye/data/sites.json@@ -502,9 +502,7 @@"manyvids": "https://www.manyvids.com/Profile/{}","spankbang": "https://spankbang.com/p/{}","camsoda": "https://www.camsoda.com/{}",- "pornmd": "https://www.pornmd.com/{}","hentaifoundry": "https://www.hentai-foundry.com/user/{}",- "literotica": "https://www.literotica.com/stories/memberpage.php?uid={}","fetlife": "https://fetlife.com/users/{}","inkedin": "https://inkedin.com/{}","wankzvr": "https://www.wankzvr.com/{}",@@ -515,7 +513,6 @@"naughtyamerica": "https://members.naughtyamerica.com/members/profile/{}","javlibrary": "https://www.javlibrary.com/en/vl_star.php?s={}","eroshare": "https://eroshare.com/u/{}",- "empornium": "https://empornium.is/userdetails.php?id={}","pornbox": "https://pornbox.org/{}","bang": "https://www.bang.com/profile/{}","clips4sale": "https://www.clips4sale.com/studio/{}",@@ -748,7 +745,6 @@"dblp": "https://dblp.org/pid/{}","IEEE": "https://ieeexplore.ieee.org/author/{}","ACM": "https://dl.acm.org/profile/{}",- "pubmed": "https://pubmed.ncbi.nlm.nih.gov/?term={}","overleaf": "https://www.overleaf.com/user/{}","zotero": "https://www.zotero.org/{}","mendeley": "https://www.mendeley.com/profiles/{}",diff --git a/src/aliens_eye/selfcheck.py b/src/aliens_eye/selfcheck.pyindex 101d05d..2dd2206 100644--- a/src/aliens_eye/selfcheck.py+++ b/src/aliens_eye/selfcheck.py@@ -25,10 +25,11 @@ from rich.text import Textfrom aliens_eye.core.analyzer import FeatureExtractorfrom aliens_eye.core.config import ScannerConfig+from aliens_eye.core.control import PageShape, control_username, page_shape, same_pagefrom aliens_eye.core.detector import Detectorfrom aliens_eye.core.http import fetch_urlfrom aliens_eye.core.rate_limit import DomainRateLimiter-from aliens_eye.core.scanner import build_session, format_site_url+from aliens_eye.core.scanner import build_session, format_site_url, overrule_foundfrom aliens_eye.utils.console import get_console@@ -81,8 +82,15 @@ async def run_selfcheck(ground_truth_path: Path | None = None,fetch=fetch_url,jobs: list[tuple[str, str, str, int]] | None = None,+ detector_only: bool = False,) -> dict[str, Any]:- """Run the self-check. Returns a metrics dict; renders a report unless report_format='json'."""+ """Run the self-check. Returns a metrics dict; renders a report unless report_format='json'.++ By default a row is scored the way a scan reports it: the detector's verdict,+ then the checks that can overrule a Found (an HTTP error, a challenge page,+ the same page as a user who doesn't exist). ``detector_only`` scores the+ detector's verdict alone, which is what model training compares.+ """console = get_console()jobs_supplied = jobs is not Noneselfcheck = load_selfcheck_data(split, ground_truth_path)@@ -119,10 +127,28 @@ async def run_selfcheck(rows: list[dict] = []semaphore = asyncio.Semaphore(min(10, len(jobs)))+ controls: dict[str, asyncio.Task] = {}async with build_session(config, 10) as session:fetch_result = fetch+ async def fetch_control(site: str) -> PageShape | None:+ """What ``site`` shows for a username that does not exist."""+ recorded = getattr(fetch_result, "control_for", None)+ name, url = control_username(), None+ if recorded is not None:+ name, url = recorded(site) or (name, None)+ if url is None:+ if site not in sites_data:+ return None+ url = format_site_url(site, sites_data[site], name)+ try:+ async with semaphore:+ page = await fetch_result(session, url, config, rate_limiter, logger)+ except Exception: # noqa: BLE001 - no control means no second opinion+ return None+ return None if page.error else page_shape(page.content, page.final_url, name)+async def check(site: str, url: str, username: str, label: int) -> None:async with semaphore:fetch = await fetch_result(session, url, config, rate_limiter, logger)@@ -138,10 +164,26 @@ async def run_selfcheck(bundle.features["fingerprint_match_found"] = 0.0bundle.features["fingerprint_match_not_found"] = 0.0detection = detector.predict(bundle.features)+ status, note = detection.status, detection.method+ if status == "Found" and not detector_only:+ async def same_as_missing_user() -> bool:+ if site not in controls: # one fetch per site, shared by its rows+ controls[site] = asyncio.ensure_future(fetch_control(site))+ control = await controls[site]+ return control is not None and same_page(+ page_shape(fetch.content, fetch.final_url, username), control+ )++ overruled = await overrule_found(+ fetch.status, bundle.signals,+ same_as_missing_user if config.control_check else None,+ )+ if overruled is not None:+ status, note = overruled[0], f"{note}-{overruled[1]}"rows.append({"site": site, "username": username, "label": label,- "status": detection.status, "confidence": detection.confidence,- "predicted": 1 if detection.status == "Found" else 0,- "note": detection.method})+ "status": status, "confidence": detection.confidence,+ "predicted": 1 if status == "Found" else 0,+ "note": note})await asyncio.gather(*(check(*j) for j in jobs))diff --git a/tests/test_config_cli.py b/tests/test_config_cli.pyindex 4485f08..9babc9f 100644--- a/tests/test_config_cli.py+++ b/tests/test_config_cli.py@@ -186,3 +186,15 @@ def test_analyzer_uses_a_parser_backend_that_still_exists():import aliens_eye.core.analyzer as analyzerassert analyzer.HTMLParser.__module__.startswith("selectolax.lexbor")+++def test_control_check_is_on_by_default_and_can_be_turned_off():+ from aliens_eye.cli import apply_cli_overrides, build_parser+ from aliens_eye.core.config import ScannerConfig++ config = ScannerConfig()+ assert config.control_check is True+ apply_cli_overrides(config, build_parser().parse_args(["someone"]))+ assert config.control_check is True+ apply_cli_overrides(config, build_parser().parse_args(["someone", "--no-control-check"]))+ assert config.control_check is Falsediff --git a/tests/test_control.py b/tests/test_control.pynew file mode 100644index 0000000..6633436--- /dev/null+++ b/tests/test_control.py@@ -0,0 +1,190 @@+"""A Found has to survive a second opinion: issue #22.++A username that does not exist was reported Found on 11 of 19 sites tried,+because the page each site returns for *anyone* looks like a profile.+"""++import pytest+from aiohttp import web+from aiohttp.test_utils import TestServer+from test_scanner import make_scanner++from aliens_eye.core import control+from aliens_eye.core.control import http_overrule, page_shape, same_page, text_similarity++# --- the comparison ---------------------------------------------------------------+++def profile(username, name="", bio="", extra=""):+ return f"""<html><head><title>{username} {name} - Profile</title>+ <meta property="og:title" content="{name or username}">+ <meta name="description" content="{username} profile picture, followers and posts">+ <style>.x{{color:red}}</style><script>var boot = "{username}-{extra}";</script>+ </head><body class="user-profile"><div class="profile-header">+ <img src="a.png"><img src="b.png"><img src="c.png"><img src="d.png"><img src="e.png"><img src="f.png"></div>+ <p>Follow {username}. Posts and activity timeline. {bio}</p></body></html>"""+++def shape(username, **kw):+ return page_shape(profile(username, **kw), f"https://site.example/u/{username}", username)+++def test_the_same_shell_for_two_usernames_is_the_same_page():+ """Only the username differs, and that is masked out."""+ assert text_similarity(shape("kristoferweston"), shape("zq1b2c3d4e5f6a")) == 1.0+ assert same_page(shape("kristoferweston"), shape("zq1b2c3d4e5f6a"))+++def test_a_real_profile_is_not_the_missing_user_page():+ real = shape("torvalds", name="Linus Torvalds", bio="Creator of Linux and Git. 250k followers. " * 3)+ assert not same_page(real, shape("zq1b2c3d4e5f6a"))+++def test_scripts_and_styles_are_not_compared():+ """A nonce or build id in a script must not make two shells look different."""+ assert text_similarity(shape("a_user", extra="nonce-1"), shape("zq1b2c3d4e5f6a", extra="nonce-2")) == 1.0+++def test_meta_tags_count_even_when_the_body_is_empty():+ """A JavaScript app whose server fills in the real name is still told apart."""+ def app(username, title):+ html = f'<html><head><meta property="og:title" content="{title}"></head><body><div id="root"></div></body></html>'+ return page_shape(html, f"https://app.example/{username}", username)++ assert not same_page(app("torvalds", "Linus Torvalds is on App with 12 posts"), app("zq1b2c3d4e5f6a", "App"))+ assert same_page(app("torvalds", "App"), app("zq1b2c3d4e5f6a", "App"))+++def test_username_matching_ignores_case():+ a = page_shape("<html><body>Profile of TORVALDS</body></html>", "https://x.example/Torvalds", "Torvalds")+ b = page_shape("<html><body>Profile of zq1b2c3d4e5f6a</body></html>", "https://x.example/zq1b2c3d4e5f6a", "zq1b2c3d4e5f6a")+ assert text_similarity(a, b) == 1.0 and a.final_path == b.final_path+++def test_two_empty_pages_are_the_same_page():+ assert same_page(page_shape("", "", "a"), page_shape("", "", "b"))+++def test_a_much_larger_page_is_not_the_same_page_even_with_the_same_words():+ small = page_shape("<html><body>hello</body></html>", "", "a")+ big = page_shape("<html><body>hello</body><script>" + "x" * 5000 + "</script></html>", "", "b")+ assert text_similarity(small, big) == 1.0 and not same_page(small, big)+++def test_control_usernames_are_random_and_ordinary_looking():+ names = {control.control_username() for _ in range(50)}+ assert len(names) == 50+ assert all(name.isalnum() and name.islower() and len(name) == 16 for name in names)++[email protected]("code,expected", [+ (200, None), (301, None), (404, ("Not Found", "http-gone")), (410, ("Not Found", "http-gone")),+ (400, ("Maybe", "http-error")), (403, ("Maybe", "http-error")), (429, ("Maybe", "http-error")),+ (500, ("Maybe", "http-error")), (503, ("Maybe", "http-error")), (999, ("Maybe", "http-error")),+])+def test_http_errors_overrule_a_found(code, expected):+ assert http_overrule(code) == expected+++# --- in a scan ------------------------------------------------------------------------+++async def sites(found_html, not_found_html):+ """Four sites that all return a profile-looking page, for different reasons."""+ app = web.Application()+ hits: list[str] = []++ def page_for(username):+ return found_html.replace("torvalds", username)++ async def shell(request): # the same page for anyone: a JS shell+ hits.append(request.path)+ return web.Response(text=page_for(request.match_info["u"]), content_type="text/html")++ async def honest(request): # a real page for one user, a different one otherwise+ hits.append(request.path)+ if request.match_info["u"] == "torvalds":+ return web.Response(text=found_html, content_type="text/html")+ return web.Response(text=not_found_html, content_type="text/html") # a "soft" 404: status 200++ def with_status(status):+ async def handler(request): # a profile-looking page under an error code+ hits.append(request.path)+ return web.Response(text=page_for(request.match_info["u"]), status=status, content_type="text/html")+ return handler++ app.router.add_get("/shell/{u}", shell)+ app.router.add_get("/honest/{u}", honest)+ for status in (404, 410, 403, 500):+ app.router.add_get(f"/s{status}/{{u}}", with_status(status))+ server = TestServer(app)+ await server.start_server()+ server.hits = hits+ server.base = f"http://{server.host}:{server.port}"+ yield server+ await server.close()+++async def scan(server, tmp_path, logger, names, username="torvalds", **config):+ scanner = make_scanner({n: f"{server.base}/{n}/{{}}" for n in names}, tmp_path, logger)+ for key, value in config.items():+ setattr(scanner.config, key, value)+ results = {r["site"]: r for r in await scanner.scan_all_sites(username)}+ return scanner, results+++async def test_a_site_that_shows_everyone_the_same_page_is_only_a_maybe(sites, tmp_path, logger):+ _, results = await scan(sites, tmp_path, logger, ["shell"])+ assert results["shell"]["status"] == "Maybe"+ assert results["shell"]["confidence"] <= 55+ assert results["shell"]["ai_analysis"]["method"].endswith("-same-as-missing-user")+++async def test_a_site_that_tells_users_apart_keeps_its_found(sites, tmp_path, logger):+ _, results = await scan(sites, tmp_path, logger, ["honest"])+ assert results["honest"]["status"] == "Found"+ assert "same-as-missing-user" not in results["honest"]["ai_analysis"]["method"]+ assert len(sites.hits) == 2 # the profile, and one made-up username+++async def test_without_the_check_the_shell_is_reported_found_as_before(sites, tmp_path, logger):+ _, results = await scan(sites, tmp_path, logger, ["shell"], control_check=False)+ assert results["shell"]["status"] == "Found"+ assert len(sites.hits) == 1+++async def test_the_made_up_username_is_asked_for_once_per_site(sites, tmp_path, logger):+ scanner, _ = await scan(sites, tmp_path, logger, ["shell"])+ await scanner.scan_all_sites("someoneelse")+ await scanner.scan_all_sites("athirdperson")+ assert len(sites.hits) == 4 # three usernames + one control+++async def test_only_a_found_costs_a_second_request(sites, tmp_path, logger):+ _, results = await scan(sites, tmp_path, logger, ["honest"], username="nobodyhere")+ assert results["honest"]["status"] != "Found"+ assert len(sites.hits) == 1++[email protected]("name,status", [("s404", "Not Found"), ("s410", "Not Found"),+ ("s403", "Maybe"), ("s500", "Maybe")])+async def test_a_profile_looking_error_page_is_never_found(sites, tmp_path, logger, name, status):+ """Regression (#22): chatujme.cz answered 404 and was reported Found at 84%."""+ _, off = await scan(sites, tmp_path, logger, [name], control_check=False, retries=0)+ assert off[name]["status"] == status+ assert len(sites.hits) == 1 # settled by the status code alone+++async def test_a_control_that_cannot_be_fetched_changes_nothing(sites, tmp_path, logger):+ scanner = make_scanner({"honest": f"{sites.base}/honest/{{}}"}, tmp_path, logger)+ real_fetch = scanner.fetch++ async def fetch(session, url, config, rate_limiter, log):+ if "torvalds" not in url:+ raise RuntimeError("network fell over")+ return await real_fetch(session, url, config, rate_limiter, log)++ scanner.fetch = fetch+ results = await scanner.scan_all_sites("torvalds")+ assert results[0]["status"] == "Found"diff --git a/tests/test_corpus.py b/tests/test_corpus.pyindex 9ac5f9d..b668c9c 100644--- a/tests/test_corpus.py+++ b/tests/test_corpus.py@@ -473,3 +473,109 @@ def test_manifest_counts_survive_incremental_flushing(tmp_path, monkeypatch, fouassert manifest["records"] == 24assert len(manifest["sites"]) == 12, "manifest must describe the whole corpus"assert ReplayFetcher(root).stats()["records"] == 24+++# --- the control row: what a site shows for a user who doesn't exist ------------------+++def shell(username):+ """A page that looks like a profile whoever you ask for."""+ return (f"<html><head><title>{username} - Profile</title>"+ f'<meta name="description" content="{username} profile picture, followers and posts"></head>'+ f'<body class="user-profile"><div class="profile-header"><img src="a.png"><img src="b.png">'+ f'<img src="c.png"><img src="d.png"><img src="e.png"><img src="f.png"></div>'+ f"<p>Follow {username}. Posts and activity timeline.</p></body></html>")+++def make_control_corpus(tmp_path, monkeypatch, found_html, not_found_html):+ """`honest` tells users apart; `shell` shows everyone the same page."""+ from aliens_eye.corpus import record as record_mod++ rows = [ # site, username, label, kind, (status, body)+ ("honest", "torvalds", 1, None, (200, found_html)),+ ("honest", "a1b2c3d4e5f6g7h8", 0, "random", (404, not_found_html)),+ ("honest", "quietharbor", 0, "plausible", (404, not_found_html)),+ ("shell", "realperson", 1, None, (200, shell("realperson"))),+ ("shell", "z9y8x7w6v5u4t3s2", 0, "random", (200, shell("z9y8x7w6v5u4t3s2"))),+ ("shell", "rapidotter", 0, "plausible", (200, shell("rapidotter"))),+ ]+ url = "https://{}.example/u/{}".format+ network = FakeNetwork({url(site, name): page for site, name, _, _, page in rows})+ monkeypatch.setattr(record_mod, "fetch_url", network)+ store = CorpusStore(tmp_path / "corpus")+ store.init()+ recorder = RecordingFetcher(store, tool_version="test")+ for site, name, label, kind, _ in rows:+ recorder.register(url(site, name), site, name, label, {"negative_kind": kind} if kind else {})++ async def drive():+ for site, name, *_ in rows:+ await recorder(None, url(site, name), ScannerConfig(), None, _NullLogger())++ asyncio.run(drive())+ store.write_manifest({"tool_version": "test", "records": recorder.flush()})+ return tmp_path / "corpus"+++def test_a_corpus_offers_one_recorded_missing_user_per_site(tmp_path, monkeypatch, found_html, not_found_html):+ replay = ReplayFetcher(make_control_corpus(tmp_path, monkeypatch, found_html, not_found_html))+ assert replay.control_for("honest") == ("a1b2c3d4e5f6g7h8", "https://honest.example/u/a1b2c3d4e5f6g7h8")+ assert replay.control_for("shell") == ("z9y8x7w6v5u4t3s2", "https://shell.example/u/z9y8x7w6v5u4t3s2")+ assert replay.control_for("nowhere") is None+++def test_control_rows_can_be_left_out_of_the_test_set(tmp_path, monkeypatch, found_html, not_found_html):+ """A row compared with itself always agrees; it must not count as a result."""+ replay = ReplayFetcher(make_control_corpus(tmp_path, monkeypatch, found_html, not_found_html))+ assert len(replay.eval_jobs()) == 6+ kept = replay.eval_jobs(exclude_controls=True)+ assert sorted(j[2] for j in kept) == ["quietharbor", "rapidotter", "realperson", "torvalds"]+++def run_check(root, **kw):+ from aliens_eye.selfcheck import run_selfcheck++ replay = ReplayFetcher(root)+ detector = Detector()+ detector.load_model(_NullLogger())+ jobs = replay.eval_jobs(exclude_controls=not kw.get("detector_only", False))+ return asyncio.run(run_selfcheck(+ {}, detector, ScannerConfig(), _NullLogger(), report_format="json", fetch=replay, jobs=jobs, **kw,+ ))+++def test_selfcheck_scores_what_a_scan_reports(tmp_path, monkeypatch, found_html, not_found_html, capsys):+ """The shell site is Found for everyone to the detector, and for no one to a scan."""+ root = make_control_corpus(tmp_path, monkeypatch, found_html, not_found_html)+ alone = run_check(root, detector_only=True)+ full = run_check(root)+ capsys.readouterr()+ assert alone["overall"]["fp"] == 2 # both made-up users on the shell site+ assert full["overall"]["fp"] == 0+ assert alone["per_site"]["shell"]["recall"] == 1.0+ assert full["per_site"]["shell"]["recall"] == 0.0 # the real one can't be told apart either+ assert full["per_site"]["honest"]["recall"] == 1.0 # and the honest site loses nothing+++def test_scanner_uses_the_recorded_control_when_replaying(tmp_path, monkeypatch, found_html, not_found_html):+ """Strict replay raises on an unknown URL; the scanner must not invent one."""+ from aliens_eye.core.analyzer import FeatureExtractor+ from aliens_eye.core.scanner import UsernameScanner++ replay = ReplayFetcher(make_control_corpus(tmp_path, monkeypatch, found_html, not_found_html), strict=True)+ config = ScannerConfig(output_dir=tmp_path / "out", fingerprints_path=tmp_path / "fp.json")+ detector = Detector()+ detector.load_model(_NullLogger())+ scanner = UsernameScanner(+ sites_data={"shell": "https://shell.example/u/{}", "honest": "https://honest.example/u/{}"},+ config=config, extractor=FeatureExtractor(), detector=detector,+ fingerprints=FingerprintStore(config.fingerprints_path, read_only=True),+ logger=_NullLogger(), fetch=replay,+ )+ by_site = {}+ for name, site in (("realperson", "shell"), ("torvalds", "honest")):+ scanner.sites_data = {site: f"https://{site}.example/u/{{}}"}+ by_site[site] = asyncio.run(scanner.scan_all_sites(name))[0]+ assert by_site["shell"]["status"] == "Maybe"+ assert by_site["honest"]["status"] == "Found"+ assert replay.misses == []diff --git a/tests/test_scanner.py b/tests/test_scanner.pyindex 244db87..4a2a2a9 100644--- a/tests/test_scanner.py+++ b/tests/test_scanner.py@@ -23,6 +23,9 @@ async def site_server(found_html, not_found_html):app = web.Application()async def alpha(request):+ # A site that knows its users: anyone else gets its "no such user" page.+ if request.match_info["username"] not in {"torvalds", "ghost"}:+ return web.Response(text=not_found_html, status=404, content_type="text/html")return web.Response(text=found_html, content_type="text/html")async def beta(request):