Skip to content

🕵️‍♂️ (2-in-1) Email & Username OSINT suite featuring native MCP support for deep data extraction just from a single Email/Username. Analyzes 2720+ actively maintained scan vectors (210+ email / 2510+ username) for security research, investigations, and digital footprinting.

refactor(core-concurrency): replace ThreadPoolExecutor with asyncio in username scan mode

Kaifdc1a72e6db11
diff --git a/tests/test_helpers.py b/tests/test_helpers.py
index e11aebf..a9bd434 100644
--- a/tests/test_helpers.py
+++ b/tests/test_helpers.py
@@ -2,8 +2,7 @@ import sys
import threading
import json
from types import SimpleNamespace
-from unittest.mock import MagicMock, patch
-
+from unittest.mock import MagicMock, AsyncMock, patch
import pytest
from user_scanner.__main__ import main
@@ -196,32 +195,35 @@ def test_username_file_unreadable(tmp_path, run_main):
assert code == 1
-@patch("httpx.Client")
+@patch("httpx.AsyncClient")
def test_validate_proxy_all_invalid(mock_client):
- instance = mock_client.return_value.__enter__.return_value
+ instance = MagicMock()
+ mock_client.return_value.__aenter__.return_value = instance
response = MagicMock()
response.status_code = 302
- instance.get.return_value = response
+ instance.get = AsyncMock(return_value=response)
proxies = ["http://proxy1.example.com:8080", "http://proxy2.example.com:3128"]
result = helpers.validate_proxies(proxies)
assert result == []
-@patch("httpx.Client")
+@patch("httpx.AsyncClient")
def test_validate_proxy_partially_invalid(mock_client):
def side_effect(*args, **kwargs):
proxy = kwargs.get("proxy")
instance = MagicMock()
if proxy and "invalid" in proxy:
- instance.get.side_effect = Exception("connection failed")
+ instance.get = AsyncMock(side_effect=Exception("connection failed"))
else:
response = MagicMock()
response.status_code = 200
- instance.get.return_value = response
- instance.__enter__.return_value = instance
- instance.__exit__.return_value = None
- return instance
+ instance.get = AsyncMock(return_value=response)
+
+ cm = MagicMock()
+ cm.__aenter__.return_value = instance
+ cm.__aexit__.return_value = None
+ return cm
mock_client.side_effect = side_effect
proxies = ["http://invalid", "socks5://socks-proxy.example.com:1080"]
@@ -234,22 +236,24 @@ def test_validate_proxy_empty_list():
assert result == []
-@patch("httpx.Client")
+@patch("httpx.AsyncClient")
def test_validate_proxy_timeout(mock_client):
- instance = mock_client.return_value.__enter__.return_value
- instance.get.side_effect = helpers.httpx.TimeoutException("timeout")
+ instance = MagicMock()
+ mock_client.return_value.__aenter__.return_value = instance
+ instance.get = AsyncMock(side_effect=helpers.httpx.TimeoutException("timeout"))
proxies = ["http://proxy1.example.com:8080"]
result = helpers.validate_proxies(proxies, timeout=1)
assert result == []
-@patch("httpx.Client")
+@patch("httpx.AsyncClient")
def test_validate_proxy_single_worker(mock_client):
- instance = mock_client.return_value.__enter__.return_value
+ instance = MagicMock()
+ mock_client.return_value.__aenter__.return_value = instance
response = MagicMock()
response.status_code = 200
- instance.get.return_value = response
+ instance.get = AsyncMock(return_value=response)
proxies = ["http://proxy1.example.com:8080", "http://proxy2.example.com:3128"]
result = helpers.validate_proxies(proxies, max_workers=1)
diff --git a/user_scanner/core/email_orchestrator.py b/user_scanner/core/email_orchestrator.py
index 89238df..ac5f92d 100644
--- a/user_scanner/core/email_orchestrator.py
+++ b/user_scanner/core/email_orchestrator.py
@@ -48,7 +48,11 @@ async def _async_worker(
return Result.skipped().update(**params).show(configs)
try:
- res = func(email)
+ import inspect
+ if inspect.iscoroutinefunction(func):
+ res = await func(email)
+ else:
+ res = await asyncio.to_thread(func, email)
result = await res if asyncio.iscoroutine(res) else res
except Exception as e:
result = Result.error(e)
diff --git a/user_scanner/core/engine.py b/user_scanner/core/engine.py
index a5e1187..f3c9952 100644
--- a/user_scanner/core/engine.py
+++ b/user_scanner/core/engine.py
@@ -27,7 +27,7 @@ async def check(module: ModuleType, target: str) -> Result:
if inspect.iscoroutinefunction(func):
result = await func(target)
else:
- result = func(target)
+ result = await asyncio.to_thread(func, target)
except Exception as e:
result = Result.error(e)
diff --git a/user_scanner/core/helpers.py b/user_scanner/core/helpers.py
index 7beb226..b6a3204 100644
--- a/user_scanner/core/helpers.py
+++ b/user_scanner/core/helpers.py
@@ -9,7 +9,7 @@ import os
import random
import threading
import functools
-from concurrent.futures import ThreadPoolExecutor, as_completed
+import asyncio
from dataclasses import dataclass
from typing import Any, Callable
@@ -122,29 +122,36 @@ def find_category(module: ModuleType) -> str | None:
return None
-def validate_proxies(proxy_list: List[str], timeout: int = 5, max_workers: int = 50) -> List[str]:
- """Validate proxies by testing them against google.com. Returns list of working proxies."""
+async def _validate_proxy_async(proxy: str, timeout: int) -> Optional[str]:
+ try:
+ async with httpx.AsyncClient(proxy=proxy, timeout=timeout) as client:
+ response = await client.get("https://www.google.com")
+ if response.status_code == 200:
+ return proxy
+ except Exception:
+ pass
+ return None
+
+async def _validate_proxies_batch(proxy_list: List[str], timeout: int, max_workers: int) -> List[str]:
working_proxies = []
+ sem = asyncio.Semaphore(max_workers)
- def test_proxy(proxy: str) -> Optional[str]:
- try:
- with httpx.Client(proxy=proxy, timeout=timeout) as client:
- response = client.get("https://www.google.com")
- if response.status_code == 200:
- return proxy
- except Exception:
- pass
- return None
+ async def _worker(proxy: str):
+ async with sem:
+ res = await _validate_proxy_async(proxy, timeout)
+ if res:
+ working_proxies.append(res)
- with ThreadPoolExecutor(max_workers=max_workers) as executor:
- futures = {executor.submit(test_proxy, proxy): proxy for proxy in proxy_list}
- for future in as_completed(futures):
- result = future.result()
- if result:
- working_proxies.append(result)
+ tasks = [_worker(proxy) for proxy in proxy_list]
+ if tasks:
+ await asyncio.gather(*tasks)
return working_proxies
+def validate_proxies(proxy_list: List[str], timeout: int = 5, max_workers: int = 50) -> List[str]:
+ """Validate proxies by testing them against google.com. Returns list of working proxies."""
+ return asyncio.run(_validate_proxies_batch(proxy_list, timeout, max_workers))
+
class ProxyManager:
"""Thread-safe proxy manager that loads and rotates proxies from a file."""
diff --git a/user_scanner/core/orchestrator.py b/user_scanner/core/orchestrator.py
index 6271b9f..559ca48 100644
--- a/user_scanner/core/orchestrator.py
+++ b/user_scanner/core/orchestrator.py
@@ -1,7 +1,8 @@
-from concurrent.futures import ThreadPoolExecutor
+import asyncio
+import inspect
from pathlib import Path
from types import ModuleType
-from typing import Callable, List, Dict, Optional
+from typing import Callable, List, Dict, Optional, Set
import threading
import httpx
@@ -20,114 +21,133 @@ from user_scanner.core.helpers import (
from user_scanner.core.result import Result
-def _worker_single(module: ModuleType, username: str, configs: ScanConfig) -> Result:
- site_name = get_site_name(module)
- func = get_scan_func(module)
+MAX_CONCURRENT_REQUESTS = 60
- params = {
- "site_name": site_name.capitalize(),
- "username": username,
- }
+async def _async_worker(
+ module: ModuleType,
+ username: str,
+ sem: asyncio.Semaphore,
+ configs: ScanConfig,
+ printed_cats: Optional[Set] = None,
+ cat_override: Optional[str] = None
+) -> Result:
+ async with sem:
+ site_name = get_site_name(module)
+ func = get_scan_func(module)
+ actual_cat = cat_override or find_category(module) or "Unknown"
+
+ params = {
+ "site_name": site_name.capitalize(),
+ "username": username,
+ "category": actual_cat,
+ }
- if not func:
- return Result.error(f"{site_name} has no validate_ function", **params)
+ if not func:
+ return Result.error(f"{site_name} has no validate_ function", **params).show(configs)
- if not configs.allow_loud and is_loud(site_name):
- return Result.skipped().update(**params)
+ if not configs.allow_loud and is_loud(site_name):
+ return Result.skipped().update(**params).show(configs)
+
+ try:
+ if inspect.iscoroutinefunction(func):
+ res = await func(username)
+ else:
+ res = await asyncio.to_thread(func, username)
+ result = await res if asyncio.iscoroutine(res) else res
+ except Exception as e:
+ result = Result.error(e)
- try:
- result: Result = func(username)
result.update(**params)
- return result
- except Exception as e:
- return Result.error(e, **params)
+ if configs.only_found and result.is_found():
+ if printed_cats is not None and actual_cat not in printed_cats:
+ print(
+ f"\n{Fore.MAGENTA}== {actual_cat.upper()} SITES =={Style.RESET_ALL}"
+ )
+ printed_cats.add(actual_cat)
-def run_user_module(
- module: ModuleType, username: str, configs: ScanConfig
+ return result.show(configs)
+
+
+async def _run_batch(
+ modules: List[ModuleType],
+ username: str,
+ configs: ScanConfig,
+ printed_cats: Optional[Set] = None,
+ module_to_cat: Optional[Dict[str, str]] = None
) -> List[Result]:
- result = _worker_single(module, username, configs)
+ sem = asyncio.Semaphore(MAX_CONCURRENT_REQUESTS)
+ tasks = []
+ for module in modules:
+ site_key = get_site_name(module).capitalize()
+ cat_override = module_to_cat.get(site_key) if module_to_cat else None
+ tasks.append(
+ _async_worker(
+ module,
+ username,
+ sem,
+ configs,
+ printed_cats=printed_cats,
+ cat_override=cat_override
+ )
+ )
- category = find_category(module)
- if category:
- result.update(category=category)
+ if not tasks:
+ return []
+ return list(await asyncio.gather(*tasks))
- # Use the result.show logic which handles the only_found filtering
- result.show(configs)
- return [result]
+def run_user_module(
+ module: ModuleType, username: str, configs: ScanConfig
+) -> List[Result]:
+ return asyncio.run(_run_batch([module], username, configs))
def run_user_category(
category_path: Path, username: str, configs: ScanConfig
) -> List[Result]:
category_name = category_path.stem.capitalize()
- results = []
modules = load_modules(category_path)
- header_printed = False
-
- with ThreadPoolExecutor(max_workers=20) as executor:
- # map returns results as they are finished, allowing for "streaming" output
- exec_map = executor.map(lambda m: _worker_single(m, username, configs), modules)
- for result in exec_map:
- result.update(category=category_name)
- results.append(result)
-
- if configs.only_found:
- if result.is_found():
- if not header_printed:
- print(
- f"\n{Fore.MAGENTA}== {category_name.upper()} SITES =={Style.RESET_ALL}"
- )
- header_printed = True
- result.show(configs)
- else:
- if not header_printed:
- print(
- f"\n{Fore.MAGENTA}== {category_name.upper()} SITES =={Style.RESET_ALL}"
- )
- header_printed = True
- result.show(configs)
-
- return results
+ printed_cats = set()
+
+ if not configs.only_found:
+ print(f"\n{Fore.MAGENTA}== {category_name.upper()} SITES =={Style.RESET_ALL}")
+ printed_cats.add(category_name)
+
+ return asyncio.run(
+ _run_batch(
+ modules,
+ username,
+ configs,
+ printed_cats=printed_cats,
+ )
+ )
def run_user_full(username: str, configs: ScanConfig) -> List[Result]:
- results = []
- all_modules = []
categories = list(load_categories(no_nsfw=configs.no_nsfw).items())
- module_to_cat = {}
- printed_categories = set()
+ all_results = []
+ printed_cats = set()
for cat_name, cat_path in categories:
modules = load_modules(cat_path)
display_name = cat_name.capitalize()
- for m in modules:
- all_modules.append(m)
- # Match the worker's capitalization exactly to prevent "Unknown" category bugs
- site_key = get_site_name(m).capitalize()
- module_to_cat[site_key] = display_name
-
- with ThreadPoolExecutor(max_workers=60) as executor:
- exec_map = executor.map(
- lambda m: _worker_single(m, username, configs), all_modules
- )
- for result in exec_map:
- cat_name = module_to_cat.get(result.site_name, "Unknown") if result.site_name else "Unknown"
-
- result.update(category=cat_name)
- results.append(result)
-
- if configs.only_found and not result.is_found():
- continue
- if cat_name not in printed_categories:
- print(f"\n{Fore.MAGENTA}== {cat_name.upper()} SITES =={Style.RESET_ALL}")
- printed_categories.add(cat_name)
-
- result.show(configs)
+ if not configs.only_found:
+ print(f"\n{Fore.MAGENTA}== {display_name.upper()} SITES =={Style.RESET_ALL}")
+ printed_cats.add(display_name)
+
+ cat_results = asyncio.run(
+ _run_batch(
+ modules,
+ username,
+ configs,
+ printed_cats=printed_cats,
+ )
+ )
+ all_results.extend(cat_results)
- return results
+ return all_results