/**
 * Credential Stuffing Attack Detector
 *
 * Advanced detection system for identifying credential stuffing attacks
 * against authentication endpoints. Features include:
 * - Real-time pattern analysis across multiple signals
 * - Redis-backed distributed tracking with sliding windows
 * - Integration with brute-force protection and alerting systems
 * - Automatic response actions (CAPTCHA, blocking, incidents)
 *
 * Attack Types Detected:
 * - Credential stuffing: Many usernames from single IP with high failure rate
 * - Brute force: Single username, many password attempts
 * - Password spraying: Single password across many usernames
 * - Bot attacks: Consistent timing patterns, automated behavior
 *
 * @packageDocumentation
 * @module security/threat-intel/credential-stuffing
 */
import type { FastifyInstance, FastifyRequest, preHandlerHookHandler } from 'fastify';
import type { Redis } from 'ioredis';
import { type Incident, type CreateIncidentInput } from '../incident/types.js';
/**
 * Authentication attempt record
 */
export interface AuthAttempt {
    /** Hashed username for privacy */
    username: string;
    /** Source IP address */
    ipAddress: string;
    /** Whether authentication succeeded */
    success: boolean;
    /** When the attempt occurred */
    timestamp: Date;
    /** User agent string */
    userAgent: string;
    /** Device/browser fingerprint */
    fingerprint: string;
    /** Optional geographic info */
    geoLocation?: {
        country?: string;
        city?: string;
        latitude?: number;
        longitude?: number;
    };
    /** Optional request metadata */
    metadata?: Record<string, unknown>;
}
/**
 * Attack type classification
 */
export type AttackType = 'credential_stuffing' | 'brute_force' | 'password_spraying' | 'unknown';
/**
 * Recommended action based on attack analysis
 */
export type RecommendedAction = 'monitor' | 'captcha' | 'block_ip' | 'block_account';
/**
 * Attack indicators returned by analysis
 */
export interface AttackIndicators {
    /** Whether an attack is detected */
    isAttack: boolean;
    /** Confidence score 0-100 */
    confidence: number;
    /** Classified attack type */
    attackType: AttackType;
    /** List of triggered indicators */
    indicators: string[];
    /** Recommended response action */
    recommendedAction: RecommendedAction;
    /** Number of affected accounts */
    affectedAccounts: number;
    /** Source IPs involved */
    sourceIPs: string[];
    /** Attack start time if detected */
    attackStartTime?: Date;
    /** Analysis timestamp */
    analyzedAt: Date;
    /** Raw metrics for debugging */
    metrics?: AttackMetrics;
}
/**
 * Internal metrics for attack analysis
 */
interface AttackMetrics {
    totalAttempts: number;
    failedAttempts: number;
    failureRate: number;
    uniqueUsernames: number;
    uniqueIPs: number;
    usernamesPerIP: Map<string, number>;
    IPsPerUsername: Map<string, number>;
    timingVariance: number;
    avgTimeBetweenAttempts: number;
    sequentialUsernameScore: number;
    geoDistributionScore: number;
}
/**
 * Configuration for the credential stuffing detector
 */
export interface CredentialStuffingConfig {
    /** Sliding window duration in seconds */
    windowSeconds: number;
    /** Failure rate threshold to trigger detection (0-1) */
    failureRateThreshold: number;
    /** Minimum usernames from single IP to flag */
    minUsernamesPerIP: number;
    /** Minimum IPs trying same username to flag */
    minIPsPerUsername: number;
    /** Maximum timing variance for bot detection (ms) */
    maxTimingVarianceMs: number;
    /** Confidence threshold to classify as attack */
    attackConfidenceThreshold: number;
    /** Whether to auto-trigger CAPTCHA */
    autoCaptcha: boolean;
    /** CAPTCHA trigger threshold */
    captchaThreshold: number;
    /** Whether to auto-block IPs */
    autoBlockIP: boolean;
    /** IP block threshold */
    ipBlockThreshold: number;
    /** Whether to create security incidents */
    createIncidents: boolean;
    /** Whether to send alerts */
    sendAlerts: boolean;
    /** Integration with brute force protection */
    integrateBruteForce: boolean;
    /** Known breached credential check endpoint (optional) */
    breachedCredentialCheckUrl?: string;
}
/**
 * Attack state stored in Redis
 */
interface AttackState {
    isUnderAttack: boolean;
    attackType: AttackType;
    confidence: number;
    detectedAt: string;
    lastAnalyzedAt: string;
    sourceIPs: string[];
    affectedAccounts: number;
    incidentId?: string;
}
/**
 * Default configuration values
 */
export declare const DEFAULT_CREDENTIAL_STUFFING_CONFIG: CredentialStuffingConfig;
/**
 * Credential Stuffing Attack Detector
 *
 * Detects and responds to credential stuffing attacks in real-time
 * using multiple behavioral signals and pattern analysis.
 *
 * @example
 * ```typescript
 * const detector = new CredentialStuffingDetector({
 *   failureRateThreshold: 0.9,
 *   autoCaptcha: true,
 * });
 *
 * // Record an authentication attempt
 * await detector.recordAttempt({
 *   username: hashUsername('user@example.com'),
 *   ipAddress: '192.168.1.1',
 *   success: false,
 *   timestamp: new Date(),
 *   userAgent: 'Mozilla/5.0...',
 *   fingerprint: 'abc123',
 * });
 *
 * // Check if under attack
 * if (await detector.isUnderAttack()) {
 *   const indicators = await detector.analyze();
 *   console.log('Attack detected:', indicators.attackType);
 * }
 * ```
 */
export declare class CredentialStuffingDetector {
    private readonly config;
    private readonly redis;
    private bruteForceProtection?;
    private alertService?;
    private incidentManager?;
    /**
     * Creates a new CredentialStuffingDetector instance
     *
     * @param config - Configuration options
     * @param redis - Optional Redis instance (uses shared instance if not provided)
     */
    constructor(config?: Partial<CredentialStuffingConfig>, redis?: Redis);
    /**
     * Sets the incident manager for creating security incidents
     */
    setIncidentManager(manager: {
        createIncident: (input: CreateIncidentInput) => Promise<Incident>;
    }): void;
    /**
     * Records an authentication attempt for analysis
     *
     * @param attempt - The authentication attempt to record
     */
    recordAttempt(attempt: AuthAttempt): Promise<void>;
    /**
     * Analyzes recent authentication patterns for attack indicators
     *
     * @returns Attack indicators and recommended actions
     */
    analyze(): Promise<AttackIndicators>;
    /**
     * Quick check if system is currently under attack
     *
     * @returns Whether an attack is currently detected
     */
    isUnderAttack(): Promise<boolean>;
    /**
     * Gets list of blocked/compromised credential hashes
     *
     * @returns Array of blocked username hashes
     */
    getBlockedCredentials(): Promise<string[]>;
    /**
     * Blocks a credential (username hash)
     *
     * @param usernameHash - The hashed username to block
     * @param reason - Reason for blocking
     * @param durationSeconds - How long to block (default: 24 hours)
     */
    blockCredential(usernameHash: string, reason: string, durationSeconds?: number): Promise<void>;
    /**
     * Checks if a credential is blocked
     *
     * @param usernameHash - The hashed username to check
     * @returns Whether the credential is blocked
     */
    isCredentialBlocked(usernameHash: string): Promise<boolean>;
    /**
     * Unblocks a credential
     *
     * @param usernameHash - The hashed username to unblock
     */
    unblockCredential(usernameHash: string): Promise<void>;
    /**
     * Gets current attack state details
     */
    getAttackState(): Promise<AttackState | null>;
    /**
     * Gets the current configuration
     */
    getConfig(): CredentialStuffingConfig;
    /**
     * Hook to call from authentication endpoints
     *
     * @param attempt - The authentication attempt
     * @returns Response actions to take
     */
    onAuthAttempt(attempt: AuthAttempt): Promise<{
        requireCaptcha: boolean;
        blockRequest: boolean;
        isBlocked: boolean;
        attackDetected: boolean;
    }>;
    /**
     * Creates a Fastify preHandler middleware for protected routes
     *
     * @returns Fastify preHandler hook
     */
    getAuthMiddleware(): preHandlerHookHandler;
    /**
     * Collects metrics from Redis for analysis
     */
    private collectMetrics;
    /**
     * Calculates timing variance for bot detection
     */
    private calculateTimingVariance;
    /**
     * Calculates sequential username pattern score
     */
    private calculateSequentialScore;
    /**
     * Calculates geographic distribution anomaly score
     */
    private calculateGeoDistribution;
    /**
     * Updates global metrics
     */
    private updateMetrics;
    /**
     * Updates attack state in Redis
     */
    private updateAttackState;
    /**
     * Runs analysis and triggers responses
     */
    private analyzeAndRespond;
    /**
     * Hashes a username for privacy
     */
    private hashUsername;
    /**
     * Cleans up old data
     */
    cleanup(): Promise<void>;
}
/**
 * Options for the Fastify plugin
 */
export interface CredentialStuffingPluginOptions {
    /** Detector instance */
    detector?: CredentialStuffingDetector;
    /** Detector configuration */
    config?: Partial<CredentialStuffingConfig>;
    /** Paths to apply protection to */
    protectedPaths?: string[];
    /** Function to extract username from request */
    extractUsername?: (request: FastifyRequest) => string | undefined;
}
/**
 * Registers the credential stuffing protection plugin with Fastify
 */
export declare function registerCredentialStuffingPlugin(fastify: FastifyInstance, options?: CredentialStuffingPluginOptions): Promise<void>;
/**
 * Gets or creates the singleton CredentialStuffingDetector instance
 *
 * @param config - Optional configuration (only used on first call)
 * @returns The singleton CredentialStuffingDetector instance
 */
export declare function getCredentialStuffingDetector(config?: Partial<CredentialStuffingConfig>): CredentialStuffingDetector;
/**
 * Resets the singleton instance (primarily for testing)
 */
export declare function resetCredentialStuffingDetector(): void;
/**
 * Creates a new CredentialStuffingDetector instance
 */
export declare function createCredentialStuffingDetector(config?: Partial<CredentialStuffingConfig>, redis?: Redis): CredentialStuffingDetector;
/**
 * Hashes a username for use with the detector
 *
 * @param username - The username to hash
 * @returns SHA-256 hash of the normalized username
 */
export declare function hashUsername(username: string): string;
/**
 * Creates an AuthAttempt from a Fastify request
 *
 * @param request - The Fastify request
 * @param success - Whether the authentication was successful
 * @param username - The username (will be hashed)
 * @returns AuthAttempt object ready for recording
 */
export declare function createAuthAttemptFromRequest(request: FastifyRequest, success: boolean, username: string): AuthAttempt;
declare module 'fastify' {
    interface FastifyInstance {
        credentialStuffingDetector?: CredentialStuffingDetector;
    }
    interface FastifyRequest {
        credentialStuffingStatus?: {
            attackDetected: boolean;
            requireCaptcha: boolean;
            confidence: number;
        };
        requireCaptcha?: boolean;
        attackConfidence?: number;
    }
}
export {};
//# sourceMappingURL=credential-stuffing.d.ts.map