Skip to content

akshaynstack/privy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

20 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Privy - Fraud Detection API

Privy is an open-source fraud detection and risk scoring API service inspired by SignupGate.
It provides real-time risk assessment for user signups, email validation, IP reputation checking, and abuse detection to help protect your applications from fraudulent users.

πŸš€ Features

  • πŸ›‘οΈ Real-time Risk Scoring β€” Instant fraud detection with configurable scoring
  • πŸ“§ Email Validation β€” Disposable email detection (10,000+ domains) and pattern analysis
  • 🌐 IP Intelligence β€” VPN, Tor, proxy detection with geolocation analysis
  • 🌍 Geolocation Analysis β€” High-risk country detection and ISP analysis
  • πŸ”‘ API Key Management β€” Secure authentication with per-organization API keys
  • ⚑ Rate Limiting β€” Token bucket rate limiting with Redis backend
  • πŸ“Š Analytics & Logging β€” Comprehensive check logging and analytics
  • 🚫 Custom Blacklists β€” Organization-specific IP, email, and domain blocking
  • πŸ”„ Background Processing β€” Async data ingestion with Celery workers
  • πŸ€– Automated Data Updates β€” Automatic updates of fraud detection databases
  • πŸ“‹ Detailed Reporting β€” Risk explanations and actionable recommendations

πŸ—οΈ Architecture

Built with:

  • ⚑ FastAPI β€” High-performance async Python API framework
  • 🐘 PostgreSQL β€” Primary database for persistent data
  • πŸ”΄ Redis β€” Caching, rate limiting, and fast lookups
  • πŸ“¦ SQLModel β€” Modern ORM with Pydantic integration
  • πŸ”„ Alembic β€” Database migration management
  • 🌿 Celery β€” Distributed task queue for background jobs
  • 🐳 Docker β€” Containerized deployment

πŸ“‚ Project Structure

backend/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ main.py              # FastAPI application entry point
β”‚   β”œβ”€β”€ config.py            # Configuration and environment variables
β”‚   β”œβ”€β”€ db.py                # Database connection and session management
β”‚   β”œβ”€β”€ models.py            # SQLModel database models
β”‚   β”œβ”€β”€ crud.py              # Database CRUD operations
β”‚   β”œβ”€β”€ api/
β”‚   β”‚   β”œβ”€β”€ deps.py          # API dependencies (auth, validation)
β”‚   β”‚   └── routes.py        # API route handlers
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ scoring.py       # Risk scoring algorithms
β”‚   β”‚   └── rate_limiter.py  # Rate limiting implementation
β”‚   └── workers/
β”‚       β”œβ”€β”€ celery_app.py    # Celery configuration
β”‚       └── tasks.py         # Background task definitions
β”œβ”€β”€ migrations/              # Alembic database migrations
β”œβ”€β”€ tests/                   # Test suite
β”œβ”€β”€ requirements.txt         # Python dependencies
β”œβ”€β”€ alembic.ini             # Alembic configuration
β”œβ”€β”€ docker-compose.yml      # Development environment
β”œβ”€β”€ Dockerfile              # Container definition
└── .env                    # Environment variables

πŸ› οΈ Setup & Installation

1. Clone the repository

git clone https://github.com/akshaynstack/privy.git
cd privy/backend

2. Environment Setup

Option A: Docker (Recommended)

# Copy environment template
cp .env.template .env

# Edit .env with your configuration
# Start all services
docker-compose up --build

Option B: Local Development

# Create virtual environment
python -m venv .venv
source .venv/bin/activate   # Linux/Mac
.venv\Scripts\activate      # Windows

# Install dependencies
pip install -r requirements.txt

# Setup environment variables
cp .env.template .env
# Edit .env with your database and Redis URLs

# Run database migrations
alembic upgrade head

# Start the API server
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000

# In separate terminals, start Redis and Celery worker:
redis-server
celery -A app.workers.celery_app.celery_app worker --loglevel=info

3. Verify Installation

# Test the API
curl -X POST "http://localhost:8000/v1/check" \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{"email": "test@example.com", "ip": "1.2.3.4"}'

πŸ“‘ API Reference

Base URL: http://localhost:8000

Core Endpoints

POST /v1/check

Perform real-time fraud detection check

Headers:

  • X-API-Key: {key_id}.{secret} (required)
  • Content-Type: application/json

Request Body:

{
  "email": "user@example.com",
  "ip": "192.168.1.1",
  "user_agent": "Mozilla/5.0...",
  "metadata": {
    "custom_field": "value"
  }
}

Response:

{
  "success": true,
  "data": {
    "risk_score": 25,
    "risk_level": "low",
    "reasons": ["disposable_email"]
  }
}

Risk Levels

  • none (0-29): Safe to proceed
  • low (30-59): Monitor closely
  • medium (60-79): Challenge user (CAPTCHA, 2FA)
  • high (80-100): Block or manual review

Rate Limits

  • Default: 60 requests per minute per API key
  • Burst: Up to 60 tokens in bucket
  • Refill: 1 token per second

Error Codes

  • 401 - Invalid or missing API key
  • 429 - Rate limit exceeded
  • 422 - Invalid request payload
  • 500 - Internal server error

πŸ—‚οΈ Data Models

User

  • Multi-tenant organization support
  • Email-based authentication
  • Automatic UUID generation

Organization

  • API key scoping
  • Custom blacklist management
  • Usage analytics

ApiKey

  • Secure key generation with public ID + secret
  • bcrypt hashed secrets
  • Revocation support

Check

  • Complete request logging
  • Risk score tracking
  • JSON metadata storage

Blacklist

  • IP addresses, email domains, ISPs, ASNs
  • Organization-specific rules
  • Reason tracking

πŸ“Š Fraud Detection Features

Email Analysis

  • βœ… Disposable email detection (10,000+ domains)
  • βœ… Domain reputation scoring
  • βœ… Custom domain blacklists
  • πŸ”„ Real-time email validation

IP Intelligence

  • βœ… VPN/Proxy detection
  • βœ… Tor exit node identification
  • βœ… Geolocation analysis
  • βœ… ISP reputation scoring
  • πŸ”„ Multiple signups from same IP detection

Behavioral Analysis

  • βœ… Rate limiting per API key
  • βœ… Request pattern analysis
  • πŸ”„ Device fingerprinting
  • πŸ”„ Time-based anomaly detection

Custom Rules

  • βœ… Organization blacklists
  • βœ… Configurable scoring weights
  • πŸ”„ Machine learning integration
  • πŸ”„ Custom webhook triggers

Legend: βœ… Implemented | πŸ”„ Planned


πŸ“ˆ Roadmap

Phase 1 (Current)

  • βœ… Core fraud detection API
  • βœ… Basic email and IP checks
  • βœ… Rate limiting and API keys
  • βœ… Docker deployment

Phase 2 (Next)

  • πŸ”„ Web dashboard for analytics
  • πŸ”„ Advanced ML-based scoring
  • πŸ”„ Webhook notifications
  • πŸ”„ Bulk data ingestion APIs

Phase 3 (Future)

  • πŸ”„ Device fingerprinting
  • πŸ”„ Behavioral analytics
  • πŸ”„ Enterprise SSO integration
  • πŸ”„ Custom rule engine UI

πŸ”§ Configuration

Environment Variables

# Database
DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/privy
DATABASE_URL_SYNC=postgresql://user:pass@localhost:5432/privy

# Redis
REDIS_URL=redis://localhost:6379

# Celery
CELERY_BROKER=redis://localhost:6379/0
CELERY_BACKEND=redis://localhost:6379/1

# API
API_HOST=0.0.0.0
API_PORT=8000
DEBUG=true

# Optional: External data sources
DISPOSABLE_EMAIL_URL=https://raw.githubusercontent.com/disposable/disposable-email-domains/master/domains.txt

Scoring Configuration

Customize risk scoring weights in app/services/scoring.py:

WEIGHTS = {
    "disposable_email": 70,
    "vpn_ip": 60,
    "tor_exit": 80,
    "bad_isp": 40,
    "multiple_from_ip": 30,
    "custom_blacklist": 100,
}

πŸ§ͺ Testing

# Run all tests
pytest

# Run with coverage
pytest --cov=app tests/

# Run specific test file
pytest tests/test_scoring.py -v

πŸš€ Production Deployment

Docker Production

# Build production image
docker build -t privy-api .

# Run with production settings
docker run -p 8000:8000 --env-file .env.prod privy-api

Manual Deployment

  1. Set up PostgreSQL and Redis
  2. Configure production environment variables
  3. Run database migrations: alembic upgrade head
  4. Start API server: gunicorn app.main:app -w 4 -k uvicorn.workers.UvicornWorker
  5. Start Celery worker: celery -A app.workers.celery_app.celery_app worker

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Please read our Code of Conduct and Security Policy.


πŸ“œ License

This project is licensed under the MIT License - see the LICENSE file for details.


🌟 Support

If you find this project useful, please consider:

  • ⭐ Starring the repository
  • πŸ› Reporting bugs and issues
  • πŸ’‘ Suggesting new features
  • 🀝 Contributing code improvements
  • πŸ“’ Sharing with others who might benefit

For support:


Built with ❀️ for developers who want to protect their applications from fraud.

About

Privy is an open-source fraud detection and risk scoring API service

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published