|
1 | 1 | import connection from '../utils/redis'; |
2 | 2 | import logger from '../utils/logger'; |
| 3 | +import { ApiError } from '../middleware/error.middleware'; |
| 4 | + |
| 5 | +const DAY_SECONDS = 24 * 60 * 60; |
| 6 | +const STROOPS_PER_UNIT = 10_000_000n; |
| 7 | + |
| 8 | +const parseAmountToMinorUnits = (amount: string | bigint): bigint => { |
| 9 | + if (typeof amount === 'bigint') return amount; |
| 10 | + if (typeof amount !== 'string') throw new ApiError(400, 'Invalid amount', 'VALIDATION_ERROR'); |
| 11 | + |
| 12 | + const normalized = amount.trim(); |
| 13 | + if (!/^\d+(\.\d+)?$/.test(normalized)) throw new ApiError(400, 'Invalid amount format', 'VALIDATION_ERROR'); |
| 14 | + |
| 15 | + const [whole, fractional = ''] = normalized.split('.'); |
| 16 | + if (fractional.length > 7) throw new ApiError(400, 'Amount has too many decimals', 'VALIDATION_ERROR'); |
| 17 | + |
| 18 | + const paddedFractional = (fractional + '0000000').slice(0, 7); |
| 19 | + return BigInt(whole) * STROOPS_PER_UNIT + BigInt(paddedFractional); |
| 20 | +}; |
3 | 21 |
|
4 | 22 | /** |
5 | 23 | * Skeletal Blueprint for Risk & Compliance. |
6 | 24 | * Implements velocity limits and sanctions screening interfaces. |
7 | 25 | */ |
8 | 26 | class ComplianceService { |
| 27 | + private readonly dailyLimit: bigint; |
| 28 | + private readonly sanctionsBlacklist: Set<string>; |
| 29 | + |
| 30 | + constructor() { |
| 31 | + const limitEnv = process.env.COMPLIANCE_DAILY_LIMIT_USD || '1000'; |
| 32 | + this.dailyLimit = parseAmountToMinorUnits(limitEnv); |
| 33 | + |
| 34 | + const blacklist = process.env.COMPLIANCE_SANCTIONS_BLACKLIST || ''; |
| 35 | + this.sanctionsBlacklist = new Set( |
| 36 | + blacklist |
| 37 | + .split(',') |
| 38 | + .map((entry) => entry.trim()) |
| 39 | + .filter((entry) => entry.length > 0) |
| 40 | + ); |
| 41 | + } |
| 42 | + |
9 | 43 | /** |
10 | 44 | * Checks if a user is on a sanctions blacklist (e.g., OFAC). |
11 | 45 | */ |
12 | 46 | async checkSanctions(userId: string): Promise<boolean> { |
13 | 47 | // Blueprint: Integrate with screening providers (Chainalysis, TRM, OFAC API). |
14 | | - return false; |
| 48 | + const normalized = userId.trim(); |
| 49 | + return this.sanctionsBlacklist.has(normalized); |
15 | 50 | } |
16 | 51 |
|
17 | 52 | /** |
18 | 53 | * Enforces rolling 24h volume limits using Redis. |
19 | 54 | */ |
20 | | - async checkVelocity(userId: string, amount: bigint): Promise<void> { |
21 | | - // Blueprint: INCR volume key in Redis with 24h TTL -> Throw error if > limit. |
22 | | - logger.info(`Skeletal Compliance: Checking velocity for user ${userId}`); |
| 55 | + async checkVelocity(userId: string, amount: string | bigint): Promise<void> { |
| 56 | + const amountUnits = parseAmountToMinorUnits(amount); |
| 57 | + if (amountUnits <= 0n) throw new ApiError(400, 'Amount must be positive', 'VALIDATION_ERROR'); |
| 58 | + |
| 59 | + const now = Date.now(); |
| 60 | + const cutoff = now - DAY_SECONDS * 1000; |
| 61 | + const key = `compliance:velocity:${userId}`; |
| 62 | + const member = `${now}:${amountUnits.toString()}`; |
| 63 | + |
| 64 | + try { |
| 65 | + const results = await connection |
| 66 | + .multi() |
| 67 | + .zremrangebyscore(key, 0, cutoff) |
| 68 | + .zadd(key, now, member) |
| 69 | + .zrangebyscore(key, cutoff, now) |
| 70 | + .expire(key, DAY_SECONDS + 3600) |
| 71 | + .exec(); |
| 72 | + |
| 73 | + const rangeResult = results?.[2]?.[1] as string[] | undefined; |
| 74 | + const entries = rangeResult ?? []; |
| 75 | + |
| 76 | + let total = 0n; |
| 77 | + for (const entry of entries) { |
| 78 | + const [, amountStr] = entry.split(':'); |
| 79 | + if (!amountStr) continue; |
| 80 | + total += BigInt(amountStr); |
| 81 | + } |
| 82 | + |
| 83 | + logger.info(`Compliance velocity check for user ${userId}: total=${total.toString()}`); |
| 84 | + |
| 85 | + if (total > this.dailyLimit) { |
| 86 | + throw new ApiError(403, 'Velocity limit exceeded', 'COMPLIANCE_VELOCITY'); |
| 87 | + } |
| 88 | + } catch (error) { |
| 89 | + if (error instanceof ApiError) throw error; |
| 90 | + logger.error('Compliance velocity check failed:', { error }); |
| 91 | + // Fail open to avoid blocking users on Redis failure |
| 92 | + return; |
| 93 | + } |
23 | 94 | } |
24 | 95 | } |
25 | 96 |
|
|
0 commit comments