/**
 * IP Reputation Service - Threat Intelligence Integration
 *
 * Provides IP reputation checking with multi-layer caching for threat intelligence.
 * Features include:
 * - Multi-layer caching (L1 in-memory LRU, L2 Redis, L3 external API)
 * - Built-in threat feeds (Tor exit nodes, datacenter IPs, internal blocklist)
 * - Async refresh pattern for non-blocking requests
 * - AbuseIPDB-compatible interface
 * - Fastify middleware for IP reputation checks
 *
 * @packageDocumentation
 * @module security/threat-intel/ip-reputation
 */
import type { preHandlerHookHandler } from 'fastify';
import type { Redis } from 'ioredis';
/**
 * IP reputation categories
 */
export type IPCategory = 'tor' | 'vpn' | 'proxy' | 'botnet' | 'spam' | 'scanner' | 'bruteforce' | 'datacenter' | 'residential' | 'mobile' | 'hosting' | 'unknown';
/**
 * IP reputation data structure
 */
export interface IPReputation {
    /** Reputation score 0-100 (0 = malicious, 100 = clean) */
    score: number;
    /** Categories this IP is associated with */
    categories: IPCategory[];
    /** When this IP was last seen in threat feeds */
    lastSeen: Date;
    /** Number of reports against this IP */
    reportCount: number;
    /** Source of the reputation data */
    source: string;
    /** Confidence level 0-100 */
    confidence: number;
    /** Country code (ISO 3166-1 alpha-2) */
    countryCode?: string;
    /** ASN information */
    asn?: {
        number: number;
        name: string;
    };
    /** Whether this IP is on the blocklist */
    isBlocked: boolean;
    /** When the reputation was last updated */
    updatedAt: Date;
    /** Whether this data is from cache */
    fromCache: boolean;
    /** Cache layer that provided the data */
    cacheLayer?: 'l1' | 'l2' | 'l3';
}
/**
 * IP report reason
 */
export interface IPReport {
    /** IP address being reported */
    ip: string;
    /** Reason for the report */
    reason: string;
    /** Category of malicious activity */
    category?: IPCategory;
    /** When the report was submitted */
    reportedAt: Date;
    /** Who submitted the report (user/system ID) */
    reportedBy?: string;
    /** Additional context */
    context?: Record<string, unknown>;
}
/**
 * External API configuration (AbuseIPDB-compatible)
 */
export interface ExternalAPIConfig {
    /** API endpoint URL */
    endpoint: string;
    /** API key */
    apiKey: string;
    /** Maximum requests per minute */
    rateLimit: number;
    /** Request timeout in milliseconds */
    timeoutMs: number;
    /** Whether the API is enabled */
    enabled: boolean;
}
/**
 * IP reputation service configuration
 */
export interface IPReputationConfig {
    /** External API configuration */
    externalAPI?: ExternalAPIConfig;
    /** Default score for unknown IPs */
    defaultScore: number;
    /** Score threshold for blocking (IPs with score below this are blocked) */
    blockThreshold: number;
    /** Enable built-in Tor exit node detection */
    enableTorDetection: boolean;
    /** Enable built-in datacenter IP detection */
    enableDatacenterDetection: boolean;
    /** Enable internal blocklist */
    enableInternalBlocklist: boolean;
    /** Score penalty for Tor exit nodes */
    torPenalty: number;
    /** Score penalty for datacenter IPs */
    datacenterPenalty: number;
    /** Score penalty for VPNs */
    vpnPenalty: number;
    /** Score penalty for proxies */
    proxyPenalty: number;
    /** Enable async background refresh */
    enableAsyncRefresh: boolean;
    /** Callback for high-risk IP detection */
    onHighRiskIP?: (ip: string, reputation: IPReputation) => void;
}
/**
 * Default IP reputation configuration
 */
export declare const DEFAULT_IP_REPUTATION_CONFIG: IPReputationConfig;
/**
 * IP Reputation Service
 *
 * Provides IP reputation checking with multi-layer caching for threat intelligence.
 *
 * @example
 * ```typescript
 * const service = new IPReputationService({
 *   blockThreshold: 20,
 *   enableTorDetection: true,
 * });
 *
 * // Check IP reputation
 * const reputation = await service.checkIP('192.168.1.1');
 * console.log(`Score: ${reputation.score}, Categories: ${reputation.categories}`);
 *
 * // Report malicious IP
 * await service.reportMaliciousIP('10.0.0.1', 'Detected brute force attack');
 *
 * // Quick block check
 * const blocked = await service.isBlocked('10.0.0.1');
 * ```
 */
export declare class IPReputationService {
    private readonly config;
    private readonly redis;
    private readonly l1Cache;
    private cleanupInterval;
    private refreshInProgress;
    /**
     * Creates a new IPReputationService instance
     *
     * @param config - Service configuration
     * @param redis - Optional Redis instance (uses shared instance if not provided)
     */
    constructor(config?: Partial<IPReputationConfig>, redis?: Redis);
    /**
     * Start L1 cache cleanup interval
     */
    private startL1CacheCleanup;
    /**
     * Get reputation from L1 (in-memory) cache
     */
    private getFromL1Cache;
    /**
     * Store reputation in L1 cache
     */
    private storeInL1Cache;
    /**
     * Get reputation from L2 (Redis) cache
     */
    private getFromL2Cache;
    /**
     * Store reputation in L2 (Redis) cache
     */
    private storeInL2Cache;
    /**
     * Check if L2 cache entry is stale (should trigger background refresh)
     */
    private isL2CacheStale;
    /**
     * Get reputation from L3 (external API)
     */
    private getFromExternalAPI;
    /**
     * Compute reputation from built-in threat feeds
     */
    private computeBuiltInReputation;
    /**
     * Trigger background refresh for an IP
     */
    private triggerBackgroundRefresh;
    /**
     * Merge reputations from multiple sources
     */
    private mergeReputations;
    /**
     * Check IP reputation
     *
     * Returns reputation score and metadata for an IP address.
     * Uses multi-layer caching with async background refresh.
     *
     * @param ip - IP address to check
     * @returns IP reputation data
     */
    checkIP(ip: string): Promise<IPReputation>;
    /**
     * Report a malicious IP address
     *
     * @param ip - IP address to report
     * @param reason - Reason for the report
     * @param category - Optional category of malicious activity
     * @param reportedBy - Optional reporter identifier
     */
    reportMaliciousIP(ip: string, reason: string, category?: IPCategory, reportedBy?: string): Promise<void>;
    /**
     * Quick check if an IP is blocked
     *
     * @param ip - IP address to check
     * @returns Whether the IP is blocked
     */
    isBlocked(ip: string): Promise<boolean>;
    /**
     * Check if IP is on the internal blocklist
     */
    private isOnBlocklist;
    /**
     * Add IP to internal blocklist
     *
     * @param ip - IP address to block
     * @param reason - Reason for blocking
     */
    addToBlocklist(ip: string, reason: string): Promise<void>;
    /**
     * Remove IP from internal blocklist
     *
     * @param ip - IP address to unblock
     */
    removeFromBlocklist(ip: string): Promise<void>;
    /**
     * Get report count for an IP
     */
    private getReportCount;
    /**
     * Get recent reports for an IP
     *
     * @param ip - IP address to get reports for
     * @param limit - Maximum number of reports to return
     */
    getReports(ip: string, limit?: number): Promise<IPReport[]>;
    /**
     * Get cache statistics
     */
    getCacheStats(): {
        l1Size: number;
        l1MaxSize: number;
        refreshInProgress: number;
    };
    /**
     * Clear all caches
     */
    clearCaches(): Promise<void>;
    /**
     * Stop the service and cleanup resources
     */
    stop(): Promise<void>;
}
/**
 * Options for IP reputation middleware
 */
export interface IPReputationMiddlewareOptions {
    /** IP reputation service instance */
    service?: IPReputationService;
    /** Service configuration (if not providing service instance) */
    config?: Partial<IPReputationConfig>;
    /** Score threshold for blocking (default: 20) */
    blockThreshold?: number;
    /** Paths to skip reputation checks for */
    skipPaths?: string[];
    /** Whether to add reputation header */
    addReputationHeader?: boolean;
    /** Custom response for blocked IPs */
    blockedResponse?: (ip: string, reputation: IPReputation) => {
        statusCode: number;
        body: Record<string, unknown>;
    };
    /** Log level for suspicious IPs (score < 50) */
    logSuspiciousIPs?: boolean;
    /** Minimum score to log as suspicious */
    suspiciousThreshold?: number;
}
/**
 * Creates Fastify middleware for IP reputation checking
 *
 * @param options - Middleware options
 * @returns Fastify preHandler hook
 *
 * @example
 * ```typescript
 * const ipReputationMiddleware = ipReputationCheck({
 *   blockThreshold: 20,
 *   skipPaths: ['/health', '/metrics'],
 *   addReputationHeader: true,
 * });
 *
 * fastify.addHook('preHandler', ipReputationMiddleware);
 * ```
 */
export declare function ipReputationCheck(options?: IPReputationMiddlewareOptions): preHandlerHookHandler;
declare module 'fastify' {
    interface FastifyRequest {
        ipReputation?: IPReputation;
    }
}
/**
 * Gets or creates the singleton IPReputationService instance
 *
 * @param config - Optional configuration (only used on first call)
 * @returns The singleton IPReputationService instance
 */
export declare function getIPReputationService(config?: Partial<IPReputationConfig>): IPReputationService;
/**
 * Resets the singleton instance (primarily for testing)
 */
export declare function resetIPReputationService(): Promise<void>;
//# sourceMappingURL=ip-reputation.d.ts.map