/** * Referral Sybil / fraud signal detection for commission payouts. */ import { query } from '../db/connection'; export type SybilSignal = | 'same_registration_ip' | 'shared_login_ip' | 'referrer_daily_limit_exceeded' | 'referrer_inactive_referrals_batch' | 'referral_chain_loop'; export const SYBIL_SIGNAL_POINTS: Record = { same_registration_ip: 3, shared_login_ip: 2, referrer_daily_limit_exceeded: 2, referrer_inactive_referrals_batch: 1, referral_chain_loop: 5, }; export function computeSybilScore(signals: SybilSignal[]): number { return signals.reduce((sum, signal) => sum + (SYBIL_SIGNAL_POINTS[signal] ?? 0), 0); } export function resolveCommissionStatusFromSybilScore( score: number, thresholds: { review: number; block: number } ): 'pending' | 'review' | 'blocked' { if (score >= thresholds.block) return 'blocked'; if (score >= thresholds.review) return 'review'; return 'pending'; } async function getRegistrationIp(userId: string): Promise { const rows = await query>( 'SELECT registration_ip FROM users WHERE id = $1', [userId] ); const fromUser = rows[0]?.registration_ip?.trim(); if (fromUser) return fromUser; const auditRows = await query>( `SELECT ip_address FROM audit_logs WHERE user_id = $1 AND action = 'register' AND ip_address IS NOT NULL ORDER BY created_at ASC LIMIT 1`, [userId] ); return auditRows[0]?.ip_address?.trim() ?? null; } async function usersShareLoginIp(userA: string, userB: string): Promise { const rows = await query<{ n: string }[]>( `SELECT 1 AS n FROM audit_logs a INNER JOIN audit_logs b ON a.ip_address = b.ip_address AND a.ip_address IS NOT NULL AND a.action = 'login' AND b.action = 'login' WHERE a.user_id = $1 AND b.user_id = $2 LIMIT 1`, [userA, userB] ); return Boolean(rows[0]); } async function referrerHasReferralChainLoop(referrerId: string): Promise { const seen = new Set(); let current: string | null = referrerId; for (let depth = 0; depth < 25 && current; depth++) { if (seen.has(current)) return true; seen.add(current); type RefRow = { referred_by_user_id: string | null }; const rows: RefRow[] = await query( 'SELECT referred_by_user_id FROM users WHERE id = $1', [current] ); current = rows[0]?.referred_by_user_id ?? null; } return false; } export async function countReferralsInLast24h(referrerId: string): Promise { const rows = await query<{ count: string }[]>( `SELECT COUNT(*)::text AS count FROM users WHERE referred_by_user_id = $1 AND created_at >= NOW() - INTERVAL '24 hours'`, [referrerId] ); return Number(rows[0]?.count ?? 0); } export async function countInactiveDirectReferrals(referrerId: string): Promise { const rows = await query<{ count: string }[]>( `SELECT COUNT(*)::text AS count FROM users u WHERE u.referred_by_user_id = $1 AND u.first_deposit_at IS NOT NULL AND NOT EXISTS ( SELECT 1 FROM candle_predict_bets b WHERE b.user_id = u.id AND b.stake_account_kind IN ('main', 'bonus') )`, [referrerId] ); return Number(rows[0]?.count ?? 0); } /** Validates referrer chain has no loop before accepting a new referral link. */ export async function assertReferralChainHasNoLoop(referrerId: string): Promise { if (await referrerHasReferralChainLoop(referrerId)) { throw new Error('Referral chain is invalid'); } } export async function detectReferralSybilSignals(input: { beneficiaryUserId: string; referredUserId: string; maxReferralsPerDay: number; inactiveReferralsThreshold?: number; }): Promise<{ score: number; signals: SybilSignal[] }> { const signals: SybilSignal[] = []; const inactiveThreshold = input.inactiveReferralsThreshold ?? 5; const [referredIp, beneficiaryIp, sharedLogin, referrals24h, inactiveReferrals, chainLoop] = await Promise.all([ getRegistrationIp(input.referredUserId), getRegistrationIp(input.beneficiaryUserId), usersShareLoginIp(input.referredUserId, input.beneficiaryUserId), countReferralsInLast24h(input.beneficiaryUserId), countInactiveDirectReferrals(input.beneficiaryUserId), referrerHasReferralChainLoop(input.beneficiaryUserId), ]); if (referredIp && beneficiaryIp && referredIp === beneficiaryIp) { signals.push('same_registration_ip'); } if (sharedLogin) { signals.push('shared_login_ip'); } if (referrals24h > input.maxReferralsPerDay) { signals.push('referrer_daily_limit_exceeded'); } if (inactiveReferrals >= inactiveThreshold) { signals.push('referrer_inactive_referrals_batch'); } if (chainLoop) { signals.push('referral_chain_loop'); } return { score: computeSybilScore(signals), signals }; }