Skip to content

feat: implement account activity anomaly detection#130

Open
vicky4196 wants to merge 3 commits into
Pidoko257:mainfrom
vicky4196:feature/account-activity-anomaly-detection
Open

feat: implement account activity anomaly detection#130
vicky4196 wants to merge 3 commits into
Pidoko257:mainfrom
vicky4196:feature/account-activity-anomaly-detection

Conversation

@vicky4196

Copy link
Copy Markdown

Account Activity Anomaly Detection Implementation

Overview

This implementation adds security anomaly detection to ProxyPay, enabling the system to detect and respond to unusual account activity including logins from new countries, API key usage from previously unseen IPs, and bulk operations at unusual hours.

Implementation Details

Database Schema

security_events table

Stores all security events for audit purposes:

  • id - UUID primary key
  • user_id - References users table
  • api_key_id - References api_keys table
  • event_type - Type of anomaly (new_country_login, new_ip_api_key_usage, etc.)
  • severity - low, medium, high, critical
  • ip_address - INET type for IP storage
  • country_code - Two-letter country code
  • user_agent - Browser/user agent string
  • metadata - JSONB for additional context
  • acknowledged - Boolean for user confirmation
  • created_at - Timestamp of event

account_activity_baseline table

Stores historical activity patterns per account:

  • user_id - UUID primary key referencing users
  • countries - Array of countries from last 30 days
  • ip_addresses - Array of IP addresses from last 30 days
  • typical_hours - JSONB of hourly activity distribution
  • last_updated - Last baseline update timestamp

SecurityAnomalyService

Located at src/services/securityAnomalyService.ts, provides:

  1. getSecurityEvents(userId) - Retrieve security events for a user
  2. getAllSecurityEvents() - Retrieve all security events (admin)
  3. createSecurityEvent(event) - Create a new security event
  4. acknowledgeEvent(eventId) - Mark event as acknowledged
  5. getAccountBaseline(userId) - Get stored baseline for user
  6. updateAccountBaseline(baseline) - Update baseline in database
  7. buildBaselineFromHistory(userId) - Build baseline from 30 days of activity
  8. detectLoginAnomaly(userId, ipAddress, userAgent) - Detect new IP logins
  9. detectCountryAnomaly(userId, ipAddress, countryCode, userAgent) - Detect new country logins
  10. validateApprovalToken(token) - Validate security approval tokens
  11. approveAnomaly(token) - Approve a security event
  12. getCountryFromIp(ipAddress) - Lookup country from IP using GeoIP API

Anomaly Detection Job

Located at src/jobs/anomalyDetectionJob.ts:

  • Runs every 15 minutes (configurable via ANOMALY_DETECTION_CRON)
  • Detects bulk operations during unusual hours (2-5 AM)
  • Updates account baselines daily to ensure fresh data

Auth Integration

Modified src/middleware/auth.ts:

  • Integrated anomaly detection into authenticateToken middleware
  • New country logins trigger immediate email with approve/revoke links
  • Suspicious countries (KP, IR, SY, CU) block login until approved
  • New IP logins send non-blocking notifications

API Endpoints

Located at src/routes/security.ts:

  • GET /security/approve?token=xxx - Approve a security event
  • GET /security/revoke?token=xxx - Revoke a security event
  • GET /security - Get user's security events (requires auth)

Email Notifications

Uses existing EmailService to send:

  • Security alert emails with approve/revoke links for critical anomalies
  • Non-blocking notifications for medium-severity events

Suspicious Countries

Blocked by default until user approval:

  • North Korea (KP)
  • Iran (IR)
  • Syria (SY)
  • Cuba (CU)

Acceptance Criteria

  • Baseline model built from last 30 days of account activity per account
  • New country logins trigger immediate security email with approve/revoke link
  • New IP API key usage sends notification but does not block the request
  • Anomaly events stored in security_events table for audit purposes
  • Background analysis job compares current activity against historical baseline
  • Bulk operations at unusual hours (2-5 AM) are flagged

Migration

Run the migration file migrations/20260630_create_security_events.sql to create the security_events and account_activity_baseline tables.

Configuration

Environment variables:

  • GEOIP_API_KEY - API key for ipgeolocation.io (optional, enables country detection)
  • SENDGRID_SECURITY_ALERT_TEMPLATE_ID - SendGrid template ID for security emails
  • APP_URL - Base URL for approval/revoke links
  • ANOMALY_DETECTION_CRON - Cron schedule (default: every 15 minutes)

Closes #117

- Implement GET /sep38/prices endpoint returning supported asset pairs and indicative exchange rates
- Implement GET /sep38/price endpoint for indicative rate queries with sell_amount/buy_amount
- Implement POST /sep38/quote endpoint returning firm quote with signed JWT token
- Quotes stored in Redis with 60-second expiry
- Quote tokens validated at payment initiation in SEP-31 transactions
- Add QUOTE_EXPIRED error code for expired/invalid quote handling
- Add comprehensive test suite for SEP-38 endpoints
Enable strict: true in tsconfig.json and resolve all resulting TypeScript errors.

Key changes:
- Enable all strict mode compiler options
- Fix nullable type checks across multiple service files
- Fix type safety in oauth.ts and 2fa.ts for possibly null values
- Add ambient declarations for untyped modules in module-ambient.d.ts
- Fix export type issue in sep38.ts for isolated modules compatibility

All TypeScript compilation passes with zero errors, no ts-ignore suppressions added, and runtime behavior unchanged.

Closes Pidoko257#116
Add security anomaly detection for unusual account activity:
- New country logins trigger immediate security email with approve/revoke links
- New IP API key usage sends notification without blocking
- Bulk operations during unusual hours (2-5 AM) are flagged
- All anomaly events stored in security_events table for audit
- Background job builds baseline from 30 days of activity per account

Changes:
- Add security_events and account_activity_baseline database tables
- Add SecurityAnomalyService for detection logic
- Integrate anomaly detection into authenticateToken middleware
- Add /security routes for approval/revoke endpoints
- Schedule anomaly detection job in scheduler

Closes Pidoko257#117
@drips-wave

drips-wave Bot commented Jun 30, 2026

Copy link
Copy Markdown

@vicky4196 Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits.

You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀

Learn more about application limits

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement Account Activity Anomaly Detection

1 participant