Sistema de AnΓ‘lise de ReputaΓ§Γ£o de Acesso para DeterminaΓ§Γ£o de Risco de Fraude
IDROCK is a comprehensive IP reputation security tool designed to provide real-time fraud risk assessment for e-commerce platforms. The system consists of two independent services integrated via SDKs:
- IDROCK Security Service (FastAPI) - Core risk assessment engine
- NexShop E-commerce Service (Node.js/Express) - Demo e-commerce platform
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β IDROCK SECURITY TOOL β
β (Independent Service) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
ββββββββββββββββββββ βββββββββββββββββββ
β FastAPI βββββΊβ ProxyCheck.io β
β Backend API β β External API β
β + Swagger Docs β β β
ββββββββββββββββββββ βββββββββββββββββββ
β²
β SDK HTTP API Calls
βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β NEXSHOP E-COMMERCE β
β (Independent Service) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
βββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββββ
β React βββββΊβ Node.js βββββΊβ SQLite β
β Frontend β β Express.js β β Database β
β + JS SDK β β Backend β β (E-commerce) β
β β β + Node.js SDK β β β
βββββββββββββββββββ ββββββββββββββββββββ ββββββββββββββββββββ
- Real-time IP reputation analysis using ProxyCheck.io
- Device Trust Management System with unique constraints to prevent cloning
- Impossible Travel Detection with geodesic calculations and speed thresholds
- Hardware Validation System detecting real computers vs automation tools
- Browser Automation Detection with comprehensive pattern matching
- Risk scoring (0-100) with adaptive thresholds and weighted factors
- Risk levels: ALLOW (70-100), REVIEW (30-69), DENY (0-29)
- Dual SDK integration for seamless service communication
- Comprehensive logging and audit trails with device access history
- Docker containerization for easy deployment
- Interactive API documentation (Swagger/OpenAPI)
- Frontend JavaScript SDK collects comprehensive device fingerprinting data (Canvas, WebGL, Audio)
- Device registration and trust management with unique constraint validation
- Hardware validation (CPU cores, RAM) and browser automation detection
- Data flows to NexShop backend via secure endpoints
- NexShop Node.js SDK communicates with IDROCK API
- IDROCK analyzes multiple risk factors:
- IP reputation via ProxyCheck.io
- Impossible travel detection using geodesic calculations
- Device trust status and access history
- Hardware authenticity validation
- Browser automation pattern matching
- Weighted risk score calculated with multi-factor analysis
- Recommendations generated with detailed risk breakdown
- Response flows back through the SDK chain with comprehensive analysis
- FastAPI (Python 3.9+) - Main API framework
- SQLAlchemy + SQLite - Database and ORM with advanced device models
- Alembic - Database migrations and schema management
- Pydantic - Data validation and API schemas
- httpx - Async HTTP client for external APIs
- geopy - Geodesic distance calculations for travel detection
- ProxyCheck.io - IP reputation analysis
- Node.js (v18+) + Express.js - Backend framework
- Sequelize + SQLite - Database ORM
- JWT - Authentication and authorization
- bcryptjs - Password hashing
- axios - HTTP client for IDROCK API
- JavaScript SDK - Advanced frontend data collection with Canvas, WebGL, Audio fingerprinting
- Node.js SDK - Backend API communication with retry logic and device management
- Docker & Docker Compose
- Node.js 18+ (for local development)
- Python 3.9+ (for local development)
# Clone the repository
git clone https://github.com/joaoariedi/idrock-security.git
cd idrock-new
# Ensure you're on the feature branch with advanced security features
git checkout feature/advanced_security_features_sprint4# Copy environment configuration template
cp .env.example .env
# Edit .env file with your specific configuration
nano .env # or use your preferred editorEdit your .env file with these essential configurations:
# IDROCK Security Service Configuration
IDROCK_API_KEY=demo-api-key-12345 # Change in production
PROXYCHECK_API_KEY=your_proxycheck_key_here # Optional, uses mock if not set
# Database Configuration
DATABASE_URL=sqlite:///./idrock_security.db
NEXSHOP_DATABASE_URL=sqlite:///./nexshop_ecommerce.db
# Security Settings
SECRET_KEY=your-super-secret-key-change-in-production
JWT_SECRET=your-jwt-secret-key-for-nexshop
BCRYPT_ROUNDS=12
# API Configuration
IDROCK_API_URL=http://localhost:8000
NEXSHOP_API_URL=http://localhost:3000
# Advanced Security Features
ENABLE_DEVICE_TRUST=true
ENABLE_TRAVEL_DETECTION=true
ENABLE_HARDWARE_VALIDATION=true
ENABLE_BROWSER_AUTOMATION_DETECTION=true
# Travel Detection Thresholds (km/h)
TRAVEL_REVIEW_THRESHOLD=1000
TRAVEL_DENY_THRESHOLD=2000
# Hardware Validation Requirements
MIN_CPU_CORES=2
MIN_RAM_GB=4
# CORS Configuration
CORS_ORIGINS=http://localhost:3000,http://localhost:8000
# Logging
LOG_LEVEL=INFO
DEBUG_MODE=false# Check that environment file is properly configured
cat .env | grep -E "IDROCK_API_KEY|DATABASE_URL|SECRET_KEY" | head -3
# Ensure all required variables are set
if [[ -z "$IDROCK_API_KEY" || -z "$SECRET_KEY" ]]; then
echo "β Missing required environment variables"
exit 1
else
echo "β
Environment configuration complete"
fi# Start all services with Docker Compose
docker-compose up -d
# View logs
docker-compose logs -f
# Services will be available at:
# - IDROCK Security API: http://localhost:8000
# - NexShop E-commerce API: http://localhost:3000cd idrock-security-service
# Install dependencies
pip install -r requirements.txt
# Run the service
python -m uvicorn app.main:app --reload --host 0.0.0.0 --port 8000cd nexshop-ecommerce-service
# Install dependencies
npm install
# Run the service
npm run dev- Interactive Docs: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
- Health Check: http://localhost:8000/health
- Health Check: http://localhost:3000/health
- Authentication: http://localhost:3000/api/auth
- Security Integration: http://localhost:3000/api/security
- Device Management: http://localhost:8000/api/v1/devices
- Travel Detection: Advanced impossible travel analysis
- Hardware Validation: Real device vs automation tool detection
- Browser Validation: Comprehensive automation pattern detection
All IDROCK Security Service endpoints require API key authentication using Bearer tokens. This ensures secure communication between client applications and the IDROCK service.
-
Environment Variable: Set
IDROCK_API_KEYin your.envfile:IDROCK_API_KEY=demo-api-key-12345
-
Docker Environment: The API key is automatically configured in
docker-compose.yml:environment: - IDROCK_API_KEY=${IDROCK_API_KEY:-demo-api-key-12345}
All API requests must include the API key in the Authorization header:
Authorization: Bearer demo-api-key-12345- HTTPBearer Authentication: FastAPI security scheme for token validation
- 403 Forbidden Response: Unauthorized requests are blocked with detailed error messages
- Automatic Token Validation: Invalid or missing tokens are rejected
- SDK Integration: NexShop SDK automatically handles authentication
curl -X POST "http://localhost:8000/api/v1/identity/verify" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer demo-api-key-12345" \
-d '{
"user_id": "user123",
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)",
"session_data": {
"timestamp": "2025-09-07T10:30:00Z"
},
"context": {
"action_type": "login"
}
}'curl -X POST "http://localhost:3000/api/auth/register" \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"email": "test@example.com",
"password": "SecurePass123",
"first_name": "Test",
"last_name": "User"
}'curl -X POST "http://localhost:3000/api/auth/login" \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"password": "SecurePass123",
"deviceFingerprint": "fp_abc123",
"sessionData": {
"browser": "Chrome",
"screen_resolution": "1920x1080"
}
}'<!-- Include the SDK -->
<script src="/static/js/idrock-sdk.js"></script>
<script>
// Initialize SDK
const idrockSDK = new IDRockSDK({
apiEndpoint: '/api/security',
debug: true
});
// Login assessment
async function handleLogin(username, password) {
try {
const assessment = await idrockSDK.assessLogin(username);
if (assessment.recommendations.proceed) {
// Continue with login
console.log('Login approved');
} else if (assessment.recommendations.require_additional_auth) {
// Show additional authentication
console.log('Additional verification required');
}
} catch (error) {
console.error('Risk assessment failed:', error);
// Graceful fallback
}
}
</script>const { IDRockNodeSDK } = require('./src/services/idrockClient');
// Initialize SDK
const idrockClient = new IDRockNodeSDK({
baseUrl: 'http://localhost:8000',
apiKey: process.env.IDROCK_API_KEY
});
// Risk assessment
async function assessRisk(userData) {
try {
const assessment = await idrockClient.verifyIdentity(userData);
switch (assessment.risk_level) {
case 'ALLOW':
return { proceed: true };
case 'REVIEW':
return { proceed: false, requiresReview: true };
case 'DENY':
return { proceed: false, blocked: true };
}
} catch (error) {
// Fallback response
return idrockClient.createFallbackResponse(userData.userId, 'service_error');
}
}# Get IDROCK service statistics (requires API key)
curl -H "Authorization: Bearer demo-api-key-12345" \
"http://localhost:8000/api/v1/identity/stats"
# Get assessment history (requires API key)
curl -H "Authorization: Bearer demo-api-key-12345" \
"http://localhost:8000/api/v1/identity/history"
# Get NexShop security integration stats
curl "http://localhost:3000/api/security/stats"
# Get authentication statistics
curl "http://localhost:3000/api/auth/stats"# Check IDROCK service health
curl "http://localhost:8000/health"
# Check NexShop service health
curl "http://localhost:3000/health"
# Check IDROCK integration from NexShop
curl "http://localhost:3000/api/security/health"- API Key Authentication with HTTPBearer token validation
- Device Trust Management with unique constraint prevention of cloning attacks
- Impossible Travel Detection using geodesic calculations (>1000 km/h = REVIEW, >2000 km/h = DENY)
- Hardware Validation System with minimum CPU/RAM requirements for real devices
- Browser Automation Detection with comprehensive pattern matching (Selenium, headless browsers)
- Advanced Device Fingerprinting with Canvas, WebGL, Audio signatures
- Multi-Factor Risk Assessment with weighted scoring algorithms
- IP Reputation Analysis via ProxyCheck.io integration
- Risk-based Authentication with adaptive thresholds
- Device Access History tracking for behavioral analysis
- Comprehensive Audit Logging for compliance with device events
- Graceful Fallback when external services are unavailable
- JWT Authentication with secure token management (NexShop)
- Rate Limiting and DDoS protection
- Input Validation and SQL injection protection
- 403 Forbidden Responses for unauthorized access attempts
- Database Constraints preventing security bypass attempts
- ALLOW (70-100): Low risk, proceed normally
- REVIEW (30-69): Medium risk, additional verification required
- DENY (0-29): High risk, block action
- IP Reputation: ProxyCheck.io analysis with connection type detection
- Travel Analysis: Impossible travel detection using geodesic distance calculations
- Device Trust: Unique device fingerprint validation and trust status
- Hardware Authenticity: CPU/RAM validation for real computer detection
- Browser Validation: Automation tool and headless browser detection
- Geographic Location: Country-based risk assessment
- Proxy/VPN Detection: Identification of anonymizing services
- Access Patterns: Device usage history and behavioral analysis
- CAPTCHA integration (CapJS) for additional verification
- Machine learning risk models with pattern recognition
- Real-time threat intelligence feeds integration
- Advanced behavioral analysis with session tracking
-
Services not starting
# Check Docker logs docker-compose logs # Restart services docker-compose restart
-
Database connection errors
# Ensure data directories exist mkdir -p idrock-security-service/data mkdir -p nexshop-ecommerce-service/data -
IDROCK API not responding
# Check service health curl http://localhost:8000/health # Check Docker container status docker ps
-
ProxyCheck.io API errors
- Verify API key in
.envfile - Check API quota limits
- System falls back to mock data if API unavailable
- Verify API key in
# Enable debug logging
export DEBUG=true
export NODE_ENV=development
# Run services with verbose output
docker-compose up# Run the comprehensive demo script (recommended first test)
python demo-script.py
# Expected: All 7 steps should pass with 100% success rate
# This validates the entire system including advanced security featurescd idrock-security-service
# Install test dependencies
pip install -r requirements.txt
# Ensure test database is clean
rm -f test_idrock.db
# Set test environment
export PYTHONPATH=.
export TESTING=true# Test device models and constraints (comprehensive validation)
PYTHONPATH=. python -m pytest app/tests/test_device_models.py -v
# Expected output should include:
# - Device creation and unique constraints
# - Impossible travel detection
# - Hardware validation
# - Browser automation detection
# - Database relationship integrity# Test all advanced security services
PYTHONPATH=. python -m pytest app/tests/ -v --tb=short
# Test specific advanced features
PYTHONPATH=. python -m pytest app/tests/test_device_models.py::TestDeviceModel::test_device_unique_constraint -v
PYTHONPATH=. python -m pytest app/tests/test_device_models.py::TestDeviceAccessModel::test_device_access_composite_primary_key -v# Test device management endpoints
curl -X POST "http://localhost:8000/api/v1/devices/register" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer demo-api-key-12345" \
-d '{
"user_id": "test_user",
"device_fingerprint": "test_fp_12345"
}'
# Test impossible travel detection
curl -X POST "http://localhost:8000/api/v1/identity/verify" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer demo-api-key-12345" \
-d '{
"user_id": "test_user",
"ip_address": "192.168.1.100",
"location_data": {"lat": 40.7128, "lng": -74.0060}
}'cd nexshop-ecommerce-service
# Install test dependencies
npm install
# Clean test database
rm -f test_nexshop.db
# Set test environment
export NODE_ENV=test
export IDROCK_API_KEY=demo-api-key-12345# Run all NexShop tests
npm test
# Run specific test suites
npm test -- --grep "authentication"
npm test -- --grep "security integration"
npm test -- --grep "device management"# Test IDROCK SDK integration
npm run test:integration
# Test authentication flow with security
curl -X POST "http://localhost:3000/api/auth/login" \
-H "Content-Type: application/json" \
-d '{
"username": "testuser",
"password": "TestPass123",
"deviceFingerprint": "test_device_fp"
}'# Test device registration
python -c "
import requests
response = requests.post('http://localhost:8000/api/v1/devices/register',
headers={'Authorization': 'Bearer demo-api-key-12345', 'Content-Type': 'application/json'},
json={'user_id': 'test_user', 'device_fingerprint': 'test_fp_advanced'})
print(f'Status: {response.status_code}, Response: {response.json()}')
"
# Test device listing
curl -H "Authorization: Bearer demo-api-key-12345" \
"http://localhost:8000/api/v1/devices/list/test_user"# Simulate NY to Tokyo travel (should be flagged)
python -c "
import requests
from datetime import datetime
import time
# First access from New York
ny_response = requests.post('http://localhost:8000/api/v1/devices/access',
headers={'Authorization': 'Bearer demo-api-key-12345', 'Content-Type': 'application/json'},
json={
'device_id': 1,
'ip_address': '192.168.1.100',
'location_data': {'lat': 40.7128, 'lng': -74.0060, 'country': 'US', 'city': 'New York'}
})
time.sleep(2) # 2 second delay
# Second access from Tokyo (impossible travel)
tokyo_response = requests.post('http://localhost:8000/api/v1/devices/access',
headers={'Authorization': 'Bearer demo-api-key-12345', 'Content-Type': 'application/json'},
json={
'device_id': 1,
'ip_address': '192.168.2.100',
'location_data': {'lat': 35.6762, 'lng': 139.6503, 'country': 'JP', 'city': 'Tokyo'}
})
print(f'Travel Detection Result: {tokyo_response.json()}')
"# Test insufficient hardware detection
curl -X POST "http://localhost:8000/api/v1/devices/register" \
-H "Authorization: Bearer demo-api-key-12345" \
-H "Content-Type: application/json" \
-d '{
"user_id": "test_user_hw",
"device_fingerprint": "weak_device_fp",
"hardware_info": {
"cpu_cores": 1,
"ram_gb": 2,
"screen_resolution": "800x600"
}
}'
# Expected: Should return validation issues for insufficient specs# Test Selenium detection
curl -X POST "http://localhost:8000/api/v1/devices/register" \
-H "Authorization: Bearer demo-api-key-12345" \
-H "Content-Type: application/json" \
-d '{
"user_id": "test_automation",
"device_fingerprint": "automation_fp",
"browser_info": {
"user_agent": "Mozilla/5.0 HeadlessChrome Selenium/3.141.59",
"detected_patterns": ["selenium", "automated", "headless"]
}
}'
# Expected: Should detect automation patterns and flag as suspicious# Install load testing tools
pip install locust
# Run performance tests on risk assessment endpoint
locust -f tests/performance/locustfile.py --host=http://localhost:8000 \
--users=50 --spawn-rate=5 --run-time=60s
# Monitor response times and throughput
# Target: <500ms average response time under load# Comprehensive system validation
echo "Running complete test validation..."
# 1. Service health checks
curl -s http://localhost:8000/health | jq '.status' | grep -q "healthy" && echo "β
IDROCK healthy" || echo "β IDROCK down"
curl -s http://localhost:3000/health | jq '.status' | grep -q "healthy" && echo "β
NexShop healthy" || echo "β NexShop down"
# 2. Database connectivity
python -c "
from idrock-security-service.app.core.database import engine
try:
engine.connect()
print('β
IDROCK database connected')
except:
print('β IDROCK database connection failed')
"
# 3. Advanced features validation
python demo-script.py --quick-test && echo "β
All advanced features working" || echo "β Some features failing"
echo "Test validation complete!"# Python linting
cd idrock-security-service
flake8 app/
# JavaScript linting
cd nexshop-ecommerce-service
npm run lintThis project is part of the IDROCK security tool implementation following the comprehensive project plan for IP reputation-based fraud detection.
- Follow secure development best practices
- Ensure all tests pass
- Update documentation
- Follow existing code patterns
- Test end-to-end integration flows
For technical support and questions:
- Check the API documentation at
/docsendpoints - Review the comprehensive project plan
- Examine log files for error details
- Use health check endpoints for service status
IDROCK Security Tool v1.0.0-Advanced Comprehensive Security Platform with Advanced Threat Detection