feat: implement account activity anomaly detection#130
Open
vicky4196 wants to merge 3 commits into
Open
Conversation
- 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
|
@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! 🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 keyuser_id- References users tableapi_key_id- References api_keys tableevent_type- Type of anomaly (new_country_login, new_ip_api_key_usage, etc.)severity- low, medium, high, criticalip_address- INET type for IP storagecountry_code- Two-letter country codeuser_agent- Browser/user agent stringmetadata- JSONB for additional contextacknowledged- Boolean for user confirmationcreated_at- Timestamp of eventaccount_activity_baseline table
Stores historical activity patterns per account:
user_id- UUID primary key referencing userscountries- Array of countries from last 30 daysip_addresses- Array of IP addresses from last 30 daystypical_hours- JSONB of hourly activity distributionlast_updated- Last baseline update timestampSecurityAnomalyService
Located at
src/services/securityAnomalyService.ts, provides:getSecurityEvents(userId)- Retrieve security events for a usergetAllSecurityEvents()- Retrieve all security events (admin)createSecurityEvent(event)- Create a new security eventacknowledgeEvent(eventId)- Mark event as acknowledgedgetAccountBaseline(userId)- Get stored baseline for userupdateAccountBaseline(baseline)- Update baseline in databasebuildBaselineFromHistory(userId)- Build baseline from 30 days of activitydetectLoginAnomaly(userId, ipAddress, userAgent)- Detect new IP loginsdetectCountryAnomaly(userId, ipAddress, countryCode, userAgent)- Detect new country loginsvalidateApprovalToken(token)- Validate security approval tokensapproveAnomaly(token)- Approve a security eventgetCountryFromIp(ipAddress)- Lookup country from IP using GeoIP APIAnomaly Detection Job
Located at
src/jobs/anomalyDetectionJob.ts:ANOMALY_DETECTION_CRON)Auth Integration
Modified
src/middleware/auth.ts:authenticateTokenmiddlewareAPI Endpoints
Located at
src/routes/security.ts:GET /security/approve?token=xxx- Approve a security eventGET /security/revoke?token=xxx- Revoke a security eventGET /security- Get user's security events (requires auth)Email Notifications
Uses existing
EmailServiceto send:Suspicious Countries
Blocked by default until user approval:
Acceptance Criteria
Migration
Run the migration file
migrations/20260630_create_security_events.sqlto 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 emailsAPP_URL- Base URL for approval/revoke linksANOMALY_DETECTION_CRON- Cron schedule (default: every 15 minutes)Closes #117