Skip to content

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

feat: Implement results exporter for scan results in JSON, CSV, and HTML formats

arxhr0078d18f6df3530
diff --git a/README.md b/README.md
index a9e9b84..32a9932 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,4 @@
-<p align="center">
- <img src="https://raw.githubusercontent.com/arxhr007/Aliens_eye/main/photos/logo.png" width="450" height="400" alt="AI-OSINT Username Scanner Logo"/>
-</p>
+![Aliens Eye Logo](https://raw.githubusercontent.com/arxhr007/Aliens_eye/main/photos/logo.png)
# AI-OSINT Username Scanner
@@ -15,150 +13,183 @@
<a href="https://github.com/BLINKING-IDIOT/Aliens_eye/issues"><img alt="Issues" src="https://img.shields.io/github/issues/BLINKING-IDIOT/Aliens_eye?color=purple&style=for-the-badge"></a>
</p>
-## 🧠 AI-Enhanced Detection
+## Highlights
-The AI-OSINT Username Scanner leverages advanced artificial intelligence techniques to find usernames across the web with unprecedented accuracy. Unlike traditional scanners that rely solely on HTTP response codes, this tool employs sophisticated analysis methods:
+- Async scanning across a large platform catalog from sites.json
+- Feature extraction with selectolax instead of fragile regex
+- Heuristic detection with confidence scoring
+- JSON, CSV, and HTML reports
+- Playwright fallback for hard pages
-- **AI-Powered Detection Engine**: Analyzes multiple factors to determine profile existence with up to 40% improved accuracy
-- **Confidence Scoring System**: Quantifies detection certainty from 0-100% for each result
-- **Pattern Recognition**: Learns from scanning patterns to continuously improve detection accuracy
-- **Content Analysis**: Intelligently examines page content, DOM structure, and metadata
-- **Smart URL Analysis**: Evaluates URL structures and redirects for more accurate results
+## Requirements
-## ✨ Key Features
+- Python 3.10+
+- Required packages: aiohttp, selectolax, playwright
+- Internet connection
-- **Scan 840+ Online Platforms**: Extensive coverage across social media, forums, and websites
-- **Intelligent Username Variations**: Automatically generates and scans common username variations
-- **Three Scan Levels**: Basic, Intermediate, and Advanced options to suit your needs
-- **Concurrent Connection Management**: Optimized for speed with configurable connection limits
-- **Detailed Reporting**: Comprehensive JSON reports with full analysis data
-- **Color-Coded Results**: Intuitive visual status indicators for immediate pattern recognition
-- **Saved Results Viewer**: Built-in capability to analyze previous scan results
+## Install
-## πŸ“‹ Requirements
+### Quick install (Linux/Termux) β€” One-liner
-- Python 3.6+
-- Required packages: aiohttp, asyncio
-- Internet connection
+Copy-paste this into your terminal:
-## πŸš€ Installation
+```bash
+bash <(curl -s https://pastebin.com/raw/XXXXX)
+```
-### Option 1: Quick Install Script
+Or:
```bash
-curl -s https://pastebin.com/raw/hkBtt6rc | tr -d '\r' | bash
+curl -s https://pastebin.com/raw/XXXXX | bash
```
-### Option 2: Manual Installation
+### Manual install
```bash
# Clone the repository
git clone https://github.com/arxhr007/Aliens_eye.git
-
-# Navigate to the directory
cd Aliens_eye
# Install dependencies
pip install -r requirements.txt
-# Make the script executable
-chmod +x aliens_eye.py
+# Install Playwright browser binaries
+playwright install
+```
+
+## Run by platform
+### Windows (PowerShell)
+
+```powershell
+git clone https://github.com/arxhr007/Aliens_eye.git
+cd Aliens_eye
+py -m pip install -r requirements.txt
+py .\aliens_eye.py username
```
-## πŸ’» Usage
+If `py` is unavailable, use:
-### Basic Usage
+```powershell
+python .\aliens_eye.py username
+```
-```bash
-# Run with interactive prompts
-ailens_eye
+### Linux
-# Scan a single username
-ailens_eye username
+Run from source:
-# Scan multiple usernames
-ailens_eye username1 username2 username3
+```bash
+git clone https://github.com/arxhr007/Aliens_eye.git
+cd Aliens_eye
+python3 -m pip install -r requirements.txt
+python3 aliens_eye.py username
```
-### Advanced Options
+Or install system-wide with the installer script:
```bash
-# Set scan level explicitly
-ailens_eye username -l advanced
+bash install.sh
+aliens_eye username
+```
-# Limit concurrent connections (useful for slower connections)
-ailens_eye username -c 30
+### iOS (iSH shell)
-# Enable verbose output for debugging
-ailens_eye username -v
+In iSH, install Python and run from source:
-# View results from a previous scan
-ailens_eye -r results/username_advanced_20250514_120000.json
+```sh
+apk add python3 py3-pip git
+git clone https://github.com/arxhr007/Aliens_eye.git
+cd Aliens_eye
+python3 -m pip install -r requirements.txt
+python3 aliens_eye.py username
```
-## πŸ” Understanding Scan Results
+Note: some websites may block requests from iOS shell environments more aggressively than desktop Linux.
+
+## Configuration
+
+Aliens Eye reads a JSON config file and merges it with CLI flags. CLI flags always win.
+
+Search order when no --config is provided:
+- ./config.json
+- <script_dir>/config.json
+- /etc/aliens_eye/config.json
+- /usr/local/etc/aliens_eye/config.json
+- /data/data/com.termux/files/usr/etc/aliens_eye/config.json
+
+Example config.json:
+
+```json
+{
+ "concurrent": 50,
+ "timeout": 10.0,
+ "max_content_bytes": 100000,
+ "retries": 2,
+ "backoff_base": 0.5,
+ "backoff_cap": 8.0,
+ "jitter": 0.2,
+ "rate_limit_delay": 0.2,
+ "fingerprints_path": "cache/fingerprints.json",
+ "output_dir": "results",
+ "output_formats": ["json", "csv", "html"],
+ "use_playwright": false,
+ "max_fingerprints_per_label": 50,
+ "level": "basic"
+}
+```
-Results are displayed with intuitive color-coding:
+## Usage
-- 🟒 **Green (Found)**: High confidence that the profile exists
-- 🟑 **Yellow (Maybe)**: Profile might exist, but confidence is moderate
-- πŸ”΄ **Red (Not Found)**: High confidence that the profile doesn't exist
+```bash
+# Interactive prompts
+aliens_eye
-Each result includes:
-- Site name
-- Status (Found/Maybe/Not Found)
-- Confidence percentage (0-100%)
-- HTTP status code
-- URL of the detected profile
-- Response time
+# Single username
+aliens_eye username
-## πŸ“Š AI Analysis Methodology
+# Multiple usernames
+aliens_eye username1 username2
-The tool employs a sophisticated multi-factor analysis approach:
+# Advanced scan level
+aliens_eye username -l advanced
-1. **Content Analysis**: Searches for positive and negative keyword patterns
-2. **HTTP Status Evaluation**: Interprets HTTP response codes with context
-3. **DOM Structure Analysis**: Examines page elements for profile indicators
-4. **URL Structure Evaluation**: Analyzes URL patterns and redirects
-5. **Metadata Inspection**: Examines meta tags and titles for username presence
-6. **Response Time Analysis**: Considers timing patterns characteristic of profile existence
-7. **Pattern Learning**: Uses historical data to improve detection accuracy
+# Limit concurrency
+aliens_eye username -c 30
-## πŸ“„ Scan Levels Explained
+# Enable verbose logs
+aliens_eye username -v
-- **Basic**: Scans only the exact username as entered
-- **Intermediate**: Adds common variations like underscores, dots, and numbers
- - Examples: `username_`, `_username`, `username.`, `username123`
-- **Advanced**: Adds common prefixes and suffixes used across platforms
- - Examples: `real_username`, `official_username`, `username_official`
+# Use a custom config file
+aliens_eye --config config.json username
-## πŸ“± Platform Support
+# Export CSV + HTML in addition to JSON
+aliens_eye username --format json,csv,html --output results
-- Linux (All distributions)
-- macOS
-- Windows (via Python)
-- Android (via Termux)
+# Enable Playwright fallback for Maybe results
+aliens_eye username --playwright
-## ⚠️ Disclaimer
+# View results from a previous scan
+aliens_eye -r results/username_advanced_20250514_120000.json
+```
-This tool is developed for educational purposes and legitimate OSINT research only. Users are responsible for complying with applicable laws and terms of service of websites. The developers assume no liability for misuse of this software.
+If you run from source, call:
-## πŸ”— Links
+```bash
+python aliens_eye.py username
+```
-- [Report Bug](https://github.com/arxhr007/AIUsernameScanner/issues)
-- [Request Feature](https://github.com/arxhr007/AIUsernameScanner/issues)
-- [Documentation](https://github.com/arxhr007/AIUsernameScanner/wiki)
+## Outputs
----
+Results are saved to the output directory with timestamped filenames:
-<p align="center">Made with ❀️ by <a href="https://github.com/arxhr007">arxhr007</a></p>
+- JSON: username_level_YYYYMMDD_HHMMSS.json
+- CSV: username_level_YYYYMMDD_HHMMSS.csv
+- HTML: username_level_YYYYMMDD_HHMMSS.html
-<p align="center">If you find this project helpful, please consider giving it a star ⭐</p>
+## Architecture
-<p align="center"><img src="https://raw.githubusercontent.com/arxhr007/Aliens_eye/refs/heads/main/photos/photo.png" width="700" alt="AI-OSINT Username Scanner Screenshot"/></p>
+Core modules live under core/ (scanner, detector, analyzer, http, exporter). Utilities are in utils/. For internals and flowcharts, see WORKING.md.
-# Also checkout:
+## Disclaimer
-<a href="https://github.com/arxhr007/wifistrike" target="blank"><img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=arxhr007&repo=wifistrike&show_icons=true&theme=chartreuse-dark"></a>
-<a href="https://github.com/arxhr007/Malware-Sandbox-Evasion" target="blank"><img align="center" src="https://github-readme-stats.vercel.app/api/pin/?username=arxhr007&repo=Malware-Sandbox-Evasion&show_icons=true&theme=chartreuse-dark"></a>
+This tool is for educational purposes and legitimate OSINT research only. You are responsible for complying with laws and site terms of service.
diff --git a/WORKING.md b/WORKING.md
new file mode 100644
index 0000000..b6ee36a
--- /dev/null
+++ b/WORKING.md
@@ -0,0 +1,99 @@
+# Aliens Eye Working Notes
+
+This document explains the runtime flow, data pipeline, and internal modules.
+
+## High-level flow
+
+```mermaid
+flowchart TD
+ A[Start] --> B[Load config and CLI args]
+ B --> C{Read results file?}
+ C -->|Yes| D[Load JSON report]
+ C -->|No| E[Load sites.json]
+ E --> F[Generate username variations]
+ F --> G[Queue workers]
+ G --> H[Fetch URL with retries]
+ H --> I[Extract features with selectolax]
+ I --> J[Fingerprint scoring]
+ J --> K[Detect via heuristics]
+ K --> L{Maybe + Playwright enabled?}
+ L -->|Yes| M[Render page and re-extract]
+ L -->|No| N[Record result]
+ M --> N
+ N --> O[Update fingerprints]
+ O --> P[Write JSON/CSV/HTML reports]
+ P --> Q[Done]
+```
+
+## Module map
+
+- core/analyzer.py: HTML parsing and feature extraction (selectolax)
+- core/http.py: Fetch with retries, backoff, and response size caps
+- core/rate_limit.py: Per-domain delay control
+- core/detector.py: Heuristic scoring and status selection
+- core/fingerprints.py: Persisted match fingerprints by site
+- core/scanner.py: Async queue workers and orchestration
+- core/exporter.py: JSON/CSV/HTML report generation
+
+## Feature extraction
+
+Signals include:
+- HTTP status buckets (200, 3xx, 4xx, 5xx)
+- Presence of username in URL path
+- Auth-related path patterns
+- Positive and error keyword counts (content and meta)
+- DOM counts (img, form, input, profile/error class hints)
+- Response time and content length
+- Redirect count
+- Fingerprint match counts
+
+These are stored as a consistent feature schema and used for heuristic scoring.
+
+## Detection logic
+
+### Heuristic path
+
+If no model is loaded, a weighted score is computed from the features. Thresholds map to:
+- Found
+- Not Found
+- Maybe
+
+## Dataset logging
+
+Dataset logging was removed to keep the project focused on live heuristic detection.
+
+## Fingerprints
+
+Fingerprints store compact signatures of known Found and Not Found pages per site:
+- title hash
+- meta hash
+- DOM signature
+- server header
+
+During detection, similarity scores are added as features to reduce false positives.
+
+## Retry and rate limiting
+
+- Retryable statuses: 408, 429, 500, 502, 503, 504
+- Backoff: exponential with jitter and optional Retry-After handling
+- Per-domain delay: prevents hammering a single host
+
+## Playwright fallback (optional)
+
+If enabled, Playwright is used only when a result is Maybe. The rendered DOM is re-parsed and can upgrade confidence.
+
+## Output pipeline
+
+Reports are timestamped and written to:
+- JSON (full detail)
+- CSV (flat table)
+- HTML (shareable summary)
+
+## Config precedence
+
+```mermaid
+flowchart TD
+ A[Defaults] --> B[config.json]
+ B --> C[CLI flags]
+ C --> D[Final runtime config]
+```
diff --git a/aliens_eye.py b/aliens_eye.py
index 09140bc..8c2204c 100644
--- a/aliens_eye.py
+++ b/aliens_eye.py
@@ -1,682 +1,468 @@
#!/usr/bin/python3
-import aiohttp
import asyncio
import json
import sys
-import time
-import logging
-from pathlib import Path
from argparse import ArgumentParser
-from datetime import datetime
-from typing import Dict, List, Any
-import re
-from urllib.parse import urlparse
-COLORS = {
- "red": "\033[31m",
- "green": "\033[32m",
- "yellow": "\033[33m",
- "blue": "\033[36m",
- "purple": "\033[35m",
- "white": "\033[37m",
- "reset": "\033[0m"
-}
-logger = logging.getLogger("username_scanner")
-class AIUsernameScanner:
- def __init__(self):
- self.headers = {
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/115.0.0.0 Safari/537.36",
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
- "Accept-Encoding": "gzip, deflate, br",
- "Accept-Language": "en-US,en;q=0.5",
- "Connection": "keep-alive",
- "DNT": "1",
- "Upgrade-Insecure-Requests": "1",
- }
- self.error_keywords = [
- "not found", "doesn't exist", "didn't find", "does not exist", "something went wrong", "no such user",
- "user not found", "cannot find", "can't find", "not exist", "profile not found", "account does not exist",
- "username not found", "no user found", "no results found", "no such username", "isn't available",
- "that content is unavailable", "page not found", "404", "404 error", "404 not found", "error", "sorry", "oops", "unavailable",
- "account suspended", "invalid username", "account not found", "account terminated", "account disabled",
- "user doesn't have an account", "this account doesn't exist", "page was not found"
- ]
- self.positive_keywords = [
- "follow", "subscribe", "like", "share", "following", "followers", "profile", "user", "posts",
- "photos", "bio", "status", "tweets", "joined", "member since", "online", "verified", "active",
- "comments", "uploads", "reviews", "friends", "connections", "activity", "timeline"
- ]
- self.meta_keywords = [
- "profile picture", "profile image", "avatar", "user page", "username", "user profile",
- "account info", "account information", "user information"
- ]
- self.auth_patterns = [
- "/login", "/signin", "/register", "/join", "auth", "oauth", "authenticate", "account/login",
- "session/new", "user/login", "members/login"
- ]
- self.sites_data = self._load_sites_data()
- self.results_dir = Path("results")
- self.results_dir.mkdir(exist_ok=True)
- self.pattern_cache = {}
- def generate_username_variations(self, username: str, level: str) -> List[str]:
- """Generate username variations based on scan level."""
- variations = [username]
- if level == "basic":
- return variations
- if level == "intermediate" or level == "advanced":
- variations.extend([
- f"{username}_",
- f"_{username}",
- f"{username}.",
- f".{username}",
- f"{username.replace(' ', '_')}",
- f"{username.replace(' ', '.')}",
- f"{username}1",
- f"{username}123",
- f"{username}007",
- f"{username}098",
- f"{username}x",
- f"__{username}",
- f"__{username}__",
- ])
- if level == "advanced":
- prefixes = ["real", "official", "the", "its", "im", "actual", "true",
- "mr", "ms", "dr", "iam", "thisis", "hey", "yo",
- "only", "itz", "iamthe", "theonly"
-]
- suffixes = [ "official", "real", "account", "verified", "original", "tv", "here",
- "live", "online", "page", "world", "spot", "media",
- "inc", "group", "team", "zone", "plus", "today"]
- for prefix in prefixes:
- variations.append(f"{prefix}{username}")
- variations.append(f"{prefix}_{username}")
- variations.append(f"{prefix}.{username}")
- for suffix in suffixes:
- variations.append(f"{username}{suffix}")
- variations.append(f"{username}_{suffix}")
- variations.append(f"{username}.{suffix}")
- return list(dict.fromkeys(variations))
- def _load_sites_data(self) -> Dict[str, str]:
- """Load sites data from JSON file with fallback paths."""
- possible_paths = [
- Path("/usr/local/bin/sites.json"),
- Path("/data/data/com.termux/files/usr/bin/sites.json"),
- Path("sites.json")
- ]
- for path in possible_paths:
- try:
- with open(path) as f:
- logger.info(f"Loaded sites data from {path}")
- return json.load(f)
- except FileNotFoundError:
- continue
- logger.error("Could not find sites.json file. Make sure it exists in one of the expected locations.")
- return {}
- def display_banner(self):
- """Display the ASCII art banner with colors."""
- r, g, y, b, p, w = COLORS["red"], COLORS["green"], COLORS["yellow"], COLORS["blue"], COLORS["purple"], COLORS["white"]
- banner = f"""{y}
-"{b}New AI detection
- feature improves
- accuracy by 40%{y}" "{b}Scans {len(self.sites_data)} websites{y}"
- {r}β˜… {w}\\{y} _.-'~~~~'-._ {w} /{y}
- {b}☾{y} .-~ {g}\\__/{p} \\__/{y} ~-. .
- .-~ {g} ({r}oo{g}) {p} ({r}oo{p}) {y}~-.
- (_____{g}//~~\\\\{p}//~~\\\\{y}______) {p}β˜†{y}
- _.-~` `~-._
- /{p}O{b}={g}O{r}={y}O{w}={p}O{b}={g}O{r}={y}O{w}={g}O{r}={y}={g}O{r}={y}O{w}O{w}={p}O{b}={g}O{r}={g}O{r}={y}O{w}={y}O{w}={p}O{b}={g}O{r}={y}O{y}\\ {w}✴
-{y} \\___________________________________/
- \\x {w}x{y} x {w}x{y} x {w}x{y} x/ {b}✫{y}
- . {w}*{y} \\{w}x{y}_{w}x{y}_{w}x{y}_{w}x{y}_{w}x{y}_{w}x{y}/
- {r}AI-POWERED{g}
- ___ __ _________ ___ ____
- / _ | / / / _/ __/ |/ ( )/ __/
- / __ |/ /___/ // _// /|/_\\ \\
-/_/ |_/____/___/___/_/|_/ /___/
-{b}
+from pathlib import Path
+from typing import Any
+
+SCRIPT_DIR = Path(__file__).resolve().parent
+LIB_DIR = SCRIPT_DIR / "aliens_eye_lib"
+if LIB_DIR.exists():
+ sys.path.insert(0, str(LIB_DIR))
+else:
+ sys.path.insert(0, str(SCRIPT_DIR))
+
+from core.analyzer import FeatureExtractor
+from core.browser import BrowserFallback
+from core.config import DEFAULT_USER_AGENT, ScannerConfig
+from core.detector import Detector
+from core.exporter import ResultsExporter
+from core.fingerprints import FingerprintStore
+from core.scanner import UsernameScanner, load_sites_data
+from utils.colors import COLORS
+from utils.logger import setup_logger
+
+
+def display_banner(site_count: int) -> None:
+ banner = f"""
+ {COLORS['green']} ___ __ _________ ___ ____
+ {COLORS['green']} / _ | / / / _/ __/ |/ ( )/ __/
+{COLORS['green']} / __ |/ /___/ // _// /|/_\\ \\
+{COLORS['green']}/_/ |_/____/___/___/_/|_/ /___/
+{COLORS['blue']}
________ ________
- {b}/ ____/\\ \\/ / ____/ {r} _ __{w}__ __
- {b}/ __/ \\ / __/ {r} | | / /{w} // /
- {b}/ /___ / / /___ {r}| | / / {w}// /
-{b}/_____/ /_/_____/ {r} | |/ /{w}__ __/
- {r} |___/ {w} /_/
+ {COLORS['blue']}/ ____/\\ \\/ / ____/ {COLORS['red']} _ __{COLORS['white']}__ __
+ {COLORS['blue']}/ __/ \\ / __/ {COLORS['red']} | | / /{COLORS['white']} // /
+ {COLORS['blue']}/ /___ / / /___ {COLORS['red']}| | / / {COLORS['white']}// /
+{COLORS['blue']}/_____/ /_/_____/ {COLORS['red']} | |/ /{COLORS['white']}__ __/
+ {COLORS['red']} |___/ {COLORS['white']} /_/
-{g}by {y}arxhr007 {COLORS["reset"]}
+{COLORS['green']}by {COLORS['yellow']}arxhr007 {COLORS["reset"]}
+{COLORS['yellow']}AI-OSINT USERNAME SCANNER{COLORS['reset']}
+{COLORS['blue']}Advanced username discovery with ML-ready signals{COLORS['reset']}
+{COLORS['purple']}Scanning {site_count} websites{COLORS['reset']}
"""
- print(banner)
- print(f"{COLORS['red']}NOTE: For educational purposes only!{COLORS['reset']}\n")
- async def check_internet(self) -> bool:
- """Check if internet connection is available."""
+ print(banner)
+ print(f"{COLORS['red']}NOTE: For educational purposes only!{COLORS['reset']}\n")
+
+
+def build_parser() -> ArgumentParser:
+ parser = ArgumentParser(
+ description="AI-Enhanced Username Scanner - Find usernames across social media platforms"
+ )
+ parser.add_argument("username", nargs="*", help="Usernames to scan")
+ parser.add_argument("-r", "--read", help="Path to JSON file to read and display")
+ parser.add_argument("-c", "--concurrent", type=int, help="Max concurrent connections")
+ parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output")
+ parser.add_argument(
+ "-l",
+ "--level",
+ choices=["basic", "intermediate", "advanced"],
+ help="Scan level",
+ )
+ parser.add_argument("--timeout", type=float, help="Request timeout in seconds")
+ parser.add_argument("--retries", type=int, help="Retry count for failed requests")
+ parser.add_argument("--backoff-base", type=float, help="Base backoff in seconds")
+ parser.add_argument("--backoff-cap", type=float, help="Max backoff in seconds")
+ parser.add_argument("--rate-limit", type=float, help="Min delay per domain")
+ parser.add_argument("--max-bytes", type=int, help="Max response bytes to parse")
+ parser.add_argument("--config", type=str, help="Path to config JSON file")
+ parser.add_argument(
+ "--format",
+ type=str,
+ default=None,
+ help="Output formats: json,csv,html,all",
+ )
+ parser.add_argument(
+ "--output", type=str, default=None, help="Output directory"
+ )
+ parser.add_argument(
+ "--playwright",
+ action="store_true",
+ help="Enable Playwright fallback for Maybe results",
+ )
+ return parser
+
+
+def parse_formats(value: str) -> list[str]:
+ formats = [item.strip().lower() for item in value.split(",") if item.strip()]
+ if not formats:
+ return ["json"]
+ if "all" in formats:
+ return ["all"]
+ return formats
+
+
+def parse_formats_value(value: Any) -> list[str]:
+ if value is None:
+ return ["json"]
+ if isinstance(value, list):
+ return parse_formats(",".join(str(item) for item in value))
+ return parse_formats(str(value))
+
+
+def prompt_yes_no(prompt: str, default: bool) -> bool:
+ suffix = "Y/n" if default else "y/N"
+ answer = input(f"{COLORS['green']}{prompt} ({suffix}): {COLORS['yellow']}").strip().lower()
+ if not answer:
+ return default
+ return answer in {"y", "yes"}
+
+
+def prompt_int(prompt: str, default: int | None, min_value: int | None = None) -> int | None:
+ default_text = "" if default is None else str(default)
+ while True:
+ value = input(
+ f"{COLORS['green']}{prompt} [{default_text}]: {COLORS['yellow']}"
+ ).strip()
+ if not value:
+ return default
try:
- async with aiohttp.ClientSession(headers=self.headers) as session:
- async with session.get("https://www.google.com/", timeout=5) as response:
- return response.status == 200
- except Exception as e:
- logger.error(f"Internet connection check failed: {e}")
- return False
- def extract_meta_tags(self, content: str) -> List[str]:
- """Extract metadata from HTML content."""
- meta_tags = []
- meta_pattern = re.compile(r'<meta[^>]*content=["\'](.*?)["\'][^>]*>', re.IGNORECASE)
- for match in meta_pattern.finditer(content):
- meta_tags.append(match.group(1))
- title_match = re.search(r'<title>(.*?)</title>', content, re.IGNORECASE)
- if title_match:
- meta_tags.append(title_match.group(1))
- og_title = re.search(r'<meta[^>]*property=["\'](og:title)["\'][^>]*content=["\'](.*?)["\']', content, re.IGNORECASE)
- if og_title:
- meta_tags.append(og_title.group(2))
- og_desc = re.search(r'<meta[^>]*property=["\'](og:description)["\'][^>]*content=["\'](.*?)["\']', content, re.IGNORECASE)
- if og_desc:
- meta_tags.append(og_desc.group(2))
- return meta_tags
- def extract_dom_structure(self, content: str) -> Dict[str, int]:
- """Extract basic DOM structure information."""
- dom_info = {}
- dom_info['img_count'] = len(re.findall(r'<img[^>]*>', content, re.IGNORECASE))
- dom_info['input_count'] = len(re.findall(r'<input[^>]*>', content, re.IGNORECASE))
- dom_info['form_count'] = len(re.findall(r'<form[^>]*>', content, re.IGNORECASE))
- dom_info['profile_section_count'] = len(re.findall(r'class=["\'](.*?profile.*?)["\']', content, re.IGNORECASE))
- dom_info['error_section_count'] = len(re.findall(r'class=["\'](.*?error.*?|.*?not-found.*?)["\']', content, re.IGNORECASE))
- return dom_info
- def analyze_url_structure(self, url: str, username: str) -> Dict[str, Any]:
- """Analyze URL structure for redirects and auth patterns."""
- parsed_url = urlparse(url)
- result = {
- 'domain': parsed_url.netloc,
- 'path': parsed_url.path,
- 'has_username_in_path': username.lower() in parsed_url.path.lower(),
- 'has_auth_pattern': any(auth in parsed_url.path.lower() for auth in self.auth_patterns),
- 'is_homepage': parsed_url.path in ('', '/')
- }
- return result
- async def detect_with_ai(self, content: str, url: str, username: str, site_name: str,
- http_code: int, response_time: float) -> Dict[str, Any]:
- """
- Use AI techniques to determine if a profile exists based on multiple factors:
- 1. Content analysis (keyword matching with weighted scoring)
- 2. HTTP status code
- 3. URL structure analysis
- 4. DOM structure analysis
- 5. Metadata analysis
- 6. Historical pattern recognition from previous scans
- """
- content_lower = content.lower()
- url_lower = url.lower()
- score = 0
- confidence = 0
- error_matches = sum(keyword in content_lower for keyword in self.error_keywords)
- positive_matches = sum(keyword in content_lower for keyword in self.positive_keywords)
- score -= error_matches * 2
- score += positive_matches * 1.5
- if http_code == 200:
- score += 5
- elif http_code == 404:
- score -= 10
- elif http_code >= 500:
- score -= 3
- elif http_code >= 300 and http_code < 400:
- url_analysis = self.analyze_url_structure(url, username)
- if url_analysis['has_auth_pattern']:
- score -= 3
- elif url_analysis['has_username_in_path']:
- score += 2
- url_analysis = self.analyze_url_structure(url, username)
- if url_analysis['has_username_in_path'] and not url_analysis['is_homepage']:
- score += 3
- if url_analysis['is_homepage'] and http_code == 200:
- score -= 5
- dom_info = self.extract_dom_structure(content)
- if dom_info['error_section_count'] > 0:
- score -= 3 * dom_info['error_section_count']
- if dom_info['profile_section_count'] > 0:
- score += 4 * dom_info['profile_section_count']
- if dom_info['img_count'] > 5:
- score += 2
- if dom_info['form_count'] > 0 and dom_info['input_count'] > 2:
- score -= 2
- meta_tags = self.extract_meta_tags(content)
- meta_content = ' '.join(meta_tags).lower()
- if username.lower() in meta_content:
- score += 5
- meta_error_matches = sum(keyword in meta_content for keyword in self.error_keywords)
- if meta_error_matches > 0:
- score -= 3 * meta_error_matches
- meta_positive_matches = sum(keyword in meta_content for keyword in self.positive_keywords + self.meta_keywords)
- if meta_positive_matches > 0:
- score += 2 * meta_positive_matches
- if site_name in self.pattern_cache:
- site_patterns = self.pattern_cache[site_name]
- for pattern, weight in site_patterns.items():
- if re.search(pattern, content_lower):
- score += weight
- if response_time < 0.5 and http_code == 404:
- score -= 2
-
- # Calculate confidence based on score magnitude (positive = found, negative = not found)
- if score > 10:
- confidence = 95
- elif score > 6:
- confidence = 85
- elif score > 2:
- confidence = 70
- elif score < -10:
- confidence = 95 # High confidence in "Not Found"
- elif score < -6:
- confidence = 85
- elif score < -2:
- confidence = 70
- else:
- confidence = 55
-
- # Stricter thresholds for status determination
- if score > 8:
- status = "Found"
- elif score < -8:
- status = "Not Found"
- else:
- status = "Maybe"
- if status in ["Found", "Not Found"]:
- self._update_pattern_cache(site_name, content_lower, status)
- return {
- "status": status,
- "confidence": confidence,
- "score": score,
- "analysis": {
- "error_keywords": error_matches,
- "positive_keywords": positive_matches,
- "dom_analysis": dom_info,
- "url_analysis": url_analysis,
- "http_code": http_code,
- "response_time": response_time
- }
- }
- def _update_pattern_cache(self, site_name: str, content: str, status: str):
- """Update the pattern cache with new learned patterns."""
- if site_name not in self.pattern_cache:
- self.pattern_cache[site_name] = {}
- if status == "Found":
- profile_patterns = [
- r'<div[^>]*class=["\'](.*?profile.*?|.*?user.*?|.*?account.*?)["\'][^>]*>',
- r'<h1[^>]*>(.*?)</h1>',
- r'<img[^>]*alt=["\'](.*?profile.*?|.*?avatar.*?|.*?user.*?)["\'][^>]*>'
- ]
- for pattern in profile_patterns:
- matches = re.findall(pattern, content, re.IGNORECASE)
- if matches:
- pattern_key = f"profile_pattern_{len(self.pattern_cache[site_name])}"
- self.pattern_cache[site_name][pattern_key] = 3
- elif status == "Not Found":
- error_patterns = [
- r'<div[^>]*class=["\'](.*?error.*?|.*?not-found.*?|.*?missing.*?)["\'][^>]*>',
- r'<h1[^>]*>(.*?not found.*?|.*?doesn\'t exist.*?|.*?error.*?)</h1>'
- ]
- for pattern in error_patterns:
- matches = re.findall(pattern, content, re.IGNORECASE)
- if matches:
-
- pattern_key = f"error_pattern_{len(self.pattern_cache[site_name])}"
- self.pattern_cache[site_name][pattern_key] = -3
- async def scan_username(self, site_name: str, url_template: str, username: str,
- session: aiohttp.ClientSession, semaphore: asyncio.Semaphore) -> Dict[str, Any]:
- """Scan a single site for the given username."""
+ number = int(value)
+ except ValueError:
+ print(f"{COLORS['red']}Please enter a whole number.{COLORS['reset']}")
+ continue
+ if min_value is not None and number < min_value:
+ print(f"{COLORS['red']}Minimum is {min_value}.{COLORS['reset']}")
+ continue
+ return number
+
+
+def prompt_float(prompt: str, default: float | None, min_value: float | None = None) -> float | None:
+ default_text = "" if default is None else str(default)
+ while True:
+ value = input(
+ f"{COLORS['green']}{prompt} [{default_text}]: {COLORS['yellow']}"
+ ).strip()
+ if not value:
+ return default
try:
- url = url_template.format(username)
- except (KeyError, IndexError):
- url = url_template.replace("{}", username)
- if "{" in url:
- url = f"https://{site_name}.com/{username}"
- except Exception as e:
- logger.debug(f"URL formatting error for {site_name}: {e}")
- url = f"https://{site_name}.com/{username}"
- status_text = "Unknown"
- code = 0
- response_time = 0
- content = ""
- ai_analysis = {}
- async with semaphore:
- start_time = time.time()
+ number = float(value)
+ except ValueError:
+ print(f"{COLORS['red']}Please enter a number.{COLORS['reset']}")
+ continue
+ if min_value is not None and number < min_value:
+ print(f"{COLORS['red']}Minimum is {min_value}.{COLORS['reset']}")
+ continue
+ return number
+
+
+def prompt_formats(current: list[str]) -> list[str]:
+ default_text = ",".join(current)
+ value = input(
+ f"{COLORS['green']}Output formats (json,csv,html,all) [{default_text}]: {COLORS['yellow']}"
+ ).strip()
+ if not value:
+ return current
+ return parse_formats(value)
+
+
+def prompt_path(prompt: str, default: Path | None) -> Path | None:
+ default_text = "" if default is None else str(default)
+ value = input(
+ f"{COLORS['green']}{prompt} [{default_text}]: {COLORS['yellow']}"
+ ).strip()
+ if not value:
+ return default
+ return Path(value)
+
+
+def prompt_scan_profile() -> str:
+ print(f"\n{COLORS['green']}Select scan profile:")
+ print(
+ f"{COLORS['white']}1. {COLORS['blue']}Quick{COLORS['white']} - fewer retries, shorter timeouts"
+ )
+ print(
+ f"{COLORS['white']}2. {COLORS['yellow']}Full{COLORS['white']} - balanced defaults"
+ )
+ print(
+ f"{COLORS['white']}3. {COLORS['red']}Aggressive{COLORS['white']} - higher concurrency, Playwright"
+ )
+ choice = input(
+ f"\n{COLORS['green']}Enter choice (1-3) [2]: {COLORS['yellow']}"
+ ).strip()
+ profile_map = {"1": "quick", "2": "full", "3": "aggressive"}
+ return profile_map.get(choice, "full")
+
+
+def apply_scan_profile(config: ScannerConfig, profile: str, args) -> None:
+ presets = {
+ "quick": {
+ "concurrent": 25,
+ "timeout": 6.0,
+ "retries": 1,
+ "backoff_base": 0.3,
+ "backoff_cap": 4.0,
+ "rate_limit_delay": 0.1,
+ "max_content_bytes": 60_000,
+ "use_playwright": False,
+ },
+ "aggressive": {
+ "concurrent": 80,
+ "timeout": 15.0,
+ "retries": 3,
+ "backoff_base": 0.4,
+ "backoff_cap": 12.0,
+ "rate_limit_delay": 0.05,
+ "max_content_bytes": 150_000,
+ "use_playwright": True,
+ },
+ }
+ preset = presets.get(profile)
+ if not preset:
+ return
+
+ if args.concurrent is None:
+ config.concurrent = preset["concurrent"]
+ if args.timeout is None:
+ config.timeout = preset["timeout"]
+ if args.retries is None:
+ config.retries = preset["retries"]
+ if args.backoff_base is None:
+ config.backoff_base = preset["backoff_base"]
+ if args.backoff_cap is None:
+ config.backoff_cap = preset["backoff_cap"]
+ if args.rate_limit is None:
+ config.rate_limit_delay = preset["rate_limit_delay"]
+ if args.max_bytes is None:
+ config.max_content_bytes = preset["max_content_bytes"]
+ if not args.playwright:
+ config.use_playwright = preset["use_playwright"]
+
+
+def load_config(path_value: str | None, logger) -> dict:
+ if path_value:
+ candidates = [Path(path_value)]
+ else:
+ candidates = [
+ Path("config.json"),
+ SCRIPT_DIR / "config.json",
+ Path("/etc/aliens_eye/config.json"),
+ Path("/usr/local/etc/aliens_eye/config.json"),
+ Path("/data/data/com.termux/files/usr/etc/aliens_eye/config.json"),
+ ]
+
+ for path in candidates:
+ if path.exists():
try:
- async with session.get(url, timeout=10, allow_redirects=True) as response:
- content = await response.text()
- code = response.status
- response_time = time.time() - start_time
- ai_analysis = await self.detect_with_ai(content, str(response.url), username,
- site_name, code, response_time)
- status_text = ai_analysis["status"]
- except asyncio.TimeoutError:
- status_text = "Timeout"
- code = 408
- response_time = time.time() - start_time
- except Exception as e:
- status_text = f"Error"
- code = 500
- response_time = time.time() - start_time
- logger.debug(f"Error scanning {site_name}: {str(e)}")
- if status_text == "Found":
- status_color = COLORS["green"]
- elif status_text == "Maybe":
- status_color = COLORS["yellow"]
+ with path.open("r", encoding="utf-8") as handle:
+ data = json.load(handle)
+ if isinstance(data, dict):
+ logger.info("Loaded config from %s", path)
+ return data
+ except Exception as exc:
+ logger.warning("Failed to read config %s: %s", path, exc)
+ return {}
+ return {}
+
+
+def apply_config(config: ScannerConfig, data: dict) -> dict:
+ if not isinstance(data, dict):
+ return {"level": None, "output_formats": None}
+
+ field_map = {
+ "concurrent": "concurrent",
+ "timeout": "timeout",
+ "max_content_bytes": "max_content_bytes",
+ "retries": "retries",
+ "backoff_base": "backoff_base",
+ "backoff_cap": "backoff_cap",
+ "jitter": "jitter",
+ "rate_limit_delay": "rate_limit_delay",
+ "fingerprints_path": "fingerprints_path",
+ "output_dir": "output_dir",
+ "use_playwright": "use_playwright",
+ "max_fingerprints_per_label": "max_fingerprints_per_label",
+ }
+ path_fields = {"fingerprints_path", "output_dir"}
+
+ for key, attr in field_map.items():
+ if key not in data:
+ continue
+ value = data.get(key)
+ if value is None:
+ continue
+ if attr in path_fields:
+ setattr(config, attr, Path(str(value)))
else:
- status_color = COLORS["red"]
- code_color = COLORS["green"] if code == 200 else COLORS["red"]
- url_color = status_color
- display_site = site_name[:20]
- confidence = ai_analysis.get("confidence", 0) if ai_analysis else 0
- confidence_str = f" ({confidence}%)" if confidence > 0 else ""
- print(f"{COLORS['green']}# {COLORS['yellow']}{display_site:20}{COLORS['white']}| "
- f"{status_color}{status_text:10}{confidence_str:8}{COLORS['white']}| "
- f"{code_color}{str(code):^10}{COLORS['white']}| "
- f"{url_color}{url}{COLORS['reset']} "
- f"({response_time:.2f}s)")
- return {
- "site": site_name,
- "url": url,
- "status": status_text,
- "code": code,
- "response_time": round(response_time, 2),
- "confidence": confidence,
- "ai_analysis": ai_analysis
- }
- async def scan_all_sites(self, username: str) -> List[Dict[str, Any]]:
- """Scan all sites for the given username."""
- results = []
- conn_limit = min(50, len(self.sites_data))
- semaphore = asyncio.Semaphore(conn_limit)
- print(f"\n{COLORS['purple']}Scanning '{COLORS['yellow']}{username}{COLORS['purple']}' across "
- f"{len(self.sites_data)} sites (max {conn_limit} concurrent connections)...{COLORS['reset']}\n")
- self._print_table_header()
- start_time = time.time()
- async with aiohttp.ClientSession(headers=self.headers) as session:
- tasks = [
- self.scan_username(site, tmpl, username, session, semaphore)
- for site, tmpl in self.sites_data.items()
- ]
- results = await asyncio.gather(*tasks)
- total_time = time.time() - start_time
- found_count = sum(1 for r in results if r["status"] == "Found")
- maybe_count = sum(1 for r in results if r["status"] == "Maybe")
- not_found_count = sum(1 for r in results if r["status"] == "Not Found")
- error_count = sum(1 for r in results if r["status"] not in ["Found", "Not Found", "Maybe"])
- high_confidence = [r for r in results if r.get("confidence", 0) >= 85 and r["status"] == "Found"]
- print(f"\n{COLORS['green']}Scan completed in {total_time:.2f} seconds")
- print(f"{COLORS['green']}Found: {found_count} | {COLORS['yellow']}Maybe: {maybe_count} | "
- f"{COLORS['red']}Not Found: {not_found_count} | Errors: {error_count}{COLORS['reset']}")
- if high_confidence:
- print(f"\n{COLORS['green']}High confidence matches ({len(high_confidence)}):{COLORS['reset']}")
- for result in high_confidence[:5]:
- print(f"{COLORS['yellow']}{result['site']}: {COLORS['green']}{result['url']}{COLORS['reset']} ({result['confidence']}% confidence)")
- if len(high_confidence) > 5:
- print(f"{COLORS['yellow']}... and {len(high_confidence) - 5} more{COLORS['reset']}")
- return results
- async def scan_with_variations(self, base_username: str, level: str = "basic") -> Dict[str, List[Dict[str, Any]]]:
- """Scan all variations of a username based on the specified level."""
- variations = self.generate_username_variations(base_username, level)
- all_results = {}
- print(f"\n{COLORS['blue']}Scan level: {COLORS['yellow']}{level.upper()}")
- print(f"{COLORS['blue']}Generated {len(variations)} username variations to scan")
- if len(variations) > 1:
- print(f"{COLORS['yellow']}Variations: {', '.join(variations[:5])}" +
- (f" and {len(variations)-5} more..." if len(variations) > 5 else ""))
- for username in variations:
- print(f"\n{COLORS['purple']}Scanning variation: {COLORS['yellow']}{username}{COLORS['reset']}")
- results = await self.scan_all_sites(username)
- all_results[username] = results
- return all_results
- def _print_table_header(self):
- """Print the table header for scan results."""
- print(f"{COLORS['blue']}# {COLORS['yellow']}{'SITE':20}{COLORS['blue']}| "
- f"{COLORS['yellow']}{'STATUS + CONFIDENCE':18}{COLORS['blue']}| "
- f"{COLORS['yellow']}{'HTTP CODE':10}{COLORS['blue']}| "
- f"{COLORS['yellow']}URL (RESPONSE TIME){COLORS['reset']}")
- print(f"{COLORS['green']}{'#' * 90}{COLORS['reset']}")
- def save_results_with_variations(self, base_username: str, all_results: Dict[str, List[Dict[str, Any]]],
- level: str) -> str:
- """Save scan results for all username variations to a JSON file."""
- variations_data = {}
- scan_summary = {
- "base_username": base_username,
- "scan_level": level,
- "timestamp": datetime.now().isoformat(),
- "total_variations": len(all_results),
- "total_sites_scanned": sum(len(results) for results in all_results.values()),
- }
- found_counts = {}
- high_confidence_matches = {}
- for username, results in all_results.items():
- found_counts[username] = sum(1 for r in results if r["status"] == "Found")
- high_confidence_matches[username] = sum(1 for r in results if r.get("confidence", 0) >= 85 and r["status"] == "Found")
- variations_data[username] = {
- "scan_info": {
- "username": username,
- "sites_scanned": len(results),
- "found": found_counts[username],
- "maybe": sum(1 for r in results if r["status"] == "Maybe"),
- "not_found": sum(1 for r in results if r["status"] == "Not Found"),
- "errors": sum(1 for r in results if r["status"] not in ["Found", "Not Found", "Maybe"]),
- "high_confidence_matches": high_confidence_matches[username]
- },
- "sites": {r["site"]: {
- "status": r["status"],
- "code": r["code"],
- "url": r["url"],
- "response_time": r["response_time"],
- "confidence": r.get("confidence", 0),
- "ai_analysis": r.get("ai_analysis", {})
- } for r in results}
- }
- scan_summary["total_found"] = sum(found_counts.values())
- scan_summary["total_high_confidence"] = sum(high_confidence_matches.values())
- scan_summary["best_variations"] = sorted(found_counts.items(), key=lambda x: x[1], reverse=True)[:5]
- results_data = {
- "scan_summary": scan_summary,
- "variations": variations_data
- }
- filename = self.results_dir / f"{base_username}_{level}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
- with open(filename, 'w') as f:
- json.dump(results_data, f, indent=4)
- return str(filename)
- def display_results_from_file(self, file_path: str) -> None:
- """Display saved results from a JSON file."""
- try:
- with open(file_path, 'r') as f:
- data = json.load(f)
- if "scan_summary" in data and "variations" in data:
- summary = data["scan_summary"]
- print(f"{COLORS['green']}{'=' * 90}")
- print(f"{COLORS['blue']}SCAN RESULTS SUMMARY: {COLORS['yellow']}{summary.get('base_username', 'Unknown')}")
- print(f"{COLORS['blue']}Scan level: {COLORS['white']}{summary.get('scan_level', 'Unknown')}")
- print(f"{COLORS['blue']}Date: {COLORS['white']}{summary.get('timestamp', 'Unknown')}")
- print(f"{COLORS['blue']}Total Variations: {COLORS['white']}{summary.get('total_variations', 0)}")
- print(f"{COLORS['blue']}Total Sites Scanned: {COLORS['white']}{summary.get('total_sites_scanned', 0)}")
- print(f"{COLORS['blue']}Total Found: {COLORS['green']}{summary.get('total_found', 0)}")
- print(f"{COLORS['blue']}Total High Confidence: {COLORS['green']}{summary.get('total_high_confidence', 0)}")
- print(f"{COLORS['green']}{'=' * 90}")
- print(f"{COLORS['blue']}Best Variations:")
- for username, count in summary.get('best_variations', []):
- print(f"{COLORS['yellow']}{username}: {COLORS['green']}{count} profiles found")
- print(f"{COLORS['green']}{'=' * 90}")
- print(f"{COLORS['blue']}Available variations:")
- for i, username in enumerate(data["variations"].keys(), 1):
- print(f"{COLORS['white']}{i}. {COLORS['yellow']}{username}")
- choice = input(f"\n{COLORS['green']}Enter number to see details (or 'all' for all, or press Enter to exit): {COLORS['yellow']}")
- if choice.lower() == 'all':
- for username, variation_data in data["variations"].items():
- self._display_variation_results(username, variation_data)
- elif choice.isdigit():
- choice_idx = int(choice) - 1
- if 0 <= choice_idx < len(data["variations"]):
- username = list(data["variations"].keys())[choice_idx]
- self._display_variation_results(username, data["variations"][username])
- else:
- scan_info = data.get("scan_info", {})
- print(f"{COLORS['green']}{'=' * 90}")
- print(f"{COLORS['blue']}SCAN RESULTS: {COLORS['yellow']}{scan_info.get('username', 'Unknown')}")
- print(f"{COLORS['blue']}Date: {COLORS['white']}{scan_info.get('timestamp', 'Unknown')}")
- print(f"{COLORS['blue']}Sites Scanned: {COLORS['white']}{scan_info.get('sites_scanned', 0)}")
- print(f"{COLORS['blue']}Found: {COLORS['green']}{scan_info.get('found', 0)} | "
- f"{COLORS['blue']}Maybe: {COLORS['yellow']}{scan_info.get('maybe', 0)} | "
- f"{COLORS['blue']}Not Found: {COLORS['red']}{scan_info.get('not_found', 0)} | "
- f"{COLORS['blue']}Errors: {COLORS['red']}{scan_info.get('errors', 0)}")
- high_conf = scan_info.get('high_confidence_matches', 0)
- if high_conf > 0:
- print(f"{COLORS['blue']}High Confidence Matches: {COLORS['green']}{high_conf}")
- print(f"{COLORS['green']}{'=' * 90}")
- self._print_table_header()
- def sort_key(item):
- status_priority = {"Found": 0, "Maybe": 1, "Not Found": 2}.get(item[1].get("status", ""), 3)
- confidence = item[1].get("confidence", 0)
- return (-confidence, status_priority)
- sorted_sites = sorted(data.get("sites", {}).items(), key=sort_key)
- for site_name, info in sorted_sites:
- status = info.get("status", "Unknown")
- code = info.get("code", 0)
- url = info.get("url", "")
- response_time = info.get("response_time", 0)
- confidence = info.get("confidence", 0)
- if status == "Found":
- status_color = COLORS["green"]
- elif status == "Maybe":
- status_color = COLORS["yellow"]
- else:
- status_color = COLORS["red"]
- code_color = COLORS["green"] if code == 200 else COLORS["red"]
- url_color = status_color
- display_site = site_name[:20]
- confidence_str = f" ({confidence}%)" if confidence > 0 else ""
- print(f"{COLORS['green']}# {COLORS['yellow']}{display_site:20}{COLORS['white']}| "
- f"{status_color}{status:10}{confidence_str:8}{COLORS['white']}| "
- f"{code_color}{str(code):^10}{COLORS['white']}| "
- f"{url_color}{url}{COLORS['reset']} "
- f"({response_time:.2f}s)")
- print(f"{COLORS['green']}{'=' * 90}{COLORS['reset']}")
- except FileNotFoundError:
- print(f"{COLORS['red']}File not found: {file_path}{COLORS['reset']}")
- except json.JSONDecodeError:
- print(f"{COLORS['red']}Invalid JSON file: {file_path}{COLORS['reset']}")
- except Exception as e:
- print(f"{COLORS['red']}Error reading file: {e}{COLORS['reset']}")
- def _display_variation_results(self, username, variation_data):
- """Display results for a specific username variation."""
- scan_info = variation_data.get("scan_info", {})
- print(f"{COLORS['green']}{'=' * 90}")
- print(f"{COLORS['blue']}SCAN RESULTS FOR VARIATION: {COLORS['yellow']}{username}")
- print(f"{COLORS['blue']}Found: {COLORS['green']}{scan_info.get('found', 0)} | "
- f"{COLORS['blue']}Maybe: {COLORS['yellow']}{scan_info.get('maybe', 0)} | "
- f"{COLORS['blue']}Not Found: {COLORS['red']}{scan_info.get('not_found', 0)} | "
- f"{COLORS['blue']}Errors: {COLORS['red']}{scan_info.get('errors', 0)}")
- high_conf = scan_info.get('high_confidence_matches', 0)
- if high_conf > 0:
- print(f"{COLORS['blue']}High Confidence Matches: {COLORS['green']}{high_conf}")
- print(f"{COLORS['green']}{'=' * 90}")
- self._print_table_header()
- def sort_key(item):
- site_info = item[1]
- status_priority = {"Found": 0, "Maybe": 1, "Not Found": 2}.get(site_info.get("status", ""), 3)
- confidence = site_info.get("confidence", 0)
- return (-confidence, status_priority)
- sites = variation_data.get("sites", {})
- sorted_sites = sorted(sites.items(), key=sort_key)
- for site_name, info in sorted_sites:
- status = info.get("status", "Unknown")
- code = info.get("code", 0)
- url = info.get("url", "")
- response_time = info.get("response_time", 0)
- confidence = info.get("confidence", 0)
- if status == "Found":
- status_color = COLORS["green"]
- elif status == "Maybe":
- status_color = COLORS["yellow"]
- else:
- status_color = COLORS["red"]
- code_color = COLORS["green"] if code == 200 else COLORS["red"]
- url_color = status_color
- display_site = site_name[:20]
- confidence_str = f" ({confidence}%)" if confidence > 0 else ""
- print(f"{COLORS['green']}# {COLORS['yellow']}{display_site:20}{COLORS['white']}| "
- f"{status_color}{status:10}{confidence_str:8}{COLORS['white']}| "
- f"{code_color}{str(code):^10}{COLORS['white']}| "
- f"{url_color}{url}{COLORS['reset']} "
- f"({response_time:.2f}s)")
- print(f"{COLORS['green']}{'=' * 90}{COLORS['reset']}")
- def display_variations_summary(self, all_results: Dict[str, List[Dict[str, Any]]]) -> None:
- """Display a summary of results for all username variations."""
- print(f"\n{COLORS['green']}{'=' * 90}")
- print(f"{COLORS['blue']}SUMMARY OF VARIATIONS:")
-
- sorted_variations = sorted(
- all_results.items(),
- key=lambda x: sum(1 for r in x[1] if r["status"] == "Found"),
- reverse=True
- )
- for username, results in sorted_variations:
- found_count = sum(1 for r in results if r["status"] == "Found")
- maybe_count = sum(1 for r in results if r["status"] == "Maybe")
- high_confidence = sum(1 for r in results if r.get("confidence", 0) >= 85 and r["status"] == "Found")
- if found_count > 0:
- status_color = COLORS["green"]
- elif maybe_count > 0:
- status_color = COLORS["yellow"]
- else:
- status_color = COLORS["red"]
- print(f"{status_color}{username:20}{COLORS['white']}| "
- f"{COLORS['green']}Found: {found_count:3}{COLORS['white']} | "
- f"{COLORS['yellow']}Maybe: {maybe_count:3}{COLORS['white']} | "
- f"{COLORS['blue']}High Conf: {high_confidence:3}")
- print(f"{COLORS['green']}{'=' * 90}{COLORS['reset']}")
-async def main():
- parser = ArgumentParser(description="AI-Enhanced Username Scanner - Find usernames across social media platforms")
- parser.add_argument("username", nargs='*', help='Usernames to scan (e.g., $ python3 script.py user1 user2)')
- parser.add_argument("-r", "--read", help='Path to JSON file to read and display', type=str)
- parser.add_argument("-c", "--concurrent", help='Maximum number of concurrent connections (default: auto)', type=int)
- parser.add_argument("-v", "--verbose", help='Enable verbose output', action='store_true')
- parser.add_argument("-l", "--level", help='Scan level (basic, intermediate, advanced)', choices=['basic', 'intermediate', 'advanced'])
- args = parser.parse_args()
- scanner = AIUsernameScanner()
- scanner.display_banner()
+ setattr(config, attr, value)
+
+ return {
+ "level": data.get("level"),
+ "output_formats": data.get("output_formats"),
+ }
+
+
+async def run_scan(args) -> None:
+ logger = setup_logger(args.verbose)
+ config_data = load_config(args.config, logger)
+ config = ScannerConfig()
+ defaults = apply_config(config, config_data)
+
+ if args.concurrent:
+ config.concurrent = args.concurrent
+ if args.timeout:
+ config.timeout = args.timeout
+ if args.retries is not None:
+ config.retries = args.retries
+ if args.backoff_base is not None:
+ config.backoff_base = args.backoff_base
+ if args.backoff_cap is not None:
+ config.backoff_cap = args.backoff_cap
+ if args.rate_limit is not None:
+ config.rate_limit_delay = args.rate_limit
+ if args.max_bytes is not None:
+ config.max_content_bytes = args.max_bytes
+ if args.output:
+ config.output_dir = Path(args.output)
+ if args.playwright:
+ config.use_playwright = True
+
+ exporter = ResultsExporter(config.output_dir)
if args.read:
- scanner.display_results_from_file(args.read)
+ exporter.display_results_from_file(args.read)
return
- internet_available = await scanner.check_internet()
- if not internet_available:
- logger.error("No internet connection available. Please check your connection and try again.")
+
+ sites_data = load_sites_data()
+ if not sites_data:
+ logger.error("Could not find sites.json. Make sure it exists in the project.")
return
+
+ display_banner(len(sites_data))
+
if args.username:
- username = args.username[0]
+ usernames = args.username
else:
username = input(f"{COLORS['green']}Enter username to scan: {COLORS['yellow']}")
- if not username or len(username) < 2:
- logger.error("Invalid username. Please provide a valid username.")
- return
- if not args.level:
+ usernames = [username]
+
+ detector = Detector()
+ detector.load_model(logger)
+
+ extractor = FeatureExtractor()
+ fingerprints = FingerprintStore(config.fingerprints_path, config.max_fingerprints_per_label)
+ fingerprints.load(logger)
+
+ scan_level = args.level or defaults.get("level")
+ if scan_level not in {"basic", "intermediate", "advanced"}:
+ scan_level = None
+ if not scan_level:
print(f"\n{COLORS['green']}Select scan level:")
print(f"{COLORS['white']}1. {COLORS['blue']}Basic{COLORS['white']} - Just the username as entered")
- print(f"{COLORS['white']}2. {COLORS['yellow']}Intermediate{COLORS['white']} - Adds variations with underscores, dots, etc.")
- print(f"{COLORS['white']}3. {COLORS['red']}Advanced{COLORS['white']} - Adds common prefixes/suffixes like 'real', 'official', etc.")
+ print(
+ f"{COLORS['white']}2. {COLORS['yellow']}Intermediate{COLORS['white']} - Adds variations"
+ )
+ print(
+ f"{COLORS['white']}3. {COLORS['red']}Advanced{COLORS['white']} - Adds common prefixes/suffixes"
+ )
level_choice = input(f"\n{COLORS['green']}Enter choice (1-3): {COLORS['yellow']}")
level_map = {"1": "basic", "2": "intermediate", "3": "advanced"}
scan_level = level_map.get(level_choice, "basic")
- else:
- scan_level = args.level
- if args.verbose:
- logger.setLevel(logging.DEBUG)
- all_results = await scanner.scan_with_variations(username, scan_level)
- result_file = scanner.save_results_with_variations(username, all_results, scan_level)
- print(f"\n{COLORS['green']}Results saved to: {COLORS['blue']}{result_file}{COLORS['reset']}")
- total_found = sum(sum(1 for r in results if r["status"] == "Found") for results in all_results.values())
- print(f"\n{COLORS['green']}Summary: Found {total_found} profiles across {len(all_results)} username variations")
- if args.username and len(args.username) > 1:
- for next_username in args.username[1:]:
- print(f"\n{COLORS['green']}Continue with next username: {COLORS['yellow']}{next_username}{COLORS['reset']}")
- all_results = await scanner.scan_with_variations(next_username, scan_level)
- result_file = scanner.save_results_with_variations(next_username, all_results, scan_level)
- print(f"\n{COLORS['green']}Results saved to: {COLORS['blue']}{result_file}{COLORS['reset']}")
+
+ formats_value = args.format if args.format is not None else defaults.get("output_formats")
+ formats = parse_formats_value(formats_value)
+
+ interactive = sys.stdin.isatty() and not args.read
+ if interactive:
+ scan_profile = prompt_scan_profile()
+ apply_scan_profile(config, scan_profile, args)
+
+ if interactive and prompt_yes_no("Customize scan settings", False):
+ if args.concurrent is None:
+ config.concurrent = prompt_int(
+ "Max concurrent connections", config.concurrent, min_value=1
+ )
+ if args.timeout is None:
+ config.timeout = prompt_float(
+ "Request timeout (seconds)", config.timeout, min_value=1.0
+ )
+ if args.retries is None:
+ config.retries = prompt_int("Retries on failure", config.retries, min_value=0)
+ if args.backoff_base is None:
+ config.backoff_base = prompt_float(
+ "Backoff base (seconds)", config.backoff_base, min_value=0.0
+ )
+ if args.backoff_cap is None:
+ config.backoff_cap = prompt_float(
+ "Backoff cap (seconds)", config.backoff_cap, min_value=0.0
+ )
+ if args.rate_limit is None:
+ config.rate_limit_delay = prompt_float(
+ "Min delay per domain (seconds)", config.rate_limit_delay, min_value=0.0
+ )
+ if args.max_bytes is None:
+ config.max_content_bytes = prompt_int(
+ "Max response bytes to parse", config.max_content_bytes, min_value=1024
+ )
+ if args.output is None:
+ config.output_dir = prompt_path("Output directory", config.output_dir)
+ if args.format is None:
+ formats = prompt_formats(formats)
+ if not args.playwright:
+ config.use_playwright = prompt_yes_no(
+ "Enable Playwright fallback for Maybe results", config.use_playwright
+ )
+
+ browser_fallback = None
+ if config.use_playwright:
+ browser_fallback = BrowserFallback(config.timeout, DEFAULT_USER_AGENT)
+
+ scanner = UsernameScanner(
+ sites_data=sites_data,
+ config=config,
+ extractor=extractor,
+ detector=detector,
+ fingerprints=fingerprints,
+ logger=logger,
+ browser_fallback=browser_fallback,
+ )
+
+ try:
+ for idx, username in enumerate(usernames):
+ if not username or len(username) < 2:
+ logger.error("Invalid username. Please provide a valid username.")
+ continue
+
+ if idx > 0:
+ print(
+ f"\n{COLORS['green']}Continue with next username: {COLORS['yellow']}{username}{COLORS['reset']}"
+ )
+
+ all_results = await scanner.scan_with_variations(username, scan_level)
+ written = exporter.save_results(username, scan_level, all_results, formats)
+
+ files_list = ", ".join(str(path) for path in written)
+ print(
+ f"\n{COLORS['green']}Results saved to: {COLORS['blue']}{files_list}{COLORS['reset']}"
+ )
+ total_found = sum(
+ sum(1 for r in results if r["status"] == "Found")
+ for results in all_results.values()
+ )
+ print(
+ f"\n{COLORS['green']}Summary: Found {total_found} profiles across {len(all_results)} username variations"
+ )
+ finally:
+ fingerprints.save()
+ if browser_fallback:
+ await browser_fallback.close()
+
print(f"\n{COLORS['green']}Thank you for using AI-Enhanced OSINT Username Scanner!{COLORS['reset']}")
-if __name__ == "__main__":
+
+
+def main() -> None:
+ parser = build_parser()
+ args = parser.parse_args()
try:
- asyncio.run(main())
+ asyncio.run(run_scan(args))
except KeyboardInterrupt:
print(f"\n\n{COLORS['red']}Scan interrupted by user.{COLORS['reset']}")
sys.exit(0)
- except Exception as e:
- logger.error(f"Unexpected error: {e}")
+ except Exception as exc:
+ print(f"{COLORS['red']}Unexpected error: {exc}{COLORS['reset']}")
sys.exit(1)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/config.json b/config.json
new file mode 100644
index 0000000..a46e030
--- /dev/null
+++ b/config.json
@@ -0,0 +1,16 @@
+{
+ "concurrent": 50,
+ "timeout": 10.0,
+ "max_content_bytes": 100000,
+ "retries": 2,
+ "backoff_base": 0.5,
+ "backoff_cap": 8.0,
+ "jitter": 0.2,
+ "rate_limit_delay": 0.2,
+ "fingerprints_path": "cache/fingerprints.json",
+ "output_dir": "results",
+ "output_formats": ["json", "csv", "html"],
+ "use_playwright": false,
+ "max_fingerprints_per_label": 50,
+ "level": "basic"
+}
diff --git a/core/__init__.py b/core/__init__.py
new file mode 100644
index 0000000..011eca6
--- /dev/null
+++ b/core/__init__.py
@@ -0,0 +1 @@
+"""Core modules for Aliens Eye."""
diff --git a/core/analyzer.py b/core/analyzer.py
new file mode 100644
index 0000000..7b364be
--- /dev/null
+++ b/core/analyzer.py
@@ -0,0 +1,162 @@
+from dataclasses import dataclass
+from typing import Any, Dict, List
+from urllib.parse import urlparse
+
+from selectolax.parser import HTMLParser
+
+from .config import (
+ AUTH_PATTERNS,
+ ERROR_CLASS_HINTS,
+ ERROR_KEYWORDS,
+ META_KEYWORDS,
+ POSITIVE_KEYWORDS,
+ PROFILE_CLASS_HINTS,
+)
+
+
+@dataclass
+class FeatureBundle:
+ features: Dict[str, float]
+ signals: Dict[str, Any]
+ fingerprint: Dict[str, Any]
+
+
+class FeatureExtractor:
+ """Extract structured signals from HTML content."""
+
+ def __init__(
+ self,
+ error_keywords: List[str] | None = None,
+ positive_keywords: List[str] | None = None,
+ meta_keywords: List[str] | None = None,
+ auth_patterns: List[str] | None = None,
+ ) -> None:
+ self.error_keywords = error_keywords or ERROR_KEYWORDS
+ self.positive_keywords = positive_keywords or POSITIVE_KEYWORDS
+ self.meta_keywords = meta_keywords or META_KEYWORDS
+ self.auth_patterns = auth_patterns or AUTH_PATTERNS
+
+ def extract(
+ self,
+ content: str,
+ url: str,
+ username: str,
+ site_name: str,
+ http_code: int,
+ response_time: float,
+ headers: Dict[str, str] | None,
+ redirect_count: int,
+ ) -> FeatureBundle:
+ content = content or ""
+ content_lower = content.lower()
+
+ error_keyword_count = sum(
+ 1 for keyword in self.error_keywords if keyword in content_lower
+ )
+ positive_keyword_count = sum(
+ 1 for keyword in self.positive_keywords if keyword in content_lower
+ )
+
+ parsed_url = urlparse(url)
+ path = parsed_url.path or ""
+ has_username_in_path = username.lower() in path.lower()
+ has_auth_pattern = any(auth in path.lower() for auth in self.auth_patterns)
+ is_homepage = path in ("", "/")
+
+ tree = HTMLParser(content)
+ title_node = tree.css_first("title")
+ title_text = title_node.text().strip() if title_node else ""
+
+ meta_contents: List[str] = []
+ for node in tree.css("meta"):
+ content_value = node.attributes.get("content")
+ if content_value:
+ meta_contents.append(content_value)
+
+ meta_text = " ".join(meta_contents).lower()
+ meta_error_keyword_count = sum(
+ 1 for keyword in self.error_keywords if keyword in meta_text
+ )
+ meta_positive_keyword_count = sum(
+ 1 for keyword in (self.positive_keywords + self.meta_keywords)
+ if keyword in meta_text
+ )
+
+ class_nodes = tree.css("[class]")
+ profile_section_count = 0
+ error_section_count = 0
+ for node in class_nodes:
+ class_attr = node.attributes.get("class", "")
+ class_value = str(class_attr).lower() if class_attr is not None else ""
+ if not class_value:
+ continue
+ if any(hint in class_value for hint in PROFILE_CLASS_HINTS):
+ profile_section_count += 1
+ if any(hint in class_value for hint in ERROR_CLASS_HINTS):
+ error_section_count += 1
+
+ img_count = len(tree.css("img"))
+ input_count = len(tree.css("input"))
+ form_count = len(tree.css("form"))
+
+ features = {
+ "http_200": 1.0 if http_code == 200 else 0.0,
+ "http_3xx": 1.0 if 300 <= http_code < 400 else 0.0,
+ "http_404": 1.0 if http_code == 404 else 0.0,
+ "http_4xx": 1.0 if 400 <= http_code < 500 else 0.0,
+ "http_5xx": 1.0 if http_code >= 500 else 0.0,
+ "has_username_in_path": 1.0 if has_username_in_path else 0.0,
+ "is_homepage": 1.0 if is_homepage else 0.0,
+ "has_auth_pattern": 1.0 if has_auth_pattern else 0.0,
+ "error_keyword_count": float(error_keyword_count),
+ "positive_keyword_count": float(positive_keyword_count),
+ "meta_error_keyword_count": float(meta_error_keyword_count),
+ "meta_positive_keyword_count": float(meta_positive_keyword_count),
+ "profile_section_count": float(profile_section_count),
+ "error_section_count": float(error_section_count),
+ "img_count": float(img_count),
+ "input_count": float(input_count),
+ "form_count": float(form_count),
+ "title_has_username": 1.0
+ if username.lower() in title_text.lower()
+ else 0.0,
+ "meta_has_username": 1.0
+ if username.lower() in meta_text
+ else 0.0,
+ "response_time": float(response_time),
+ "content_length": float(len(content)),
+ "redirect_count": float(redirect_count),
+ }
+
+ signals = {
+ "site": site_name,
+ "title": title_text,
+ "meta_samples": meta_contents[:5],
+ "url_analysis": {
+ "domain": parsed_url.netloc,
+ "path": path,
+ "has_username_in_path": has_username_in_path,
+ "has_auth_pattern": has_auth_pattern,
+ "is_homepage": is_homepage,
+ },
+ "dom": {
+ "img_count": img_count,
+ "input_count": input_count,
+ "form_count": form_count,
+ "profile_section_count": profile_section_count,
+ "error_section_count": error_section_count,
+ },
+ "headers": {
+ "server": (headers or {}).get("Server", ""),
+ "content_type": (headers or {}).get("Content-Type", ""),
+ },
+ }
+
+ fingerprint = {
+ "title": title_text,
+ "meta_text": meta_text,
+ "dom_signature": f"img:{img_count}|form:{form_count}|profile:{profile_section_count}|error:{error_section_count}",
+ "server": (headers or {}).get("Server", ""),
+ }
+
+ return FeatureBundle(features=features, signals=signals, fingerprint=fingerprint)
diff --git a/core/browser.py b/core/browser.py
new file mode 100644
index 0000000..67c6c4f
--- /dev/null
+++ b/core/browser.py
@@ -0,0 +1,44 @@
+import asyncio
+from typing import Optional, Tuple
+
+
+class BrowserFallback:
+ """Playwright-based fallback for hard pages."""
+
+ def __init__(self, timeout: float, user_agent: str) -> None:
+ self.timeout = timeout
+ self.user_agent = user_agent
+ self._playwright = None
+ self._browser = None
+ self._context = None
+ self._lock = asyncio.Lock()
+
+ async def start(self) -> None:
+ try:
+ from playwright.async_api import async_playwright
+ except ImportError as exc:
+ raise RuntimeError("Playwright is not installed") from exc
+
+ self._playwright = await async_playwright().start()
+ self._browser = await self._playwright.chromium.launch(headless=True)
+ self._context = await self._browser.new_context(user_agent=self.user_agent)
+
+ async def close(self) -> None:
+ if self._context:
+ await self._context.close()
+ if self._browser:
+ await self._browser.close()
+ if self._playwright:
+ await self._playwright.stop()
+
+ async def fetch(self, url: str) -> Tuple[str, str]:
+ if not self._context:
+ await self.start()
+
+ async with self._lock:
+ page = await self._context.new_page()
+ await page.goto(url, wait_until="domcontentloaded", timeout=int(self.timeout * 1000))
+ content = await page.content()
+ final_url = page.url
+ await page.close()
+ return content, final_url
diff --git a/core/config.py b/core/config.py
new file mode 100644
index 0000000..659298e
--- /dev/null
+++ b/core/config.py
@@ -0,0 +1,127 @@
+from dataclasses import dataclass
+from pathlib import Path
+
+DEFAULT_USER_AGENT = (
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
+ "AppleWebKit/537.36 Chrome/115.0.0.0 Safari/537.36"
+)
+
+DEFAULT_HEADERS = {
+ "User-Agent": DEFAULT_USER_AGENT,
+ "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
+ "Accept-Encoding": "gzip, deflate, br",
+ "Accept-Language": "en-US,en;q=0.5",
+ "Connection": "keep-alive",
+ "DNT": "1",
+ "Upgrade-Insecure-Requests": "1",
+}
+
+ERROR_KEYWORDS = [
+ "not found",
+ "doesn't exist",
+ "didn't find",
+ "does not exist",
+ "something went wrong",
+ "no such user",
+ "user not found",
+ "cannot find",
+ "can't find",
+ "not exist",
+ "profile not found",
+ "account does not exist",
+ "username not found",
+ "no user found",
+ "no results found",
+ "no such username",
+ "isn't available",
+ "that content is unavailable",
+ "page not found",
+ "404",
+ "404 error",
+ "404 not found",
+ "error",
+ "sorry",
+ "oops",
+ "unavailable",
+ "account suspended",
+ "invalid username",
+ "account not found",
+ "account terminated",
+ "account disabled",
+ "user doesn't have an account",
+ "this account doesn't exist",
+ "page was not found",
+]
+
+POSITIVE_KEYWORDS = [
+ "follow",
+ "subscribe",
+ "like",
+ "share",
+ "following",
+ "followers",
+ "profile",
+ "user",
+ "posts",
+ "photos",
+ "bio",
+ "status",
+ "tweets",
+ "joined",
+ "member since",
+ "online",
+ "verified",
+ "active",
+ "comments",
+ "uploads",
+ "reviews",
+ "friends",
+ "connections",
+ "activity",
+ "timeline",
+]
+
+META_KEYWORDS = [
+ "profile picture",
+ "profile image",
+ "avatar",
+ "user page",
+ "username",
+ "user profile",
+ "account info",
+ "account information",
+ "user information",
+]
+
+AUTH_PATTERNS = [
+ "/login",
+ "/signin",
+ "/register",
+ "/join",
+ "auth",
+ "oauth",
+ "authenticate",
+ "account/login",
+ "session/new",
+ "user/login",
+ "members/login",
+]
+
+PROFILE_CLASS_HINTS = ["profile", "user", "account"]
+ERROR_CLASS_HINTS = ["error", "not-found", "missing", "unavailable"]
+
+
+@dataclass
+class ScannerConfig:
+ concurrent: int = 50
+ timeout: float = 10.0
+ max_content_bytes: int = 100_000
+ retries: int = 2
+ backoff_base: float = 0.5
+ backoff_cap: float = 8.0
+ jitter: float = 0.2
+ rate_limit_delay: float = 0.2
+ fingerprints_path: Path = Path("cache/fingerprints.json")
+ output_dir: Path = Path("results")
+ use_playwright: bool = False
+ max_fingerprints_per_label: int = 50
diff --git a/core/detector.py b/core/detector.py
new file mode 100644
index 0000000..79e6796
--- /dev/null
+++ b/core/detector.py
@@ -0,0 +1,93 @@
+from dataclasses import dataclass
+from typing import Dict
+
+from .features import vectorize_features
+
+
+@dataclass
+class DetectionResult:
+ status: str
+ confidence: int
+ score: float
+ method: str
+ probability: float | None
+
+
+class Detector:
+ """Heuristic-only detection based on structured response features."""
+
+ def load_model(self, logger) -> None:
+ logger.debug("ML model loading is disabled; using heuristics only.")
+
+ def predict(self, features: Dict[str, float]) -> DetectionResult:
+ heuristic_score = self._heuristic_score(features)
+ status, confidence = self._status_from_score(heuristic_score)
+ return DetectionResult(
+ status=status,
+ confidence=confidence,
+ score=heuristic_score,
+ method="heuristic",
+ probability=None,
+ )
+
+ def _heuristic_score(self, features: Dict[str, float]) -> float:
+ score = 0.0
+ score -= features.get("error_keyword_count", 0.0) * 2
+ score += features.get("positive_keyword_count", 0.0) * 1.5
+
+ if features.get("http_200", 0.0) > 0:
+ score += 5
+ if features.get("http_404", 0.0) > 0:
+ score -= 10
+ if features.get("http_5xx", 0.0) > 0:
+ score -= 3
+ if features.get("http_3xx", 0.0) > 0:
+ if features.get("has_auth_pattern", 0.0) > 0:
+ score -= 3
+ if features.get("has_username_in_path", 0.0) > 0:
+ score += 2
+
+ if features.get("has_username_in_path", 0.0) > 0 and features.get("is_homepage", 0.0) == 0:
+ score += 3
+ if features.get("is_homepage", 0.0) > 0 and features.get("http_200", 0.0) > 0:
+ score -= 5
+
+ score -= features.get("error_section_count", 0.0) * 3
+ score += features.get("profile_section_count", 0.0) * 4
+
+ if features.get("img_count", 0.0) > 5:
+ score += 2
+ if features.get("form_count", 0.0) > 0 and features.get("input_count", 0.0) > 2:
+ score -= 2
+
+ if features.get("meta_has_username", 0.0) > 0:
+ score += 5
+ score -= features.get("meta_error_keyword_count", 0.0) * 3
+ score += features.get("meta_positive_keyword_count", 0.0) * 2
+
+ score += features.get("fingerprint_match_found", 0.0) * 2
+ score -= features.get("fingerprint_match_not_found", 0.0) * 2
+
+ return score
+
+ def _status_from_score(self, score: float) -> tuple[str, int]:
+ if score > 10:
+ confidence = 95
+ elif score > 6:
+ confidence = 85
+ elif score > 2:
+ confidence = 70
+ elif score < -10:
+ confidence = 95
+ elif score < -6:
+ confidence = 85
+ elif score < -2:
+ confidence = 70
+ else:
+ confidence = 55
+
+ if score > 8:
+ return "Found", confidence
+ if score < -8:
+ return "Not Found", confidence
+ return "Maybe", confidence
diff --git a/core/exporter.py b/core/exporter.py
new file mode 100644
index 0000000..8724eb7
--- /dev/null
+++ b/core/exporter.py
@@ -0,0 +1,402 @@
+import csv
+import json
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List
+
+from utils.colors import COLORS
+
+
+class ResultsExporter:
+ """Save scan results in JSON, CSV, or HTML formats."""
+
+ def __init__(self, output_dir: Path) -> None:
+ self.output_dir = output_dir
+ self.output_dir.mkdir(parents=True, exist_ok=True)
+
+ def save_results(
+ self,
+ base_username: str,
+ level: str,
+ all_results: Dict[str, List[Dict[str, Any]]],
+ formats: List[str],
+ ) -> List[Path]:
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ results_data = self._build_results_data(
+ base_username, level, all_results, timestamp
+ )
+ written: List[Path] = []
+
+ if "json" in formats or "all" in formats:
+ json_path = self.output_dir / f"{base_username}_{level}_{timestamp}.json"
+ with json_path.open("w", encoding="utf-8") as handle:
+ json.dump(results_data, handle, indent=4)
+ written.append(json_path)
+
+ if "csv" in formats or "all" in formats:
+ csv_path = self.output_dir / f"{base_username}_{level}_{timestamp}.csv"
+ self._write_csv(csv_path, base_username, level, all_results)
+ written.append(csv_path)
+
+ if "html" in formats or "all" in formats:
+ html_path = self.output_dir / f"{base_username}_{level}_{timestamp}.html"
+ self._write_html(html_path, results_data)
+ written.append(html_path)
+
+ return written
+
+ def _build_results_data(
+ self,
+ base_username: str,
+ level: str,
+ all_results: Dict[str, List[Dict[str, Any]]],
+ timestamp: str,
+ ) -> Dict[str, Any]:
+ variations_data: Dict[str, Any] = {}
+ scan_summary = {
+ "base_username": base_username,
+ "scan_level": level,
+ "timestamp": timestamp,
+ "total_variations": len(all_results),
+ "total_sites_scanned": sum(len(results) for results in all_results.values()),
+ }
+
+ found_counts: Dict[str, int] = {}
+ high_confidence_matches: Dict[str, int] = {}
+
+ for username, results in all_results.items():
+ found_counts[username] = sum(1 for r in results if r["status"] == "Found")
+ high_confidence_matches[username] = sum(
+ 1
+ for r in results
+ if r.get("confidence", 0) >= 85 and r["status"] == "Found"
+ )
+ variations_data[username] = {
+ "scan_info": {
+ "username": username,
+ "sites_scanned": len(results),
+ "found": found_counts[username],
+ "maybe": sum(1 for r in results if r["status"] == "Maybe"),
+ "not_found": sum(
+ 1 for r in results if r["status"] == "Not Found"
+ ),
+ "errors": sum(
+ 1
+ for r in results
+ if r["status"] not in {"Found", "Not Found", "Maybe"}
+ ),
+ "high_confidence_matches": high_confidence_matches[username],
+ },
+ "sites": {
+ r["site"]: {
+ "status": r["status"],
+ "code": r["code"],
+ "url": r["url"],
+ "final_url": r.get("final_url", ""),
+ "response_time": r["response_time"],
+ "confidence": r.get("confidence", 0),
+ "ai_analysis": r.get("ai_analysis", {}),
+ }
+ for r in results
+ },
+ }
+
+ scan_summary["total_found"] = sum(found_counts.values())
+ scan_summary["total_high_confidence"] = sum(high_confidence_matches.values())
+ scan_summary["best_variations"] = sorted(
+ found_counts.items(), key=lambda x: x[1], reverse=True
+ )[:5]
+
+ return {"scan_summary": scan_summary, "variations": variations_data}
+
+ def _write_csv(
+ self,
+ path: Path,
+ base_username: str,
+ level: str,
+ all_results: Dict[str, List[Dict[str, Any]]],
+ ) -> None:
+ fieldnames = [
+ "base_username",
+ "variation",
+ "site",
+ "status",
+ "confidence",
+ "http_code",
+ "url",
+ "final_url",
+ "response_time",
+ ]
+ with path.open("w", newline="", encoding="utf-8") as handle:
+ writer = csv.DictWriter(handle, fieldnames=fieldnames)
+ writer.writeheader()
+ for variation, results in all_results.items():
+ for item in results:
+ writer.writerow(
+ {
+ "base_username": base_username,
+ "variation": variation,
+ "site": item["site"],
+ "status": item["status"],
+ "confidence": item.get("confidence", 0),
+ "http_code": item.get("code", 0),
+ "url": item.get("url", ""),
+ "final_url": item.get("final_url", ""),
+ "response_time": item.get("response_time", 0),
+ }
+ )
+
+ def _write_html(self, path: Path, results_data: Dict[str, Any]) -> None:
+ summary = results_data.get("scan_summary", {})
+ variations = results_data.get("variations", {})
+
+ rows = []
+ for variation, data in variations.items():
+ for site, info in data.get("sites", {}).items():
+ rows.append(
+ f"<tr><td>{variation}</td><td>{site}</td><td>{info.get('status','')}</td>"
+ f"<td>{info.get('confidence',0)}</td><td>{info.get('code',0)}</td>"
+ f"<td><a href='{info.get('url','')}'>{info.get('url','')}</a></td></tr>"
+ )
+
+ html = f"""
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Aliens Eye Report</title>
+<style>
+body {{ font-family: Arial, sans-serif; padding: 20px; }}
+summary, table {{ margin-top: 20px; }}
+
+table {{ border-collapse: collapse; width: 100%; }}
+th, td {{ border: 1px solid #ddd; padding: 8px; font-size: 12px; }}
+th {{ background-color: #f2f2f2; text-align: left; }}
+</style>
+</head>
+<body>
+<h1>Aliens Eye Report</h1>
+<p><strong>Base Username:</strong> {summary.get('base_username','')}</p>
+<p><strong>Scan Level:</strong> {summary.get('scan_level','')}</p>
+<p><strong>Total Variations:</strong> {summary.get('total_variations',0)}</p>
+<p><strong>Total Sites Scanned:</strong> {summary.get('total_sites_scanned',0)}</p>
+<p><strong>Total Found:</strong> {summary.get('total_found',0)}</p>
+<p><strong>Total High Confidence:</strong> {summary.get('total_high_confidence',0)}</p>
+
+<table>
+<thead>
+<tr>
+<th>Variation</th>
+<th>Site</th>
+<th>Status</th>
+<th>Confidence</th>
+<th>HTTP Code</th>
+<th>URL</th>
+</tr>
+</thead>
+<tbody>
+{''.join(rows)}
+</tbody>
+</table>
+</body>
+</html>
+"""
+ with path.open("w", encoding="utf-8") as handle:
+ handle.write(html)
+
+ def display_results_from_file(self, file_path: str) -> None:
+ try:
+ with open(file_path, "r", encoding="utf-8") as handle:
+ data = json.load(handle)
+
+ if "scan_summary" in data and "variations" in data:
+ summary = data["scan_summary"]
+ print(f"{COLORS['green']}{'=' * 90}")
+ print(
+ f"{COLORS['blue']}SCAN RESULTS SUMMARY: "
+ f"{COLORS['yellow']}{summary.get('base_username', 'Unknown')}"
+ )
+ print(
+ f"{COLORS['blue']}Scan level: {COLORS['white']}"
+ f"{summary.get('scan_level', 'Unknown')}"
+ )
+ print(
+ f"{COLORS['blue']}Total Variations: {COLORS['white']}"
+ f"{summary.get('total_variations', 0)}"
+ )
+ print(
+ f"{COLORS['blue']}Total Sites Scanned: {COLORS['white']}"
+ f"{summary.get('total_sites_scanned', 0)}"
+ )
+ print(
+ f"{COLORS['blue']}Total Found: {COLORS['green']}"
+ f"{summary.get('total_found', 0)}"
+ )
+ print(
+ f"{COLORS['blue']}Total High Confidence: {COLORS['green']}"
+ f"{summary.get('total_high_confidence', 0)}"
+ )
+ print(f"{COLORS['green']}{'=' * 90}")
+ print(f"{COLORS['blue']}Best Variations:")
+ for username, count in summary.get("best_variations", []):
+ print(
+ f"{COLORS['yellow']}{username}: {COLORS['green']}{count} profiles found"
+ )
+ print(f"{COLORS['green']}{'=' * 90}")
+ print(f"{COLORS['blue']}Available variations:")
+ for i, username in enumerate(data["variations"].keys(), 1):
+ print(f"{COLORS['white']}{i}. {COLORS['yellow']}{username}")
+
+ choice = input(
+ f"\n{COLORS['green']}Enter number to see details (or 'all' for all, or press Enter to exit): {COLORS['yellow']}"
+ )
+ if choice.lower() == "all":
+ for username, variation_data in data["variations"].items():
+ self._display_variation_results(username, variation_data)
+ elif choice.isdigit():
+ choice_idx = int(choice) - 1
+ if 0 <= choice_idx < len(data["variations"]):
+ username = list(data["variations"].keys())[choice_idx]
+ self._display_variation_results(
+ username, data["variations"][username]
+ )
+ return
+
+ scan_info = data.get("scan_info", {})
+ print(f"{COLORS['green']}{'=' * 90}")
+ print(
+ f"{COLORS['blue']}SCAN RESULTS: {COLORS['yellow']}"
+ f"{scan_info.get('username', 'Unknown')}"
+ )
+ print(
+ f"{COLORS['blue']}Date: {COLORS['white']}"
+ f"{scan_info.get('timestamp', 'Unknown')}"
+ )
+ print(
+ f"{COLORS['blue']}Sites Scanned: {COLORS['white']}"
+ f"{scan_info.get('sites_scanned', 0)}"
+ )
+ print(
+ f"{COLORS['blue']}Found: {COLORS['green']}"
+ f"{scan_info.get('found', 0)} | "
+ f"{COLORS['blue']}Maybe: {COLORS['yellow']}"
+ f"{scan_info.get('maybe', 0)} | "
+ f"{COLORS['blue']}Not Found: {COLORS['red']}"
+ f"{scan_info.get('not_found', 0)} | "
+ f"{COLORS['blue']}Errors: {COLORS['red']}"
+ f"{scan_info.get('errors', 0)}"
+ )
+ high_conf = scan_info.get("high_confidence_matches", 0)
+ if high_conf > 0:
+ print(
+ f"{COLORS['blue']}High Confidence Matches: {COLORS['green']}{high_conf}"
+ )
+ print(f"{COLORS['green']}{'=' * 90}")
+ self._print_table_header()
+
+ def sort_key(item):
+ status_priority = {"Found": 0, "Maybe": 1, "Not Found": 2}.get(
+ item[1].get("status", ""), 3
+ )
+ confidence = item[1].get("confidence", 0)
+ return (-confidence, status_priority)
+
+ sorted_sites = sorted(data.get("sites", {}).items(), key=sort_key)
+ for site_name, info in sorted_sites:
+ status = info.get("status", "Unknown")
+ code = info.get("code", 0)
+ url = info.get("url", "")
+ response_time = info.get("response_time", 0)
+ confidence = info.get("confidence", 0)
+ if status == "Found":
+ status_color = COLORS["green"]
+ elif status == "Maybe":
+ status_color = COLORS["yellow"]
+ else:
+ status_color = COLORS["red"]
+ code_color = COLORS["green"] if code == 200 else COLORS["red"]
+ url_color = status_color
+ display_site = site_name[:20]
+ confidence_str = f" ({confidence}%)" if confidence > 0 else ""
+ print(
+ f"{COLORS['green']}# {COLORS['yellow']}{display_site:20}{COLORS['white']}| "
+ f"{status_color}{status:10}{confidence_str:8}{COLORS['white']}| "
+ f"{code_color}{str(code):^10}{COLORS['white']}| "
+ f"{url_color}{url}{COLORS['reset']} "
+ f"({response_time:.2f}s)"
+ )
+ print(f"{COLORS['green']}{'=' * 90}{COLORS['reset']}")
+ except FileNotFoundError:
+ print(f"{COLORS['red']}File not found: {file_path}{COLORS['reset']}")
+ except json.JSONDecodeError:
+ print(f"{COLORS['red']}Invalid JSON file: {file_path}{COLORS['reset']}")
+ except Exception as exc:
+ print(f"{COLORS['red']}Error reading file: {exc}{COLORS['reset']}")
+
+ def _display_variation_results(self, username: str, variation_data: Dict[str, Any]) -> None:
+ scan_info = variation_data.get("scan_info", {})
+ print(f"{COLORS['green']}{'=' * 90}")
+ print(
+ f"{COLORS['blue']}SCAN RESULTS FOR VARIATION: {COLORS['yellow']}{username}"
+ )
+ print(
+ f"{COLORS['blue']}Found: {COLORS['green']}"
+ f"{scan_info.get('found', 0)} | "
+ f"{COLORS['blue']}Maybe: {COLORS['yellow']}"
+ f"{scan_info.get('maybe', 0)} | "
+ f"{COLORS['blue']}Not Found: {COLORS['red']}"
+ f"{scan_info.get('not_found', 0)} | "
+ f"{COLORS['blue']}Errors: {COLORS['red']}"
+ f"{scan_info.get('errors', 0)}"
+ )
+ high_conf = scan_info.get("high_confidence_matches", 0)
+ if high_conf > 0:
+ print(
+ f"{COLORS['blue']}High Confidence Matches: {COLORS['green']}{high_conf}"
+ )
+ print(f"{COLORS['green']}{'=' * 90}")
+ self._print_table_header()
+
+ def sort_key(item):
+ site_info = item[1]
+ status_priority = {"Found": 0, "Maybe": 1, "Not Found": 2}.get(
+ site_info.get("status", ""), 3
+ )
+ confidence = site_info.get("confidence", 0)
+ return (-confidence, status_priority)
+
+ sites = variation_data.get("sites", {})
+ sorted_sites = sorted(sites.items(), key=sort_key)
+ for site_name, info in sorted_sites:
+ status = info.get("status", "Unknown")
+ code = info.get("code", 0)
+ url = info.get("url", "")
+ response_time = info.get("response_time", 0)
+ confidence = info.get("confidence", 0)
+ if status == "Found":
+ status_color = COLORS["green"]
+ elif status == "Maybe":
+ status_color = COLORS["yellow"]
+ else:
+ status_color = COLORS["red"]
+ code_color = COLORS["green"] if code == 200 else COLORS["red"]
+ url_color = status_color
+ display_site = site_name[:20]
+ confidence_str = f" ({confidence}%)" if confidence > 0 else ""
+ print(
+ f"{COLORS['green']}# {COLORS['yellow']}{display_site:20}{COLORS['white']}| "
+ f"{status_color}{status:10}{confidence_str:8}{COLORS['white']}| "
+ f"{code_color}{str(code):^10}{COLORS['white']}| "
+ f"{url_color}{url}{COLORS['reset']} "
+ f"({response_time:.2f}s)"
+ )
+ print(f"{COLORS['green']}{'=' * 90}{COLORS['reset']}")
+
+ def _print_table_header(self) -> None:
+ print(
+ f"{COLORS['blue']}# {COLORS['yellow']}{'SITE':20}{COLORS['blue']}| "
+ f"{COLORS['yellow']}{'STATUS + CONFIDENCE':18}{COLORS['blue']}| "
+ f"{COLORS['yellow']}{'HTTP CODE':10}{COLORS['blue']}| "
+ f"{COLORS['yellow']}URL (RESPONSE TIME){COLORS['reset']}"
+ )
+ print(f"{COLORS['green']}{'#' * 90}{COLORS['reset']}")
diff --git a/core/features.py b/core/features.py
new file mode 100644
index 0000000..c5d9081
--- /dev/null
+++ b/core/features.py
@@ -0,0 +1,33 @@
+from typing import Dict, List
+
+FEATURE_SCHEMA = [
+ "http_200",
+ "http_3xx",
+ "http_404",
+ "http_4xx",
+ "http_5xx",
+ "has_username_in_path",
+ "is_homepage",
+ "has_auth_pattern",
+ "error_keyword_count",
+ "positive_keyword_count",
+ "meta_error_keyword_count",
+ "meta_positive_keyword_count",
+ "profile_section_count",
+ "error_section_count",
+ "img_count",
+ "input_count",
+ "form_count",
+ "title_has_username",
+ "meta_has_username",
+ "response_time",
+ "content_length",
+ "redirect_count",
+ "fingerprint_match_found",
+ "fingerprint_match_not_found",
+]
+
+
+def vectorize_features(features: Dict[str, float]) -> List[float]:
+ """Return features as an ordered list aligned with FEATURE_SCHEMA."""
+ return [float(features.get(name, 0.0)) for name in FEATURE_SCHEMA]
diff --git a/core/fingerprints.py b/core/fingerprints.py
new file mode 100644
index 0000000..65f76cf
--- /dev/null
+++ b/core/fingerprints.py
@@ -0,0 +1,113 @@
+import hashlib
+import json
+from json import JSONDecodeError
+from pathlib import Path
+from typing import Any, Dict, List
+
+
+def _normalize(text: str) -> str:
+ return " ".join(text.strip().lower().split())
+
+
+def _hash_text(text: str) -> str:
+ normalized = _normalize(text)
+ if not normalized:
+ return ""
+ return hashlib.sha256(normalized.encode("utf-8")).hexdigest()
+
+
+def build_fingerprint(raw: Dict[str, Any]) -> Dict[str, str]:
+ """Convert raw fingerprint inputs into hashed signatures."""
+ title_hash = _hash_text(str(raw.get("title", "")))
+ meta_hash = _hash_text(str(raw.get("meta_text", "")))
+ dom_signature = str(raw.get("dom_signature", ""))
+ server = str(raw.get("server", ""))
+ return {
+ "title_hash": title_hash,
+ "meta_hash": meta_hash,
+ "dom_signature": dom_signature,
+ "server": server,
+ }
+
+
+class FingerprintStore:
+ """Persist lightweight fingerprints per site."""
+
+ def __init__(self, path: Path, max_entries_per_label: int = 50) -> None:
+ self.path = path
+ self.max_entries_per_label = max_entries_per_label
+ self.data: Dict[str, Any] = {"sites": {}}
+
+ def load(self, logger=None) -> None:
+ if not self.path.exists():
+ return
+ try:
+ with self.path.open("r", encoding="utf-8") as handle:
+ self.data = json.load(handle)
+ except JSONDecodeError as exc:
+ self.data = {"sites": {}}
+ if logger:
+ logger.warning(
+ "Fingerprint cache is invalid; starting fresh: %s", exc
+ )
+
+ def save(self) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ with self.path.open("w", encoding="utf-8") as handle:
+ json.dump(self.data, handle, indent=2, ensure_ascii=True)
+
+ def _ensure_site(self, site: str) -> Dict[str, List[Dict[str, str]]]:
+ sites = self.data.setdefault("sites", {})
+ return sites.setdefault(site, {"found": [], "not_found": []})
+
+ def add(self, site: str, label: str, fingerprint: Dict[str, str]) -> None:
+ if label not in {"found", "not_found"}:
+ return
+ site_entry = self._ensure_site(site)
+ entries = site_entry[label]
+ key = self._fingerprint_key(fingerprint)
+ if any(self._fingerprint_key(item) == key for item in entries):
+ return
+ entries.append(fingerprint)
+ if len(entries) > self.max_entries_per_label:
+ site_entry[label] = entries[-self.max_entries_per_label :]
+
+ def score(self, site: str, fingerprint: Dict[str, str]) -> Dict[str, int]:
+ site_entry = self.data.get("sites", {}).get(site, {})
+ found_entries = site_entry.get("found", [])
+ missing_entries = site_entry.get("not_found", [])
+
+ match_found = self._count_matches(found_entries, fingerprint)
+ match_missing = self._count_matches(missing_entries, fingerprint)
+
+ return {
+ "match_found": match_found,
+ "match_not_found": match_missing,
+ "score": match_found - match_missing,
+ }
+
+ def _count_matches(
+ self, entries: List[Dict[str, str]], fingerprint: Dict[str, str]
+ ) -> int:
+ score = 0
+ for entry in entries:
+ if entry.get("title_hash") and entry.get("title_hash") == fingerprint.get("title_hash"):
+ score += 2
+ if entry.get("meta_hash") and entry.get("meta_hash") == fingerprint.get("meta_hash"):
+ score += 1
+ if entry.get("dom_signature") and entry.get("dom_signature") == fingerprint.get("dom_signature"):
+ score += 1
+ if entry.get("server") and entry.get("server") == fingerprint.get("server"):
+ score += 1
+ return score
+
+ @staticmethod
+ def _fingerprint_key(fingerprint: Dict[str, str]) -> str:
+ return "|".join(
+ [
+ fingerprint.get("title_hash", ""),
+ fingerprint.get("meta_hash", ""),
+ fingerprint.get("dom_signature", ""),
+ fingerprint.get("server", ""),
+ ]
+ )
diff --git a/core/http.py b/core/http.py
new file mode 100644
index 0000000..6b54c80
--- /dev/null
+++ b/core/http.py
@@ -0,0 +1,120 @@
+import asyncio
+import random
+import time
+from dataclasses import dataclass
+from typing import Dict, Optional
+from urllib.parse import urlparse
+
+import aiohttp
+
+from .rate_limit import DomainRateLimiter
+from .config import ScannerConfig
+
+
+@dataclass
+class FetchResult:
+ url: str
+ final_url: str
+ status: int
+ content: str
+ response_time: float
+ headers: Dict[str, str]
+ error: Optional[str]
+ redirect_count: int
+
+
+def _should_retry(status: int) -> bool:
+ return status in {408, 429, 500, 502, 503, 504}
+
+
+def _parse_retry_after(headers: Dict[str, str]) -> Optional[float]:
+ value = headers.get("Retry-After")
+ if not value:
+ return None
+ try:
+ return float(value)
+ except ValueError:
+ return None
+
+
+async def fetch_url(
+ session: aiohttp.ClientSession,
+ url: str,
+ config: ScannerConfig,
+ rate_limiter: DomainRateLimiter,
+ logger,
+) -> FetchResult:
+ error_message = None
+ last_status = 0
+ last_headers: Dict[str, str] = {}
+ final_url = url
+ redirect_count = 0
+
+ retry_after = None
+ for attempt in range(config.retries + 1):
+ try:
+ parsed = urlparse(url)
+ await rate_limiter.wait_for_slot(
+ parsed.netloc, config.rate_limit_delay, retry_after
+ )
+
+ start_time = time.monotonic()
+ async with session.get(url, timeout=config.timeout, allow_redirects=True) as response:
+ raw = await response.content.read(config.max_content_bytes)
+ encoding = response.charset or "utf-8"
+ content = raw.decode(encoding, errors="ignore")
+ response_time = time.monotonic() - start_time
+ last_status = response.status
+ last_headers = dict(response.headers)
+ final_url = str(response.url)
+ redirect_count = len(response.history)
+
+ if _should_retry(response.status) and attempt < config.retries:
+ retry_after = _parse_retry_after(last_headers)
+ raise aiohttp.ClientResponseError(
+ request_info=response.request_info,
+ history=response.history,
+ status=response.status,
+ message="retryable status",
+ )
+
+ return FetchResult(
+ url=url,
+ final_url=final_url,
+ status=last_status,
+ content=content,
+ response_time=response_time,
+ headers=last_headers,
+ error=None,
+ redirect_count=redirect_count,
+ )
+ except asyncio.TimeoutError:
+ error_message = "timeout"
+ last_status = 408
+ except aiohttp.ClientResponseError as exc:
+ error_message = str(exc)
+ last_status = exc.status or last_status
+ retry_after = _parse_retry_after(last_headers)
+ except aiohttp.ClientError as exc:
+ error_message = str(exc)
+ except Exception as exc:
+ error_message = str(exc)
+
+ if attempt < config.retries:
+ backoff = min(config.backoff_base * (2 ** attempt), config.backoff_cap)
+ backoff += random.uniform(0.0, config.jitter)
+ if retry_after:
+ backoff = max(backoff, retry_after)
+ await asyncio.sleep(backoff)
+
+ logger.debug("Fetch failed for %s: %s", url, error_message)
+ return FetchResult(
+ url=url,
+ final_url=final_url,
+ status=last_status,
+ content="",
+ response_time=0.0,
+ headers=last_headers,
+ error=error_message,
+ redirect_count=redirect_count,
+ )
diff --git a/core/rate_limit.py b/core/rate_limit.py
new file mode 100644
index 0000000..572349d
--- /dev/null
+++ b/core/rate_limit.py
@@ -0,0 +1,30 @@
+import asyncio
+import time
+from typing import Dict
+
+
+class DomainRateLimiter:
+ """Simple per-domain rate limiting with retry-after support."""
+
+ def __init__(self) -> None:
+ self._locks: Dict[str, asyncio.Lock] = {}
+ self._next_allowed: Dict[str, float] = {}
+ self._global_lock = asyncio.Lock()
+
+ async def wait_for_slot(self, domain: str, min_delay: float, retry_after: float | None) -> None:
+ lock = await self._get_lock(domain)
+ async with lock:
+ now = time.monotonic()
+ next_time = self._next_allowed.get(domain, now)
+ delay = max(0.0, next_time - now)
+ if retry_after:
+ delay = max(delay, retry_after)
+ if delay > 0:
+ await asyncio.sleep(delay)
+ self._next_allowed[domain] = time.monotonic() + min_delay
+
+ async def _get_lock(self, domain: str) -> asyncio.Lock:
+ async with self._global_lock:
+ if domain not in self._locks:
+ self._locks[domain] = asyncio.Lock()
+ return self._locks[domain]
diff --git a/core/scanner.py b/core/scanner.py
new file mode 100644
index 0000000..b5fdc36
--- /dev/null
+++ b/core/scanner.py
@@ -0,0 +1,427 @@
+import asyncio
+import json
+import time
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Dict, List, Tuple
+
+import aiohttp
+
+from .analyzer import FeatureExtractor
+from .browser import BrowserFallback
+from .config import DEFAULT_HEADERS, ScannerConfig
+from .detector import Detector
+from .fingerprints import FingerprintStore, build_fingerprint
+from .http import fetch_url
+from .rate_limit import DomainRateLimiter
+from .variations import generate_username_variations
+from utils.colors import COLORS
+
+
+@dataclass
+class ScanResult:
+ site: str
+ url: str
+ final_url: str
+ status: str
+ code: int
+ response_time: float
+ confidence: int
+ ai_analysis: Dict[str, Any]
+
+
+def load_sites_data() -> Dict[str, str]:
+ """Load sites data from common locations."""
+ base_dir = Path(__file__).resolve().parents[1]
+ bin_dir = Path(__file__).resolve().parents[2]
+ possible_paths = [
+ Path("/usr/local/bin/sites.json"),
+ Path("/usr/local/etc/aliens_eye/sites.json"),
+ Path("/etc/aliens_eye/sites.json"),
+ Path("/data/data/com.termux/files/usr/bin/sites.json"),
+ bin_dir / "sites.json",
+ base_dir / "sites.json",
+ Path("sites.json"),
+ ]
+ for path in possible_paths:
+ if path.exists():
+ with path.open("r", encoding="utf-8") as handle:
+ return json.load(handle)
+ return {}
+
+
+class UsernameScanner:
+ """Coordinates async scanning across all platforms."""
+
+ def __init__(
+ self,
+ sites_data: Dict[str, str],
+ config: ScannerConfig,
+ extractor: FeatureExtractor,
+ detector: Detector,
+ fingerprints: FingerprintStore,
+ logger,
+ browser_fallback: BrowserFallback | None = None,
+ ) -> None:
+ self.sites_data = sites_data
+ self.config = config
+ self.extractor = extractor
+ self.detector = detector
+ self.fingerprints = fingerprints
+ self.logger = logger
+ self.browser_fallback = browser_fallback
+
+ self.results_dir = config.output_dir
+ self.results_dir.mkdir(parents=True, exist_ok=True)
+
+ async def scan_with_variations(
+ self, base_username: str, level: str
+ ) -> Dict[str, List[Dict[str, Any]]]:
+ variations = generate_username_variations(base_username, level)
+ all_results: Dict[str, List[Dict[str, Any]]] = {}
+
+ print(
+ f"\n{COLORS['blue']}Scan level: {COLORS['yellow']}{level.upper()}"
+ )
+ print(
+ f"{COLORS['blue']}Generated {len(variations)} username variations to scan"
+ )
+ if len(variations) > 1:
+ preview = ", ".join(variations[:5])
+ more = f" and {len(variations) - 5} more..." if len(variations) > 5 else ""
+ print(f"{COLORS['yellow']}Variations: {preview}{more}")
+
+ for username in variations:
+ print(
+ f"\n{COLORS['purple']}Scanning variation: {COLORS['yellow']}{username}{COLORS['reset']}"
+ )
+ results = await self.scan_all_sites(username)
+ all_results[username] = results
+
+ return all_results
+
+ async def scan_all_sites(self, username: str) -> List[Dict[str, Any]]:
+ results: List[Dict[str, Any]] = []
+ if not self.sites_data:
+ return results
+
+ conn_limit = max(1, min(self.config.concurrent, len(self.sites_data)))
+ rate_limiter = DomainRateLimiter()
+ queue: asyncio.Queue[Tuple[str, str]] = asyncio.Queue()
+ for site, tmpl in self.sites_data.items():
+ queue.put_nowait((site, tmpl))
+
+ print(
+ f"\n{COLORS['purple']}Scanning '{COLORS['yellow']}{username}{COLORS['purple']}' across "
+ f"{len(self.sites_data)} sites (max {conn_limit} concurrent connections)...{COLORS['reset']}\n"
+ )
+ self._print_table_header()
+
+ connector = aiohttp.TCPConnector(limit=conn_limit)
+ start_time = time.monotonic()
+ async with aiohttp.ClientSession(
+ headers=DEFAULT_HEADERS, connector=connector
+ ) as session:
+ workers = [
+ asyncio.create_task(
+ self._worker(queue, username, session, rate_limiter, results)
+ )
+ for _ in range(conn_limit)
+ ]
+ await queue.join()
+ for worker in workers:
+ worker.cancel()
+ await asyncio.gather(*workers, return_exceptions=True)
+
+ total_time = time.monotonic() - start_time
+ print(f"\n{COLORS['green']}Scan completed in {total_time:.2f} seconds")
+ self._print_summary(results)
+ return results
+
+ async def _worker(
+ self,
+ queue: asyncio.Queue[Tuple[str, str]],
+ username: str,
+ session: aiohttp.ClientSession,
+ rate_limiter: DomainRateLimiter,
+ results: List[Dict[str, Any]],
+ ) -> None:
+ while True:
+ try:
+ site, tmpl = await queue.get()
+ except asyncio.CancelledError:
+ break
+ try:
+ result = await self._scan_site(
+ site, tmpl, username, session, rate_limiter
+ )
+ results.append(result)
+ except Exception as exc:
+ url = self._format_url(site, tmpl, username)
+ self.logger.debug("Worker failed for %s: %s", site, exc)
+ self._print_result_line(site, "Error", 0, 0, url, 0.0)
+ results.append(
+ {
+ "site": site,
+ "url": url,
+ "final_url": url,
+ "status": "Error",
+ "code": 0,
+ "response_time": 0.0,
+ "confidence": 0,
+ "ai_analysis": {"error": str(exc)},
+ }
+ )
+ finally:
+ queue.task_done()
+
+ async def _scan_site(
+ self,
+ site_name: str,
+ url_template: str,
+ username: str,
+ session: aiohttp.ClientSession,
+ rate_limiter: DomainRateLimiter,
+ ) -> Dict[str, Any]:
+ url = self._format_url(site_name, url_template, username)
+ fetch = await fetch_url(session, url, self.config, rate_limiter, self.logger)
+
+ if fetch.error and fetch.status == 408:
+ status_text = "Timeout"
+ elif fetch.error:
+ status_text = "Error"
+ else:
+ status_text = "Unknown"
+
+ ai_analysis: Dict[str, Any] = {}
+ confidence = 0
+ if not fetch.error:
+ try:
+ bundle = self.extractor.extract(
+ fetch.content,
+ fetch.final_url,
+ username,
+ site_name,
+ fetch.status,
+ fetch.response_time,
+ fetch.headers,
+ fetch.redirect_count,
+ )
+ except Exception as exc:
+ self.logger.debug("Feature extraction failed for %s: %s", site_name, exc)
+ status_text = "Error"
+ fetch.status = 0
+ fetch.final_url = fetch.final_url or url
+ ai_analysis = {"error": str(exc)}
+ self._print_result_line(
+ site_name,
+ status_text,
+ confidence,
+ fetch.status,
+ fetch.final_url or url,
+ fetch.response_time,
+ )
+ return {
+ "site": site_name,
+ "url": url,
+ "final_url": fetch.final_url,
+ "status": status_text,
+ "code": fetch.status,
+ "response_time": round(fetch.response_time, 2),
+ "confidence": confidence,
+ "ai_analysis": ai_analysis,
+ }
+
+ fingerprint = build_fingerprint(bundle.fingerprint)
+ fingerprint_score = self.fingerprints.score(site_name, fingerprint)
+ bundle.features["fingerprint_match_found"] = float(
+ fingerprint_score["match_found"]
+ )
+ bundle.features["fingerprint_match_not_found"] = float(
+ fingerprint_score["match_not_found"]
+ )
+
+ detection = self.detector.predict(bundle.features)
+ status_text = detection.status
+ confidence = detection.confidence
+
+ ai_analysis = {
+ "method": detection.method,
+ "score": detection.score,
+ "probability": detection.probability,
+ "features": bundle.features,
+ "signals": bundle.signals,
+ }
+
+ if (
+ status_text == "Maybe"
+ and self.browser_fallback is not None
+ and self.config.use_playwright
+ ):
+ status_text, confidence, ai_analysis = await self._playwright_fallback(
+ site_name,
+ username,
+ url,
+ fetch,
+ ai_analysis,
+ status_text,
+ confidence,
+ )
+
+ if status_text in {"Found", "Not Found"} and confidence >= 85:
+ label = "found" if status_text == "Found" else "not_found"
+ self.fingerprints.add(site_name, label, fingerprint)
+
+ self._print_result_line(
+ site_name,
+ status_text,
+ confidence,
+ fetch.status,
+ fetch.final_url or url,
+ fetch.response_time,
+ )
+
+ return {
+ "site": site_name,
+ "url": url,
+ "final_url": fetch.final_url,
+ "status": status_text,
+ "code": fetch.status,
+ "response_time": round(fetch.response_time, 2),
+ "confidence": confidence,
+ "ai_analysis": ai_analysis,
+ }
+
+ async def _playwright_fallback(
+ self,
+ site_name: str,
+ username: str,
+ url: str,
+ fetch,
+ ai_analysis: Dict[str, Any],
+ status_text: str,
+ confidence: int,
+ ) -> Tuple[str, int, Dict[str, Any]]:
+ try:
+ content, final_url = await self.browser_fallback.fetch(url)
+ except Exception as exc:
+ self.logger.debug("Playwright fallback failed for %s: %s", site_name, exc)
+ return status_text, confidence, ai_analysis
+
+ bundle = self.extractor.extract(
+ content,
+ final_url,
+ username,
+ site_name,
+ fetch.status,
+ fetch.response_time,
+ fetch.headers,
+ fetch.redirect_count,
+ )
+ fingerprint = build_fingerprint(bundle.fingerprint)
+ fingerprint_score = self.fingerprints.score(site_name, fingerprint)
+ bundle.features["fingerprint_match_found"] = float(
+ fingerprint_score["match_found"]
+ )
+ bundle.features["fingerprint_match_not_found"] = float(
+ fingerprint_score["match_not_found"]
+ )
+
+ detection = self.detector.predict(bundle.features)
+ if detection.confidence > confidence or detection.status != "Maybe":
+ return detection.status, detection.confidence, {
+ "method": f"playwright-{detection.method}",
+ "score": detection.score,
+ "probability": detection.probability,
+ "features": bundle.features,
+ "signals": bundle.signals,
+ }
+
+ return status_text, confidence, ai_analysis
+
+ @staticmethod
+ def _format_url(site_name: str, url_template: str, username: str) -> str:
+ try:
+ url = url_template.format(username)
+ except (KeyError, IndexError):
+ url = url_template.replace("{}", username)
+ if "{" in url:
+ url = f"https://{site_name}.com/{username}"
+ except Exception:
+ url = f"https://{site_name}.com/{username}"
+ return url
+
+ def _print_table_header(self) -> None:
+ print(
+ f"{COLORS['blue']}# {COLORS['yellow']}{'SITE':20}{COLORS['blue']}| "
+ f"{COLORS['yellow']}{'STATUS + CONFIDENCE':18}{COLORS['blue']}| "
+ f"{COLORS['yellow']}{'HTTP CODE':10}{COLORS['blue']}| "
+ f"{COLORS['yellow']}URL (RESPONSE TIME){COLORS['reset']}"
+ )
+ print(f"{COLORS['green']}{'#' * 90}{COLORS['reset']}")
+
+ def _print_result_line(
+ self,
+ site_name: str,
+ status_text: str,
+ confidence: int,
+ code: int,
+ url: str,
+ response_time: float,
+ ) -> None:
+ if status_text == "Found":
+ status_color = COLORS["green"]
+ elif status_text == "Maybe":
+ status_color = COLORS["yellow"]
+ else:
+ status_color = COLORS["red"]
+
+ code_color = COLORS["green"] if code == 200 else COLORS["red"]
+ url_color = status_color
+ display_site = site_name[:20]
+ confidence_str = f" ({confidence}%)" if confidence > 0 else ""
+
+ print(
+ f"{COLORS['green']}# {COLORS['yellow']}{display_site:20}{COLORS['white']}| "
+ f"{status_color}{status_text:10}{confidence_str:8}{COLORS['white']}| "
+ f"{code_color}{str(code):^10}{COLORS['white']}| "
+ f"{url_color}{url}{COLORS['reset']} "
+ f"({response_time:.2f}s)"
+ )
+
+ def _print_summary(self, results: List[Dict[str, Any]]) -> None:
+ found_count = sum(1 for r in results if r["status"] == "Found")
+ maybe_count = sum(1 for r in results if r["status"] == "Maybe")
+ not_found_count = sum(1 for r in results if r["status"] == "Not Found")
+ error_count = sum(
+ 1
+ for r in results
+ if r["status"] not in {"Found", "Not Found", "Maybe"}
+ )
+ high_confidence = [
+ r
+ for r in results
+ if r.get("confidence", 0) >= 85 and r["status"] == "Found"
+ ]
+
+ print(
+ f"\n{COLORS['green']}Found: {found_count} | "
+ f"{COLORS['yellow']}Maybe: {maybe_count} | "
+ f"{COLORS['red']}Not Found: {not_found_count} | Errors: {error_count}"
+ f"{COLORS['reset']}"
+ )
+ if high_confidence:
+ print(
+ f"\n{COLORS['green']}High confidence matches ({len(high_confidence)}):"
+ f"{COLORS['reset']}"
+ )
+ for result in high_confidence[:5]:
+ print(
+ f"{COLORS['yellow']}{result['site']}: {COLORS['green']}{result['url']}"
+ f"{COLORS['reset']} ({result['confidence']}% confidence)"
+ )
+ if len(high_confidence) > 5:
+ print(
+ f"{COLORS['yellow']}... and {len(high_confidence) - 5} more"
+ f"{COLORS['reset']}"
+ )
diff --git a/core/variations.py b/core/variations.py
new file mode 100644
index 0000000..c8a6073
--- /dev/null
+++ b/core/variations.py
@@ -0,0 +1,80 @@
+from typing import List
+
+
+def generate_username_variations(username: str, level: str) -> List[str]:
+ """Generate username variations based on scan level."""
+ variations = [username]
+ if level == "basic":
+ return variations
+
+ if level in {"intermediate", "advanced"}:
+ variations.extend(
+ [
+ f"{username}_",
+ f"_{username}",
+ f"{username}.",
+ f".{username}",
+ f"{username.replace(' ', '_')}",
+ f"{username.replace(' ', '.')}",
+ f"{username}1",
+ f"{username}123",
+ f"{username}007",
+ f"{username}098",
+ f"{username}x",
+ f"__{username}",
+ f"__{username}__",
+ ]
+ )
+
+ if level == "advanced":
+ prefixes = [
+ "real",
+ "official",
+ "the",
+ "its",
+ "im",
+ "actual",
+ "true",
+ "mr",
+ "ms",
+ "dr",
+ "iam",
+ "thisis",
+ "hey",
+ "yo",
+ "only",
+ "itz",
+ "iamthe",
+ "theonly",
+ ]
+ suffixes = [
+ "official",
+ "real",
+ "account",
+ "verified",
+ "original",
+ "tv",
+ "here",
+ "live",
+ "online",
+ "page",
+ "world",
+ "spot",
+ "media",
+ "inc",
+ "group",
+ "team",
+ "zone",
+ "plus",
+ "today",
+ ]
+ for prefix in prefixes:
+ variations.append(f"{prefix}{username}")
+ variations.append(f"{prefix}_{username}")
+ variations.append(f"{prefix}.{username}")
+ for suffix in suffixes:
+ variations.append(f"{username}{suffix}")
+ variations.append(f"{username}_{suffix}")
+ variations.append(f"{username}.{suffix}")
+
+ return list(dict.fromkeys(variations))
diff --git a/install.sh b/install.sh
index 3f977c8..4b1082e 100644
--- a/install.sh
+++ b/install.sh
@@ -24,13 +24,26 @@ check_requirement() {
return 0
}
+# Resolve Python command and keep pip aligned with that interpreter
+resolve_python_cmd() {
+ if command -v python3 >/dev/null 2>&1; then
+ echo "python3"
+ return 0
+ fi
+ if command -v python >/dev/null 2>&1; then
+ echo "python"
+ return 0
+ fi
+ return 1
+}
+
# Trap errors
trap cleanup ERR
clear
-echo -e "${BLUE}╔═══════════════════════════════════════════╗${NC}"
-echo -e "${BLUE}β•‘ ${GREEN}Aliens Eye Installation${BLUE} β•‘${NC}"
-echo -e "${BLUE}β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•${NC}"
+echo -e "${BLUE}===========================================${NC}"
+echo -e "${BLUE} ${GREEN}Aliens Eye Installation${BLUE} ${NC}"
+echo -e "${BLUE}===========================================${NC}"
echo
# Detect environment (Linux or Termux)
@@ -40,6 +53,7 @@ if [ -d "/data/data/com.termux" ]; then
PREFIX="/data/data/com.termux/files/usr"
BIN_DIR="${PREFIX}/bin"
CONFIG_DIR="${PREFIX}/etc/aliens_eye"
+ LIB_DIR="${BIN_DIR}/aliens_eye_lib"
REQUIRES_ROOT=false
else
echo -e "${YELLOW}Linux environment detected${NC}"
@@ -47,6 +61,7 @@ else
PREFIX="/usr/local"
BIN_DIR="${PREFIX}/bin"
CONFIG_DIR="/etc/aliens_eye"
+ LIB_DIR="${BIN_DIR}/aliens_eye_lib"
REQUIRES_ROOT=true
# Check for root on Linux
@@ -60,12 +75,22 @@ fi
# Check for required programs
echo -e "${GREEN}Checking requirements...${NC}"
-check_requirement "pip" || {
- echo -e "${RED}Python pip is required but not installed.${NC}"
+PYTHON_CMD="$(resolve_python_cmd)" || {
+ echo -e "${RED}Error: Python is required but not installed.${NC}"
if [ "$REQUIRES_ROOT" = false ]; then
echo -e "${YELLOW}Run 'pkg install python' in Termux to install it.${NC}"
else
- echo -e "${YELLOW}Install Python and pip on your system and try again.${NC}"
+ echo -e "${YELLOW}Install Python 3.10+ on your system and try again.${NC}"
+ fi
+ exit 1
+}
+
+"${PYTHON_CMD}" -m pip --version >/dev/null 2>&1 || {
+ echo -e "${RED}Error: pip is not available for ${PYTHON_CMD}.${NC}"
+ if [ "$REQUIRES_ROOT" = false ]; then
+ echo -e "${YELLOW}Run 'pkg install python' in Termux to install pip.${NC}"
+ else
+ echo -e "${YELLOW}Install pip for your Python interpreter and try again.${NC}"
fi
exit 1
}
@@ -81,27 +106,32 @@ if [[ ! -f "sites.json" ]]; then
exit 1
fi
+if [[ ! -d "core" || ! -d "utils" ]]; then
+ echo -e "${RED}Error: core/ or utils/ directory not found in current directory.${NC}"
+ exit 1
+fi
+
# Install dependencies if requirements.txt exists
if [[ -f "requirements.txt" ]]; then
echo -e "${GREEN}Installing Python dependencies...${NC}"
if [ "$REQUIRES_ROOT" = true ]; then
# Use --break-system-packages for Linux (requires newer pip)
- pip_version=$(pip --version | awk '{print $2}' | cut -d. -f1)
+ pip_version=$(${PYTHON_CMD} -m pip --version | awk '{print $2}' | cut -d. -f1)
if [ "$pip_version" -ge 23 ]; then
- pip install -r requirements.txt --break-system-packages || {
+ ${PYTHON_CMD} -m pip install -r requirements.txt --break-system-packages || {
echo -e "${RED}Failed to install dependencies.${NC}"
exit 1
}
else
- pip install -r requirements.txt || {
+ ${PYTHON_CMD} -m pip install -r requirements.txt || {
echo -e "${RED}Failed to install dependencies.${NC}"
exit 1
}
fi
else
# Termux doesn't need --break-system-packages
- pip install -r requirements.txt || {
+ ${PYTHON_CMD} -m pip install -r requirements.txt || {
echo -e "${RED}Failed to install dependencies.${NC}"
exit 1
}
@@ -110,6 +140,13 @@ else
echo -e "${YELLOW}No requirements.txt found, skipping dependency installation.${NC}"
fi
+# Install Playwright browser binaries so the fallback is ready to use
+echo -e "${GREEN}Installing Playwright browser binaries...${NC}"
+${PYTHON_CMD} -m playwright install chromium || {
+ echo -e "${RED}Failed to install Playwright browser binaries.${NC}"
+ exit 1
+}
+
# Create config directory if it doesn't exist
echo -e "${GREEN}Setting up configuration directory...${NC}"
mkdir -p "${CONFIG_DIR}" || {
@@ -117,10 +154,21 @@ mkdir -p "${CONFIG_DIR}" || {
exit 1
}
+# Install default config if provided
+if [[ -f "config.json" ]]; then
+ if [[ ! -f "${CONFIG_DIR}/config.json" ]]; then
+ cp "config.json" "${CONFIG_DIR}/config.json" || {
+ echo -e "${RED}Failed to install default config.${NC}"
+ exit 1
+ }
+ fi
+fi
+
# Remove old installations if they exist
echo -e "${GREEN}Cleaning up old installation (if any)...${NC}"
rm -f "${BIN_DIR}/aliens_eye" 2>/dev/null
rm -f "${BIN_DIR}/sites.json" 2>/dev/null
+rm -rf "${LIB_DIR}" 2>/dev/null
# Install program files
echo -e "${GREEN}Installing program files...${NC}"
@@ -129,6 +177,16 @@ cp "aliens_eye.py" "${BIN_DIR}/aliens_eye" || {
exit 1
}
+mkdir -p "${LIB_DIR}" || {
+ echo -e "${RED}Failed to create lib directory.${NC}"
+ exit 1
+}
+
+cp -r "core" "utils" "${LIB_DIR}/" || {
+ echo -e "${RED}Failed to install core modules.${NC}"
+ exit 1
+}
+
cp "sites.json" "${CONFIG_DIR}/sites.json" || {
echo -e "${RED}Failed to install configuration.${NC}"
exit 1
@@ -144,7 +202,7 @@ ln -sf "${CONFIG_DIR}/sites.json" "${BIN_DIR}/sites.json"
# Verify installation
if [[ -x "${BIN_DIR}/aliens_eye" && -f "${CONFIG_DIR}/sites.json" ]]; then
- echo -e "\n${GREEN}βœ“ Installation completed successfully!${NC}"
+ echo -e "\n${GREEN}[OK] Installation completed successfully!${NC}"
if [ "$REQUIRES_ROOT" = true ]; then
echo -e "${YELLOW}You can now run 'aliens_eye' from anywhere in the terminal.${NC}"
@@ -154,7 +212,7 @@ if [[ -x "${BIN_DIR}/aliens_eye" && -f "${CONFIG_DIR}/sites.json" ]]; then
echo -e "${YELLOW}Configuration file is located at: ${CONFIG_DIR}/sites.json${NC}\n"
else
- echo -e "\n${RED}βœ— Installation failed. Please check the error messages above.${NC}"
+ echo -e "\n${RED}[FAIL] Installation failed. Please check the error messages above.${NC}"
exit 1
fi
diff --git a/requirements.txt b/requirements.txt
index 8eaaf92..a7ca3d4 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,5 +1,3 @@
aiohttp>=3.8.0
-asyncio>=3.4.3
-pathlib
-typing
-python-dateutil
+selectolax>=0.3.21
+playwright>=1.42.0
diff --git a/uninstall.sh b/uninstall.sh
index b342c83..4899fdd 100644
--- a/uninstall.sh
+++ b/uninstall.sh
@@ -22,6 +22,7 @@ if [ -d "/data/data/com.termux" ]; then
PREFIX="/data/data/com.termux/files/usr"
BIN_DIR="${PREFIX}/bin"
CONFIG_DIR="${PREFIX}/etc/aliens_eye"
+ LIB_DIR="${BIN_DIR}/aliens_eye_lib"
REQUIRES_ROOT=false
else
echo -e "${YELLOW}Linux environment detected${NC}"
@@ -30,6 +31,7 @@ else
BIN_DIR="${PREFIX}/bin"
ALT_BIN_DIR="/usr/bin"
CONFIG_DIR="/etc/aliens_eye"
+ LIB_DIR="${BIN_DIR}/aliens_eye_lib"
REQUIRES_ROOT=true
# Check for root permissions on Linux
@@ -107,6 +109,10 @@ fi
echo -e "\n${GREEN}Removing configuration files...${NC}"
remove_dir "${CONFIG_DIR}"
+# Remove installed library directory
+echo -e "\n${GREEN}Removing library files...${NC}"
+remove_dir "${LIB_DIR}"
+
# Additional cleanup - remove any leftover files
echo -e "\n${GREEN}Checking for leftover files...${NC}"
if [ "$REQUIRES_ROOT" = true ]; then
diff --git a/utils/__init__.py b/utils/__init__.py
new file mode 100644
index 0000000..90669f2
--- /dev/null
+++ b/utils/__init__.py
@@ -0,0 +1 @@
+"""Utility helpers for Aliens Eye."""
diff --git a/utils/colors.py b/utils/colors.py
new file mode 100644
index 0000000..600497b
--- /dev/null
+++ b/utils/colors.py
@@ -0,0 +1,15 @@
+COLORS = {
+ "red": "\033[31m",
+ "green": "\033[32m",
+ "yellow": "\033[33m",
+ "blue": "\033[36m",
+ "purple": "\033[35m",
+ "white": "\033[37m",
+ "reset": "\033[0m",
+}
+
+
+def color_text(text: str, color: str) -> str:
+ """Wrap text in an ANSI color code."""
+ prefix = COLORS.get(color, "")
+ return f"{prefix}{text}{COLORS['reset']}"
diff --git a/utils/logger.py b/utils/logger.py
new file mode 100644
index 0000000..04c4853
--- /dev/null
+++ b/utils/logger.py
@@ -0,0 +1,16 @@
+import logging
+
+
+def setup_logger(verbose: bool) -> logging.Logger:
+ """Configure the shared logger for the app."""
+ logger = logging.getLogger("username_scanner")
+ if logger.handlers:
+ logger.setLevel(logging.DEBUG if verbose else logging.INFO)
+ return logger
+
+ logger.setLevel(logging.DEBUG if verbose else logging.INFO)
+ handler = logging.StreamHandler()
+ formatter = logging.Formatter("%(levelname)s: %(message)s")
+ handler.setFormatter(formatter)
+ logger.addHandler(handler)
+ return logger