π΅οΈββοΈ (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.
Python cybersecuritycybersecurity-toolsemail-osintethical-hackingethical-hacking-toolsidentificationinfosecosintosint-emailosint-toolosint-toolsosint-usernamepentestingpythonredteam-toolsredteamingthreat-intelligence
feat(export): add PDF report generator and --format pdf export option
Kaif4e2248cb5a94
diff --git a/pyproject.toml b/pyproject.tomlindex c1184d7..138554e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -24,6 +24,7 @@ keywords = ["osint", "email-osint", "username-osint", "python", "cli-tool", "cyb[project.optional-dependencies]dev = ["pytest", "pytest-cov", "pytest-anyio", "anyio[trio]"]+pdf = ["reportlab>=4.0.0", "pillow>=10.0.0", "svglib>=1.5.0"][project.urls]Homepage = "https://github.com/kaifcodec/user-scanner"diff --git a/tests/test_pdf_generator.py b/tests/test_pdf_generator.pynew file mode 100644index 0000000..8562dfb--- /dev/null+++ b/tests/test_pdf_generator.py@@ -0,0 +1,70 @@+import pytest+from user_scanner.core.result import Result+from user_scanner.core.formatter import into_pdf+from user_scanner.core.pdf_generator import generate_pdf_report, REPORTLAB_AVAILABLE++[email protected](not REPORTLAB_AVAILABLE, reason="ReportLab not installed")+def test_generate_pdf_report_basic():+ results = [+ Result.taken(+ site_name="GitHub",+ category="Dev",+ url="https://github.com/testuser",+ extra={+ "name": "Test User",+ "bio": "Open Source Developer",+ "followers": "100",+ "avatar": "https://avatars.githubusercontent.com/u/1?v=4",+ },+ ),+ Result.available(site_name="Twitter", category="Social", url="https://twitter.com/testuser"),+ ]++ pdf_bytes = generate_pdf_report(+ target="testuser",+ scan_type="Username",+ results=results,+ total_modules=2,+ include_media=True,+ version="1.4.1.9",+ )++ assert isinstance(pdf_bytes, bytes)+ assert len(pdf_bytes) > 0+ assert pdf_bytes.startswith(b"%PDF-")++[email protected](not REPORTLAB_AVAILABLE, reason="ReportLab not installed")+def test_formatter_into_pdf():+ results = [+ Result.taken(+ site_name="GitHub",+ category="Dev",+ url="https://github.com/testuser",+ extra={"name": "Test User"},+ )+ ]++ pdf_bytes = into_pdf(+ results=results,+ target="[email protected]",+ scan_type="Email",+ total_modules=10,+ include_media=False,+ version="1.4.1.9",+ )++ assert isinstance(pdf_bytes, bytes)+ assert pdf_bytes.startswith(b"%PDF-")+++def test_pdf_no_reportlab_import_error(monkeypatch):+ import user_scanner.core.pdf_generator as pdf_gen++ monkeypatch.setattr(pdf_gen, "REPORTLAB_AVAILABLE", False)++ with pytest.raises(ImportError) as exc_info:+ generate_pdf_report("target", "Username", [])++ assert "ReportLab is required for PDF generation" in str(exc_info.value)diff --git a/user_scanner/__main__.py b/user_scanner/__main__.pyindex 2ef236c..9b190dd 100644--- a/user_scanner/__main__.py+++ b/user_scanner/__main__.py@@ -118,7 +118,13 @@ def main():"-d", "--delay", type=float, default=0, help="Delay between requests")- parser.add_argument("-f", "--format", choices=["csv", "json"], help="Output format")+ parser.add_argument("-f", "--format", choices=["csv", "json", "pdf"], help="Output format")++ parser.add_argument(+ "--no-pdf-media",+ action="store_true",+ help="Disable profile photo media fetching in PDF report generation",+ )parser.add_argument("-o", "--output", type=str, help="Output file path")@@ -424,46 +430,60 @@ def main():if args.hudson_scan:sys.exit(0)- if args.output:- content = (- formatter.into_csv(results)- if args.format == "csv"- else formatter.into_json(results)- )- if args.format == "json":- # Get the new data as a LIST of DICTS, not a string+ is_pdf_export = args.format == "pdf" or (args.output and args.output.lower().endswith(".pdf"))++ if args.output or is_pdf_export:+ output_path = args.output or f"{targets_found[0] if targets_found else 'target'}_report.pdf"++ if is_pdf_export:+ version_str, _ = load_local_version()+ try:+ pdf_bytes = formatter.into_pdf(+ results,+ target=targets_found[0] if targets_found else "Target",+ scan_type="Email" if is_email else "Username",+ total_modules=len(results),+ include_media=not args.no_pdf_media,+ version=version_str,+ )+ with open(output_path, "wb") as f:+ f.write(pdf_bytes)+ print(G + f"\n[+] PDF report saved to {output_path}" + Style.RESET_ALL)+ except ImportError as e:+ print(f"\n{R}[β] PDF export failed: {e}{X}")+ except Exception as e:+ print(f"\n{R}[β] Failed to generate PDF report: {e}{X}")+ elif args.format == "json":new_items = formatter.get_json_data(results)data = []- # Try to load existing data- if os.path.exists(args.output):+ if os.path.exists(output_path):try:- with open(args.output, "r", encoding="utf-8") as f:+ with open(output_path, "r", encoding="utf-8") as f:old = json.load(f)if isinstance(old, list):data = oldexcept (json.JSONDecodeError, Exception):pass- # Merge and savedata.extend(new_items)- with open(args.output, "w", encoding="utf-8") as f:+ with open(output_path, "w", encoding="utf-8") as f:json.dump(data, f, indent=2, ensure_ascii=False)--- if args.format == "csv":+ print(G + f"\n[+] Results saved to {output_path}" + Style.RESET_ALL)+ else:+ content = formatter.into_csv(results) if args.format == "csv" else formatter.into_json(results)try:- with open(args.output, "r", encoding="utf-8") as init_file:+ with open(output_path, "r", encoding="utf-8") as init_file:has_content = init_file.read().strip() != ""except Exception:has_content = False- with open(args.output, "a", encoding="utf-8") as f:+ with open(output_path, "a", encoding="utf-8") as f:if has_content:f.write("\n")f.write(content)+ print(G + f"\n[+] Results saved to {output_path}" + Style.RESET_ALL)- print(G + f"\n[+] Results saved to {args.output}" + Style.RESET_ALL)total_found = len([r for r in results if r.is_found()])total_skipped = len([r for r in results if r.status == Status.SKIPPED])diff --git a/user_scanner/core/formatter.py b/user_scanner/core/formatter.pyindex adc6033..213ef39 100644--- a/user_scanner/core/formatter.py+++ b/user_scanner/core/formatter.py@@ -17,3 +17,24 @@ def get_json_data(results: List[Result]) -> list:def into_csv(results: List[Result]) -> str:return CSV_HEADER + "\n" + "\n".join(result.to_csv() for result in results)+++def into_pdf(+ results: List[Result],+ target: str = "Target",+ scan_type: str = "Unknown",+ total_modules: int = None,+ include_media: bool = True,+ version: str = None,+) -> bytes:+ from user_scanner.core.pdf_generator import generate_pdf_report++ return generate_pdf_report(+ target=target,+ scan_type=scan_type,+ results=results,+ total_modules=total_modules,+ include_media=include_media,+ version=version,+ )+diff --git a/user_scanner/core/pdf_generator.py b/user_scanner/core/pdf_generator.pynew file mode 100644index 0000000..a3e70ad--- /dev/null+++ b/user_scanner/core/pdf_generator.py@@ -0,0 +1,486 @@+import io+import json+from datetime import datetime+from typing import List, Dict, Any, Union, Optional++import httpx++try:+ from reportlab.lib.pagesizes import A4+ from reportlab.lib import colors+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle+ from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, Image as RLImage, KeepTogether+ from reportlab.lib.units import inch+ REPORTLAB_AVAILABLE = True+except ImportError:+ REPORTLAB_AVAILABLE = False++try:+ from PIL import Image as PILImage+ PIL_AVAILABLE = True+except ImportError:+ PIL_AVAILABLE = False++try:+ from svglib.svglib import svg2rlg+ SVGLIB_AVAILABLE = True+except ImportError:+ SVGLIB_AVAILABLE = False+++def truncate(val: Any, max_length: int = 300) -> str:+ if val is None:+ return ""+ if isinstance(val, (dict, list)):+ try:+ s = json.dumps(val)+ except Exception:+ s = str(val)+ else:+ s = str(val)++ s = "".join([c for c in s if ord(c) < 128])+ if len(s) > max_length:+ return s[:max_length] + "..."+ return s+++def clean_metadata(extra: Any) -> List[tuple]:+ if not extra or not isinstance(extra, dict):+ return []+ return [(k, v) for k, v in extra.items() if k not in ["avatar", "image"]]+++def fetch_and_resize_image(url: str, size: tuple = (60, 60)) -> Optional[Any]:+ if not PIL_AVAILABLE:+ return None+ try:+ resp = httpx.get(+ url,+ headers={+ "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"+ },+ timeout=3.0,+ follow_redirects=True,+ )+ if resp.status_code == 200:+ content_type = resp.headers.get("Content-Type", "")+ if SVGLIB_AVAILABLE and ("svg" in content_type.lower() or url.lower().endswith(".svg")):+ try:+ drawing = svg2rlg(io.BytesIO(resp.content))+ if drawing and hasattr(drawing, "width") and hasattr(drawing, "height") and drawing.width > 0 and drawing.height > 0:+ sx = size[0] / drawing.width+ sy = size[1] / drawing.height+ s = min(sx, sy)+ drawing.scale(s, s)+ drawing.width = drawing.width * s+ drawing.height = drawing.height * s+ return drawing+ except Exception:+ pass++ img = PILImage.open(io.BytesIO(resp.content))+ img = img.convert("RGB")++ # Crop to square+ min_dim = min(img.width, img.height)+ left = (img.width - min_dim) / 2+ top = (img.height - min_dim) / 2+ right = (img.width + min_dim) / 2+ bottom = (img.height + min_dim) / 2+ img = img.crop((left, top, right, bottom))+ img = img.resize(size, PILImage.Resampling.LANCZOS)++ img_byte_arr = io.BytesIO()+ img.save(img_byte_arr, format="JPEG")+ img_byte_arr.seek(0)+ return img_byte_arr+ except Exception:+ pass+ return None+++def generate_pdf_report(+ target: str,+ scan_type: str,+ results: List[Any],+ total_modules: Optional[int] = None,+ include_media: bool = True,+ version: Optional[str] = None,+) -> bytes:+ if not REPORTLAB_AVAILABLE:+ raise ImportError(+ "ReportLab is required for PDF generation. "+ "Please install it using: pip install user-scanner[pdf] or pip install reportlab pillow svglib"+ )++ # Convert Result objects to dicts if needed+ raw_results = []+ for r in results:+ if hasattr(r, "to_dict"):+ raw_results.append(r.to_dict())+ elif isinstance(r, dict):+ raw_results.append(r)++ if total_modules is None:+ total_modules = len(raw_results)++ buffer = io.BytesIO()+ doc = SimpleDocTemplate(+ buffer,+ pagesize=A4,+ rightMargin=30,+ leftMargin=30,+ topMargin=30,+ bottomMargin=30,+ )++ styles = getSampleStyleSheet()++ header_brand_style = ParagraphStyle(+ "HeaderBrand",+ parent=styles["Normal"],+ fontSize=8,+ leading=10,+ textColor=colors.HexColor("#555555"),+ fontName="Helvetica-Bold",+ )+ header_title_style = ParagraphStyle(+ "HeaderTitle",+ parent=styles["Normal"],+ fontSize=18,+ leading=22,+ textColor=colors.black,+ fontName="Helvetica-Bold",+ )+ header_subtitle_style = ParagraphStyle(+ "HeaderSubtitle",+ parent=styles["Normal"],+ fontSize=8,+ leading=10,+ textColor=colors.HexColor("#555555"),+ fontName="Helvetica",+ )+ date_right_style = ParagraphStyle(+ "DateRight",+ parent=styles["Normal"],+ fontSize=7,+ leading=9,+ textColor=colors.HexColor("#666666"),+ alignment=2, # Right align+ )+ section_title_style = ParagraphStyle(+ "SectionTitle",+ parent=styles["Heading2"],+ fontSize=12,+ leading=15,+ textColor=colors.black,+ spaceBefore=15,+ spaceAfter=10,+ fontName="Helvetica-Bold",+ )+ normal_style = styles["Normal"]++ elements = []+ date_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")++ version_str = f" v{version}" if version else ""++ header_left = [+ Paragraph(f"USER SCANNER{version_str.upper()}", header_brand_style),+ Spacer(1, 2),+ Paragraph("INTELLIGENCE DOSSIER", header_title_style),+ Spacer(1, 2),+ Paragraph("AUTOMATED OSINT EXTRACTION", header_subtitle_style),+ ]++ header_right = [+ Paragraph(+ "<font size=9 color='#dc2626' name='Helvetica-Bold'>CONFIDENTIAL / INTERNAL</font><br/>"+ + date_str,+ date_right_style,+ )+ ]++ # Header Table+ header_data = [[header_left, header_right]]+ header_table = Table(header_data, colWidths=[4.2 * inch, 2.8 * inch])+ header_table.setStyle(+ TableStyle(+ [+ ("VALIGN", (0, 0), (-1, -1), "BOTTOM"),+ ("LINEBELOW", (0, 0), (-1, -1), 1, colors.HexColor("#222222")),+ ("BOTTOMPADDING", (0, 0), (-1, -1), 8),+ ]+ )+ )+ elements.append(header_table)+ elements.append(Spacer(1, 20))++ hits = [+ r+ for r in raw_results+ if str(r.get("status", "")).lower() in ["found", "registered", "taken"]+ ]++ # Summary Box+ summary_data = [+ [+ Paragraph(+ f"<font size=7 color='#6b7280'>SUBJECT TARGET</font><br/><font size=10 name='Helvetica-Bold'>{target}</font>",+ normal_style,+ ),+ Paragraph(+ f"<font size=7 color='#6b7280'>SCAN PARAMETER</font><br/><font size=10 name='Helvetica-Bold'>{scan_type.upper()}</font>",+ normal_style,+ ),+ Paragraph(+ f"<font size=7 color='#6b7280'>DATE OF REPORT</font><br/><font size=10 name='Helvetica-Bold'>{date_str}</font>",+ normal_style,+ ),+ Paragraph(+ f"<font size=7 color='#6b7280'>TOTAL FINDINGS</font><br/><font size=10 name='Helvetica-Bold'>{len(hits)} Hits across {total_modules} vectors</font>",+ normal_style,+ ),+ ]+ ]+ summary_table = Table(summary_data, colWidths=[1.8 * inch] * 4)+ summary_table.setStyle(+ TableStyle(+ [+ ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#fafafa")),+ ("BOX", (0, 0), (-1, -1), 1, colors.HexColor("#e5e7eb")),+ ("PADDING", (0, 0), (-1, -1), 10),+ ("VALIGN", (0, 0), (-1, -1), "TOP"),+ ]+ )+ )+ elements.append(summary_table)++ # Profile Photos Grid+ if include_media and PIL_AVAILABLE:+ unique_photos = {}+ for idx, hit in enumerate(hits):+ extra = hit.get("extra", {})+ if isinstance(extra, dict):+ url = extra.get("avatar") or extra.get("image")+ if url and isinstance(url, str) and url not in unique_photos:+ unique_photos[url] = {+ "site": hit.get("site_name", "Unknown"),+ "slNo": idx + 1,+ }++ if unique_photos:+ elements.append(+ Paragraph("IDENTIFIED PROFILE MEDIA", section_title_style)+ )++ photo_cells = []+ for url, info in unique_photos.items():+ img_io_or_drawing = fetch_and_resize_image(url)+ if img_io_or_drawing:+ if isinstance(img_io_or_drawing, io.BytesIO):+ rl_img = RLImage(img_io_or_drawing, width=60, height=60)+ else:+ rl_img = img_io_or_drawing+ caption = Paragraph(+ f"<font size=6 color='#6b7280'>{info['slNo']}. {info['site']}</font>",+ ParagraphStyle("c", alignment=1),+ )+ photo_cells.append([rl_img, caption])++ if photo_cells:+ row = []+ grid_data = []+ for cell in photo_cells:+ cell_table = Table(+ [[cell[0]], [cell[1]]], colWidths=[65], rowHeights=[65, 15]+ )+ cell_table.setStyle(+ TableStyle(+ [+ ("ALIGN", (0, 0), (-1, -1), "CENTER"),+ ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),+ (+ "BOX",+ (0, 0),+ (0, 0),+ 1,+ colors.HexColor("#e5e7eb"),+ ),+ (+ "BACKGROUND",+ (0, 0),+ (0, 0),+ colors.HexColor("#f3f4f6"),+ ),+ ]+ )+ )+ row.append(cell_table)+ if len(row) == 7:+ grid_data.append(row)+ row = []+ if row:+ while len(row) < 7:+ row.append("")+ grid_data.append(row)++ grid_table = Table(grid_data)+ grid_table.setStyle(+ TableStyle(+ [+ ("VALIGN", (0, 0), (-1, -1), "TOP"),+ ("ALIGN", (0, 0), (-1, -1), "CENTER"),+ ]+ )+ )+ elements.append(grid_table)+ elements.append(Spacer(1, 10))++ # Footprint Table+ elements.append(Paragraph("DIGITAL FOOTPRINT MAPPING", section_title_style))++ table_data = [+ [+ Paragraph(+ "<font size=8 name='Helvetica-Bold' color='#374151'>SL</font>",+ normal_style,+ ),+ Paragraph(+ "<font size=8 name='Helvetica-Bold' color='#374151'>PLATFORM</font>",+ normal_style,+ ),+ Paragraph(+ "<font size=8 name='Helvetica-Bold' color='#374151'>CATEGORY</font>",+ normal_style,+ ),+ Paragraph(+ "<font size=8 name='Helvetica-Bold' color='#374151'>STATUS</font>",+ normal_style,+ ),+ Paragraph(+ "<font size=8 name='Helvetica-Bold' color='#374151'>IDENTIFIED URL</font>",+ normal_style,+ ),+ ]+ ]++ for idx, hit in enumerate(hits):+ status = str(hit.get("status", "Unknown"))+ status_color = (+ "#16a34a"+ if status.lower() in ["found", "registered", "taken"]+ else "#111111"+ )+ url_text = truncate(hit.get("url", "N/A"), 100)++ table_data.append(+ [+ Paragraph(+ f"<font size=8>{idx + 1}</font>",+ ParagraphStyle("C", alignment=1),+ ),+ Paragraph(+ f"<font size=8>{hit.get('site_name', '')}</font>", normal_style+ ),+ Paragraph(+ f"<font size=8>{hit.get('category', '')}</font>", normal_style+ ),+ Paragraph(+ f"<font size=8 color='{status_color}'>{status}</font>",+ normal_style,+ ),+ Paragraph(+ f"<font size=7 color='#2563eb'>{url_text}</font>", normal_style+ ),+ ]+ )++ data_table = Table(+ table_data,+ colWidths=[0.5 * inch, 1.5 * inch, 1.2 * inch, 1.0 * inch, 3.1 * inch],+ repeatRows=1,+ )+ data_table.setStyle(+ TableStyle(+ [+ ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#f3f4f6")),+ ("BOX", (0, 0), (-1, -1), 1, colors.HexColor("#e5e7eb")),+ ("INNERGRID", (0, 0), (-1, -1), 1, colors.HexColor("#e5e7eb")),+ ("VALIGN", (0, 0), (-1, -1), "MIDDLE"),+ ("BOTTOMPADDING", (0, 0), (-1, 0), 5),+ ("TOPPADDING", (0, 0), (-1, 0), 5),+ ]+ )+ )+ elements.append(data_table)++ # Deep Metadata Cards+ hits_with_meta = []+ for hit in hits:+ meta = clean_metadata(hit.get("extra"))+ if meta:+ hits_with_meta.append((hit, meta))++ if hits_with_meta:+ elements.append(+ Paragraph("EXTRACTED DEEP INTELLIGENCE", section_title_style)+ )++ for hit, meta in hits_with_meta:+ meta_elements = [+ Paragraph(+ f"<font size=10 name='Helvetica-Bold'>{hit.get('site_name', '')}</font>",+ normal_style,+ ),+ Spacer(1, 5),+ ]++ meta_grid = []+ row = []+ for k, v in meta:+ key_para = f"<font size=7 color='#6b7280'>{str(k).replace('_', ' ').upper()}</font>"+ val_para = (+ f"<font size=8 color='#1f2937'>{truncate(v, 200)}</font>"+ )+ cell = Paragraph(f"{key_para}<br/>{val_para}", normal_style)+ row.append(cell)+ if len(row) == 2:+ meta_grid.append(row)+ row = []+ if row:+ row.append("")+ meta_grid.append(row)++ if meta_grid:+ m_table = Table(meta_grid, colWidths=[3.6 * inch, 3.6 * inch])+ m_table.setStyle(+ TableStyle(+ [+ ("VALIGN", (0, 0), (-1, -1), "TOP"),+ ("BOTTOMPADDING", (0, 0), (-1, -1), 3),+ ("TOPPADDING", (0, 0), (-1, -1), 0),+ ]+ )+ )+ meta_elements.append(m_table)++ block_table = Table([[meta_elements]], colWidths=[7.2 * inch])+ block_table.setStyle(+ TableStyle(+ [+ ("BACKGROUND", (0, 0), (-1, -1), colors.HexColor("#f9fafb")),+ ("BOX", (0, 0), (-1, -1), 1, colors.HexColor("#f3f4f6")),+ ("PADDING", (0, 0), (-1, -1), 8),+ ("BOTTOMPADDING", (0, 0), (-1, -1), 12),+ ]+ )+ )++ elements.append(KeepTogether(block_table))+ elements.append(Spacer(1, 10))++ doc.build(elements)+ buffer.seek(0)+ return buffer.read()