Skip to main content

A lightweight AI-powered cybersecurity toolkit for phishing detection

Project description

๐Ÿ” SafeTrace

License: MIT Python 3.9+ Version

Lightweight AI-powered cybersecurity toolkit for phishing detection.

SafeTrace is a CLI-first Python package that lets developers scan URLs and text for phishing or malicious patterns using machine learning. It ships with auto-training models, a professional command-line interface, and a modular Python API.


๐Ÿค” Why SafeTrace?

Most phishing detection tools are either enterprise-grade SaaS products or unmaintained research projects. SafeTrace fills the gap:

  • Zero setup friction โ€” models auto-train on first run, no manual steps.
  • CLI-first โ€” pipe it into scripts, CI pipelines, or security audits.
  • Explainable โ€” every scan tells you why something is suspicious, not just a score.
  • Lightweight โ€” only 3 dependencies (scikit-learn, joblib, numpy). No cloud, no API keys.
  • Extensible โ€” add your own patterns in config.py, retrain with safetrace train.

โœจ Features

Feature Description
URL Scanner Extracts 15 structural features and classifies via Random Forest
Email Analyser TF-IDF + Logistic Regression + rule-based pattern matching
Batch Processing Scan entire files of URLs or emails in one command
JSON Output --json flag for machine-readable output / pipeline integration
Verbose Mode --verbose flag for detailed breakdowns
Auto-Training Models train automatically on first use โ€” no manual step
Explainability Specific reasons for each risk assessment, not generic labels

๐Ÿ“ฆ Installation

From source (recommended)

git clone https://github.com/safetrace/safetrace.git
cd safetrace
pip install -e .

From PyPI (once published)

pip install safetrace

๐Ÿš€ Quick Start

Models auto-train on first use โ€” just start scanning:

Scan a URL

safetrace url http://fake-login.xyz/verify-account
  [HIGH RISK โš ๏ธ]
  URL:        http://fake-login.xyz/verify-account
  Confidence: 0.94
  Reasons:
    โ€ข Contains suspicious keyword 'login'
    โ€ข Multiple suspicious keywords: 'login', 'verify', 'account'
    โ€ข Uses TLD '.xyz' โ€” commonly associated with phishing campaigns
    โ€ข Does not use HTTPS encryption

Analyse text / email

safetrace email "URGENT: Your account has been compromised. Verify your identity immediately."
  [HIGH RISK โš ๏ธ]
  Phishing probability: 0.97
  Detected patterns:
    โ€ข Urgency: 'immediately', 'urgent'
    โ€ข Threats: 'your account has been compromised'
    โ€ข Credential Request: 'verify your identity'

Scan a safe URL

safetrace url https://www.github.com/explore
  [LOW RISK โœ…]
  URL:        https://www.github.com/explore
  Confidence: 0.03
  Reasons:
    โ€ข No specific risk indicators found

๐Ÿ“„ Batch Processing

Scan multiple URLs or text entries from a file:

# URLs โ€” one per line
safetrace url-file urls.txt

# Emails / text โ€” one per line
safetrace email-file emails.txt

# JSON output for scripting
safetrace url-file urls.txt --json

โš™๏ธ CLI Flags

Flag Effect
--json Output results as machine-readable JSON
--verbose Show detailed explanation and thresholds
--version / -v Print SafeTrace version

JSON output example

safetrace url http://fake-login.xyz --json
{
  "url": "http://fake-login.xyz",
  "risk": "HIGH",
  "confidence": 0.94,
  "reasons": [
    "Contains suspicious keyword 'login'",
    "Uses TLD '.xyz' โ€” commonly associated with phishing campaigns",
    "Does not use HTTPS encryption"
  ]
}

๐Ÿงฐ Python API

from safetrace.core import URLScanner, EmailScanner

# URL scanning
url_scanner = URLScanner()
result = url_scanner.scan("http://paypal-secure-login.tk/confirm")
print(result)
# {
#     "url": "http://paypal-secure-login.tk/confirm",
#     "risk": "HIGH",
#     "confidence": 0.93,
#     "reasons": ["Contains suspicious keyword 'login'", ...]
# }

# Email scanning
email_scanner = EmailScanner()
result = email_scanner.scan("Congratulations! You have won a million dollars!")
print(result)
# {
#     "risk": "HIGH",
#     "phishing_probability": 0.88,
#     "flags": ["Too Good To Be True: 'congratulations', 'you have won', 'million dollars'"]
# }

๐Ÿ“ Project Structure

SafeTrace/
โ”œโ”€โ”€ safetrace/
โ”‚   โ”œโ”€โ”€ __init__.py              # Package metadata
โ”‚   โ”œโ”€โ”€ __main__.py              # python -m safetrace support
โ”‚   โ”œโ”€โ”€ cli.py                   # CLI (argparse + --json + --verbose)
โ”‚   โ”œโ”€โ”€ config.py                # Thresholds, paths, patterns, logging
โ”‚   โ”œโ”€โ”€ train.py                 # Model training script
โ”‚   โ”œโ”€โ”€ core/
โ”‚   โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”‚   โ”œโ”€โ”€ url_scanner.py       # URL risk classifier (auto-trains)
โ”‚   โ”‚   โ”œโ”€โ”€ email_scanner.py     # Email phishing detector (auto-trains)
โ”‚   โ”‚   โ”œโ”€โ”€ feature_extractor.py # 15-feature URL vector + explainability
โ”‚   โ”‚   โ””โ”€โ”€ utils.py             # Risk labels, formatting, model checks
โ”‚   โ””โ”€โ”€ models/                  # .joblib artifacts (auto-generated)
โ”œโ”€โ”€ .github/
โ”‚   โ”œโ”€โ”€ ISSUE_TEMPLATE.md
โ”‚   โ””โ”€โ”€ PULL_REQUEST_TEMPLATE.md
โ”œโ”€โ”€ pyproject.toml
โ”œโ”€โ”€ requirements.txt
โ”œโ”€โ”€ CONTRIBUTING.md
โ”œโ”€โ”€ LICENSE (MIT)
โ”œโ”€โ”€ .gitignore
โ””โ”€โ”€ README.md

๐Ÿง  How It Works

URL Scanner

  1. Feature Extraction โ€” Parses the URL and extracts 15 numerical features:

    • Structural: length, dots, hyphens, slashes, digit count
    • Security: HTTPS presence, IP address detection, suspicious TLD
    • Semantic: count of phishing-related tokens (login, verify, account, etc.)
    • Complexity: subdomain depth, path length, query string length
  2. Classification โ€” A RandomForestClassifier (100 trees, balanced classes) predicts phishing probability.

  3. Explainability โ€” Each risk reason references the specific indicator found (e.g., "Contains suspicious keyword 'login'" instead of "Suspicious URL").

Email / Text Scanner

  1. TF-IDF Vectorization โ€” Converts text into sparse unigram+bigram features (500 max).

  2. Classification โ€” LogisticRegression predicts phishing probability.

  3. Pattern Matching โ€” Rule-based detection flags 5 phishing categories:

    • Urgency, Threats, Credential Requests, Too-Good-To-Be-True, Impersonation
  4. Hybrid Correction โ€” If 3+ pattern categories match but the ML score is low, the probability is boosted for safety.


โš™๏ธ Configuration

All thresholds and patterns live in safetrace/config.py:

Setting Default Description
HIGH_RISK_THRESHOLD 0.75 Probability โ‰ฅ this โ†’ HIGH risk
MEDIUM_RISK_THRESHOLD 0.45 Probability โ‰ฅ this โ†’ MEDIUM risk
SUSPICIOUS_TOKENS 18 items Keywords common in phishing URLs
SUSPICIOUS_TLDS 14 items TLDs frequently abused by attackers
PHISHING_PATTERNS 5 categories Rule-based text patterns

๐Ÿ› ๏ธ Manual Training

Models auto-train on first use, but you can retrain anytime:

safetrace train

This rebuilds models using the built-in synthetic dataset and saves them to safetrace/models/.


๐Ÿ“‹ Requirements

  • Python โ‰ฅ 3.9
  • scikit-learn โ‰ฅ 1.3.0
  • joblib โ‰ฅ 1.3.0
  • numpy โ‰ฅ 1.24.0

๐Ÿ“„ License

MIT โ€” see LICENSE for details.


๐Ÿค Contributing

Contributions welcome! See CONTRIBUTING.md for guidelines.

Ideas for future development:

  • Real-world training datasets (PhishTank, OpenPhish)
  • Domain age / WHOIS lookups
  • Email header analysis
  • REST API server mode
  • Browser extension integration
  • Confidence calibration with Platt scaling

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

safetrace-0.2.0.tar.gz (40.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

safetrace-0.2.0-py3-none-any.whl (41.0 kB view details)

Uploaded Python 3

File details

Details for the file safetrace-0.2.0.tar.gz.

File metadata

  • Download URL: safetrace-0.2.0.tar.gz
  • Upload date:
  • Size: 40.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.1

File hashes

Hashes for safetrace-0.2.0.tar.gz
Algorithm Hash digest
SHA256 24bf931a4f0a62a95b925901297d2936ee03aeab861a7fe3a61e11de09c0a743
MD5 8f80b98ee2a364d90e56dc9753777344
BLAKE2b-256 cfd0768bdb2745d9995c5472d21c3f2c1964cebd59efebd9c41752febd4e0927

See more details on using hashes here.

File details

Details for the file safetrace-0.2.0-py3-none-any.whl.

File metadata

  • Download URL: safetrace-0.2.0-py3-none-any.whl
  • Upload date:
  • Size: 41.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.1

File hashes

Hashes for safetrace-0.2.0-py3-none-any.whl
Algorithm Hash digest
SHA256 8cce974684aee2f5a3b339e47a3f78c5b9a5ddc83761448cc3b7a305621bffad
MD5 1610ffea165e195618d9fd4c32a8f09e
BLAKE2b-256 c35ad54a24a32b3d4d1537a489579a8ca36479cfb521f0fb030a6e7aeb0c35f0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page