Skip to content

AI powered OSINT engine to discover and map 840+ social media identities across the web

feat: stable aliens_eye.api for building tools on the engine; release 2.4.0

arxhr0071ab44f5930a2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fbff10d..c639667 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,32 @@
# Changelog
+## 2.4.0 (2026-09-18)
+
+### Security
+- **`--correlate` fetched attacker-chosen URLs (SSRF).** Avatar URLs are scraped from the
+ target's own page (`og:image`, JSON-LD, favicon, per-site selectors), so whoever controls
+ that page chooses them, and they were requested with no validation. A hostile profile could
+ point its avatar at a cloud metadata endpoint, an intranet host, or a service on the
+ analyst's own loopback. Avatar URLs are now limited to `http`/`https` and must resolve to
+ public addresses. Upgrade if you use `--correlate`.
+
+### Added
+- **`aliens_eye.api`**, a stable programmatic API (`scan`, `correlate`, `load_sites`) for
+ building other tools on Aliens Eye. It returns plain dicts shaped like the JSON report,
+ prints nothing by default, and never writes into the caller's working directory.
+- `UsernameScanner` accepts an `on_result(username, result)` progress hook (sync or async)
+ and an injectable `console`.
+
+### Fixed
+- Sites whose response headers exceed 8190 bytes (e.g. trakt.tv) failed on every request
+ with `Got more than 8190 bytes when reading`. The limit is now 64 KB.
+- `--watch nan` and `--watch inf` were accepted: NaN slips past a `<= 0` check because every
+ comparison with it is false. Durations must now be positive and finite.
+
+### Changed
+- The MCP server now uses `aliens_eye.api`, and routes console output to stderr for the
+ whole process, not just during scans.
+
## 2.3.0 (2026-09-06)
Evaluation and reproducibility release. No change to detection behaviour: the shipped
diff --git a/README.md b/README.md
index cfd244b..9788f92 100644
--- a/README.md
+++ b/README.md
@@ -207,6 +207,30 @@ Ground truth is split **site-disjoint** into `data/selfcheck.json` (train, 30
sites) and `data/eval_holdout.json` (holdout, 13 sites). Scoring `--split train`
measures fit, not generalization, and will read high.
+## Using it as a library
+
+`aliens_eye.api` is the stable surface for building other tools on Aliens Eye. It
+returns plain dicts shaped like the JSON report and prints nothing by default.
+
+```python
+import asyncio
+from aliens_eye import api
+
+async def main():
+ sites = api.load_sites(exclude_nsfw=True)
+ report = await api.scan(
+ "someone",
+ sites=sites,
+ on_result=lambda user, r: print(r["site"], r["status"]), # optional progress hook
+ )
+ correlation = await api.correlate(report)
+ print(len(correlation["clusters"]), "clusters")
+
+asyncio.run(main())
+```
+
+Everything outside `aliens_eye.api` is internal and may change between minor releases.
+
## Configuration
Aliens Eye merges a JSON config file with CLI flags (CLI wins). Search order without `--config`: `./config.json`, then the platform config dir (e.g. `~/.config/aliens_eye/config.json` on Linux, `%LOCALAPPDATA%\aliens_eye` on Windows).
diff --git a/pyproject.toml b/pyproject.toml
index 25c85ff..38072c1 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "aliens-eye"
-version = "2.3.0"
+version = "2.4.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__.py
index dfbb454..935ae96 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.3.0"
+__version__ = "2.4.0"
diff --git a/src/aliens_eye/api.py b/src/aliens_eye/api.py
new file mode 100644
index 0000000..e4042cd
--- /dev/null
+++ b/src/aliens_eye/api.py
@@ -0,0 +1,145 @@
+"""Stable programmatic API.
+
+Everything else in the package is an implementation detail and may change between
+minor releases. These functions are what other tools should build on: they take
+plain arguments, return plain dicts in the same shape as a saved JSON report, and
+never print to the terminal unless asked to.
+
+ from aliens_eye import api
+
+ sites = api.load_sites(exclude_nsfw=True)
+ report = await api.scan("someone", sites=sites)
+ correlation = await api.correlate(report)
+"""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable
+from pathlib import Path
+from typing import Any
+
+__all__ = ["LEVELS", "ResultHook", "correlate", "load_sites", "scan"]
+
+LEVELS = ("basic", "intermediate", "advanced")
+
+#: ``on_result(username, result)`` -- called once per site as it completes. May be
+#: sync or async. ``result`` is one entry of a report's per-site results.
+ResultHook = Callable[[str, dict[str, Any]], "Awaitable[None] | None"]
+
+
+def _cache_root() -> Path:
+ """Aliens Eye's cache directory -- the same one the CLI uses."""
+ from platformdirs import user_cache_dir
+
+ return Path(user_cache_dir("aliens_eye"))
+
+
+def _quiet_console():
+ from rich.console import Console
+
+ return Console(quiet=True)
+
+
+def load_sites(
+ exclude_nsfw: bool = False,
+ path: Path | None = None,
+) -> dict[str, str]:
+ """The site catalogue as ``{site_name: url_template}``.
+
+ Load it once and pass it to :func:`scan` to know the total up front (for a
+ progress bar) or to filter it before scanning.
+ """
+ from aliens_eye.core.scanner import filter_sites, load_nsfw_sites, load_sites_data
+
+ sites = load_sites_data(Path(path) if path else None)
+ if exclude_nsfw:
+ sites = filter_sites(sites, None, load_nsfw_sites())
+ return sites
+
+
+async def scan(
+ username: str,
+ level: str = "basic",
+ *,
+ sites: dict[str, str] | None = None,
+ use_ml: bool = True,
+ proxy: str | None = None,
+ on_result: ResultHook | None = None,
+ quiet: bool = True,
+) -> dict[str, Any]:
+ """Scan ``username`` across ``sites`` and return the structured report.
+
+ The return value has the same shape as the JSON report the CLI writes, so it
+ can be passed straight to :func:`correlate`. ``sites`` defaults to the full
+ catalogue. ``quiet`` (the default) suppresses all terminal output.
+ """
+ if not isinstance(username, str) or len(username.strip()) < 2:
+ raise ValueError("username must be at least 2 characters")
+ if level not in LEVELS:
+ raise ValueError(f"level must be one of {', '.join(LEVELS)}")
+
+ from aliens_eye.core.analyzer import FeatureExtractor
+ from aliens_eye.core.config import ScannerConfig
+ from aliens_eye.core.detector import Detector
+ from aliens_eye.core.exporter import ResultsExporter
+ from aliens_eye.core.fingerprints import FingerprintStore
+ from aliens_eye.core.scanner import UsernameScanner
+ from aliens_eye.utils.logger import setup_logger
+
+ logger = setup_logger(False)
+ cache = _cache_root()
+ # Scratch space instead of ./results in the caller's cwd; fingerprints shared
+ # with the CLI so signatures learned in one improve the other.
+ config = ScannerConfig(
+ proxy=proxy,
+ output_dir=cache / "api",
+ fingerprints_path=cache / "fingerprints.json",
+ )
+ sites_data = dict(sites) if sites is not None else load_sites()
+
+ detector = Detector()
+ if use_ml:
+ detector.load_model(logger)
+ fingerprints = FingerprintStore(config.fingerprints_path, config.max_fingerprints_per_label)
+ fingerprints.load(logger)
+
+ scanner = UsernameScanner(
+ sites_data=sites_data,
+ config=config,
+ extractor=FeatureExtractor(),
+ detector=detector,
+ fingerprints=fingerprints,
+ logger=logger,
+ on_result=on_result,
+ # Scoped to this scan: the process-wide console is left untouched, so a
+ # quiet library call cannot silence anything else in the same process.
+ console=_quiet_console() if quiet else None,
+ )
+ try:
+ all_results = await scanner.scan_with_variations(username.strip(), level)
+ finally:
+ fingerprints.save()
+ return ResultsExporter(config.output_dir).report_dict(username.strip(), level, all_results)
+
+
+async def correlate(
+ report: dict[str, Any],
+ *,
+ proxy: str | None = None,
+ timeout: float = 10.0,
+ allow_private_avatars: bool = False,
+) -> dict[str, Any]:
+ """Cluster the report's Found/Maybe profiles that look like the same person.
+
+ Avatar URLs are scraped from the pages themselves, so they are fetched only
+ when they resolve to public addresses. ``allow_private_avatars`` lifts that,
+ for deliberately scanning a network you own.
+ """
+ from aliens_eye.core.correlate import correlate_report
+
+ return await correlate_report(
+ report,
+ proxy=proxy,
+ timeout=timeout,
+ allow_private_avatars=allow_private_avatars,
+ )
diff --git a/src/aliens_eye/core/scanner.py b/src/aliens_eye/core/scanner.py
index 6e9ef31..c6de34a 100644
--- a/src/aliens_eye/core/scanner.py
+++ b/src/aliens_eye/core/scanner.py
@@ -163,11 +163,17 @@ class UsernameScanner:
browser_fallback: BrowserFallback | None = None,
checkpoint=None,
fetch=fetch_url,
+ on_result=None,
+ console=None,
) -> None:
# ``fetch`` is the single seam between the scanner and the network.
# Swapping it for aliens_eye.corpus.replay.ReplayFetcher runs the whole
# pipeline off a frozen corpus with every downstream stage unchanged.
self.fetch = fetch
+ # Optional ``on_result(username, result)`` progress hook, called once per
+ # site as it completes. May be sync or async. Used by callers that are not
+ # a terminal -- a web UI streaming progress, for instance.
+ self.on_result = on_result
self.sites_data = sites_data
self.config = config
self.extractor = extractor
@@ -176,7 +182,9 @@ class UsernameScanner:
self.logger = logger
self.browser_fallback = browser_fallback
self.checkpoint = checkpoint
- self.console = get_console()
+ # Injectable, like ScanView's, so a library caller can silence one scan
+ # without touching the process-wide console.
+ self.console = console or get_console()
self.results_dir = config.output_dir
self.results_dir.mkdir(parents=True, exist_ok=True)
@@ -295,6 +303,13 @@ class UsernameScanner:
await self.checkpoint.record(username, site, result)
except Exception as exc: # noqa: BLE001 - checkpoint is best-effort
self.logger.debug("Checkpoint write failed for %s: %s", site, exc)
+ if self.on_result is not None:
+ try:
+ outcome = self.on_result(username, result)
+ if asyncio.iscoroutine(outcome):
+ await outcome
+ except Exception as exc: # noqa: BLE001 - a progress hook must never kill a scan
+ self.logger.debug("on_result hook failed for %s: %s", site, exc)
found = sum(1 for r in results if r["status"] == "Found")
view.advance(found)
queue.task_done()
diff --git a/src/aliens_eye/mcp_server.py b/src/aliens_eye/mcp_server.py
index 103397a..59a140e 100644
--- a/src/aliens_eye/mcp_server.py
+++ b/src/aliens_eye/mcp_server.py
@@ -16,34 +16,16 @@ from typing import Any
async def _run_scan(username: str, level: str, sites: str | None, no_ml: bool) -> dict[str, Any]:
- from aliens_eye.core.analyzer import FeatureExtractor
- from aliens_eye.core.config import ScannerConfig
- from aliens_eye.core.detector import Detector
- from aliens_eye.core.exporter import ResultsExporter
- from aliens_eye.core.fingerprints import FingerprintStore
- from aliens_eye.core.scanner import UsernameScanner, load_sites_data
- from aliens_eye.utils.console import set_plain
- from aliens_eye.utils.logger import setup_logger
-
- set_plain(True, stderr=True)
- logger = setup_logger(False)
- config = ScannerConfig()
- sites_data = load_sites_data(Path(sites) if sites else None)
- detector = Detector()
- if not no_ml:
- detector.load_model(logger)
- extractor = FeatureExtractor()
- fingerprints = FingerprintStore(config.fingerprints_path, config.max_fingerprints_per_label)
- fingerprints.load(logger)
- scanner = UsernameScanner(
- sites_data=sites_data, config=config, extractor=extractor,
- detector=detector, fingerprints=fingerprints, logger=logger,
+ from aliens_eye import api
+
+ # stdio carries the MCP protocol, so nothing may reach stdout.
+ return await api.scan(
+ username,
+ level,
+ sites=api.load_sites(path=Path(sites) if sites else None),
+ use_ml=not no_ml,
+ quiet=True,
)
- try:
- all_results = await scanner.scan_with_variations(username, level)
- finally:
- fingerprints.save()
- return ResultsExporter(config.output_dir).report_dict(username, level, all_results)
async def serve(args) -> None:
@@ -57,6 +39,12 @@ async def serve(args) -> None:
)
return
+ from aliens_eye.utils.console import set_plain
+
+ # stdout carries the MCP protocol for the life of the process; route any
+ # stray console output to stderr so nothing can corrupt the stream.
+ set_plain(True, stderr=True)
+
sites = getattr(args, "sites", None)
no_ml = getattr(args, "no_ml", False)
mcp = FastMCP("aliens-eye")
@@ -73,9 +61,9 @@ async def serve(args) -> None:
@mcp.tool()
async def correlate(report: dict[str, Any]) -> dict[str, Any]:
"""Cluster the profiles in a scan report that look like the same person."""
- from aliens_eye.core.correlate import correlate_report
+ from aliens_eye import api
- return await correlate_report(report)
+ return await api.correlate(report)
@mcp.tool()
def read_report(path: str) -> dict[str, Any]:
diff --git a/tests/test_api.py b/tests/test_api.py
new file mode 100644
index 0000000..7d89351
--- /dev/null
+++ b/tests/test_api.py
@@ -0,0 +1,135 @@
+"""The public programmatic API: shape, progress hook, isolation and delegation."""
+
+import pytest
+from test_scanner import server_sites, site_server # noqa: F401 - fixture re-export
+
+from aliens_eye import api
+
+
[email protected](autouse=True)
+def isolated_cache(tmp_path, monkeypatch):
+ """Keep every test out of the real user cache."""
+ cache = tmp_path / "cache"
+ monkeypatch.setattr(api, "_cache_root", lambda: cache)
+ return cache
+
+
+async def test_scan_returns_a_report_shaped_dict(site_server): # noqa: F811
+ report = await api.scan("torvalds", sites=server_sites(site_server))
+
+ assert report["scan_summary"]["base_username"] == "torvalds"
+ assert report["scan_summary"]["scan_level"] == "basic"
+ sites = report["variations"]["torvalds"]["sites"]
+ assert sites["alpha"]["status"] == "Found"
+ assert sites["beta"]["status"] == "Not Found"
+
+
+async def test_on_result_is_called_once_per_site(site_server): # noqa: F811
+ seen = []
+ await api.scan(
+ "torvalds",
+ sites=server_sites(site_server),
+ on_result=lambda username, result: seen.append((username, result["site"])),
+ )
+ assert sorted(seen) == [("torvalds", "alpha"), ("torvalds", "beta")]
+
+
+async def test_async_on_result_is_awaited(site_server): # noqa: F811
+ seen = []
+
+ async def hook(username, result):
+ seen.append(result["site"])
+
+ await api.scan("torvalds", sites=server_sites(site_server), on_result=hook)
+ assert sorted(seen) == ["alpha", "beta"]
+
+
+async def test_a_failing_hook_does_not_kill_the_scan(site_server): # noqa: F811
+ def hook(username, result):
+ raise RuntimeError("UI went away")
+
+ report = await api.scan("torvalds", sites=server_sites(site_server), on_result=hook)
+ assert report["variations"]["torvalds"]["sites"]["alpha"]["status"] == "Found"
+
+
+async def test_scan_does_not_write_into_the_callers_cwd(site_server, tmp_path, monkeypatch): # noqa: F811
+ """A library call must not litter ./results wherever the caller happens to be."""
+ work = tmp_path / "work"
+ work.mkdir()
+ monkeypatch.chdir(work)
+ await api.scan("torvalds", sites=server_sites(site_server))
+ assert not (work / "results").exists()
+
+
+async def test_quiet_scan_prints_nothing(site_server, capsys): # noqa: F811
+ await api.scan("torvalds", sites=server_sites(site_server))
+ captured = capsys.readouterr()
+ assert captured.out == ""
+ assert captured.err == ""
+
+
[email protected]("username", ["", " ", "a", None])
+async def test_scan_rejects_bad_usernames(username):
+ with pytest.raises(ValueError, match="username"):
+ await api.scan(username, sites={})
+
+
+async def test_scan_rejects_unknown_levels():
+ with pytest.raises(ValueError, match="level"):
+ await api.scan("torvalds", "extreme", sites={})
+
+
+async def test_correlate_passes_the_private_avatar_flag_through(monkeypatch):
+ captured = {}
+
+ async def fake_correlate_report(report, **kwargs):
+ captured.update(kwargs)
+ return {"clusters": []}
+
+ import aliens_eye.core.correlate as correlate_mod
+
+ monkeypatch.setattr(correlate_mod, "correlate_report", fake_correlate_report)
+ await api.correlate({"variations": {}})
+ assert captured["allow_private_avatars"] is False
+ await api.correlate({"variations": {}}, allow_private_avatars=True)
+ assert captured["allow_private_avatars"] is True
+
+
+def test_load_sites_can_exclude_nsfw():
+ from aliens_eye.core.scanner import load_nsfw_sites
+
+ everything = api.load_sites()
+ safe = api.load_sites(exclude_nsfw=True)
+ nsfw = set(load_nsfw_sites())
+ assert len(safe) < len(everything)
+ assert not (set(safe) & nsfw)
+
+
+async def test_mcp_scan_delegates_to_the_api(monkeypatch):
+ """The MCP server and the API must not drift apart: one implementation."""
+ from aliens_eye import mcp_server
+
+ calls = {}
+
+ async def fake_scan(username, level, **kwargs):
+ calls.update(username=username, level=level, **kwargs)
+ return {"ok": True}
+
+ monkeypatch.setattr(api, "scan", fake_scan)
+ result = await mcp_server._run_scan("torvalds", "basic", None, no_ml=True)
+ assert result == {"ok": True}
+ assert calls["username"] == "torvalds"
+ assert calls["use_ml"] is False
+ assert calls["quiet"] is True
+
+
+async def test_quiet_scan_does_not_silence_the_global_console(site_server): # noqa: F811
+ """Regression: an early version flipped the process-wide console to quiet,
+ so one library call silenced every later Aliens Eye print in the process."""
+ from aliens_eye.utils.console import get_console
+
+ before = get_console()
+ await api.scan("torvalds", sites=server_sites(site_server))
+ after = get_console()
+ assert after is before
+ assert not after.quiet