/** Analyze a login attempt for anomalous behavior. */
export async function detectLoginAnomaly(attempt, recentAttempts) {
    const reasons = [];
    let riskScore = 0;
    const userAttempts = recentAttempts.filter((a) => a.userId === attempt.userId);
    if (userAttempts.length > 0) {
        const knownIPs = new Set(userAttempts.filter((a) => a.success).map((a) => a.ipAddress));
        if (knownIPs.size > 0 && !knownIPs.has(attempt.ipAddress)) {
            riskScore += 20;
            reasons.push('Login from previously unseen IP address');
        }
        const knownAgents = new Set(userAttempts.filter((a) => a.success).map((a) => a.userAgent));
        if (knownAgents.size > 0 && !knownAgents.has(attempt.userAgent)) {
            riskScore += 15;
            reasons.push('Login from previously unseen user agent');
        }
        const fiveMinAgo = Date.now() - 5 * 60 * 1000;
        const recentDistinctIPs = new Set(userAttempts
            .filter((a) => !a.success && a.timestamp.getTime() > fiveMinAgo)
            .map((a) => a.ipAddress));
        if (recentDistinctIPs.size >= 3) {
            riskScore += 30;
            reasons.push(`Failed logins from ${recentDistinctIPs.size} distinct IPs in 5 minutes`);
        }
    }
    const hour = attempt.timestamp.getHours();
    if (hour >= 1 && hour <= 5) {
        riskScore += 10;
        reasons.push('Login attempt during unusual hours (1 AM–5 AM)');
    }
    return { suspicious: riskScore > 50, reasons, riskScore };
}
/** Check if there are too many failed login attempts for an account. */
export function checkBruteForce(recentAttempts, maxFailures = 5, windowMs = 15 * 60 * 1000) {
    const cutoff = Date.now() - windowMs;
    const recentFailures = recentAttempts.filter((a) => !a.success && a.timestamp.getTime() > cutoff);
    return recentFailures.length >= maxFailures;
}
//# sourceMappingURL=anomaly-detection.js.map