<?php
// API 安全增强
function enhanceAPISecurity() {
    // 1. 请求频率限制
    function rateLimit($identifier, $limit = 60, $window = 3600) {
        $key = "rate_limit_" . md5($identifier);
        $current = apcu_fetch($key, $success);
        
        if (!$success || $current < $limit) {
            apcu_store($key, $current + 1, $window);
            return true;
        }
        
        return false;
    }
    
    // 2. 请求签名验证
    function verifyRequestSignature($data, $signature, $secret) {
        $expectedSignature = hash_hmac('sha256', json_encode($data), $secret);
        return hash_equals($expectedSignature, $signature);
    }
    
    // 3. IP 白名单
    $allowedIPs = [
        '127.0.0.1',
        '::1',
        // 添加你的服务器IP
    ];
    
    if (!in_array($_SERVER['REMOTE_ADDR'], $allowedIPs)) {
        // 记录可疑请求
        error_log("Suspicious API request from IP: " . $_SERVER['REMOTE_ADDR']);
        // 可以选择阻止或要求额外验证
    }
    
    // 4. 请求头安全
    header('X-Content-Type-Options: nosniff');
    header('X-Frame-Options: DENY');
    header('X-XSS-Protection: 1; mode=block');
    header('Strict-Transport-Security: max-age=31536000; includeSubDomains');
    header('Content-Security-Policy: default-src \'self\'');
}

// 文件上传安全增强
function enhanceFileUploadSecurity() {
    // 1. 文件类型白名单
    $allowedTypes = [
        'image/jpeg', 'image/png', 'image/gif', 'image/webp',
        'application/pdf', 'text/plain',
        // 添加其他允许的类型
    ];
    
    // 2. 文件大小限制
    $maxFileSize = 10 * 1024 * 1024; // 10MB
    
    // 3. 文件名安全
    function sanitizeFileName($filename) {
        $filename = preg_replace('/[^a-zA-Z0-9._-]/', '', $filename);
        $filename = trim($filename, '.');
        return $filename;
    }
    
    // 4. 病毒扫描（可选）
    function scanFile($filePath) {
        // 集成 ClamAV 或其他病毒扫描
        return true;
    }
}
?>