<?php
/**
 * 实时保护：服务端请求检测、临时 IP 拦截、陌生设备记录、F12 上报与完整性自检。
 * 这里只做防御，不执行任何远程规则或第三方代码。
 */

function realtime_guard_enabled()
{
    return setting('realtime_guard_enabled', '1') === '1';
}

/**
 * F12 / 右键自动刷新：实时保护下的子开关。
 * 开启后前端检测到调试快捷键或右键菜单，先上报当前 IP，再立即刷新页面。
 */
function realtime_guard_refresh_enabled()
{
    return realtime_guard_enabled() && setting('realtime_guard_refresh_enabled', '0') === '1';
}

function realtime_guard_ip()
{
    // Cloudflare 直连时优先使用其真实客户端 IP；普通直连不信任可伪造的 XFF。
    $cf = trim((string) ($_SERVER['HTTP_CF_CONNECTING_IP'] ?? ''));
    if (filter_var($cf, FILTER_VALIDATE_IP)) { return $cf; }
    $remote = trim((string) ($_SERVER['REMOTE_ADDR'] ?? ''));
    if (filter_var($remote, FILTER_VALIDATE_IP)) {
        if (!ip_is_private($remote)) { return $remote; }
        $forwarded = trim((string) explode(',', (string) ($_SERVER['HTTP_X_FORWARDED_FOR'] ?? ''))[0]);
        if (filter_var($forwarded, FILTER_VALIDATE_IP)) { return $forwarded; }
        return $remote;
    }
    return (string) client_ip();
}

/** 读取当前设备的持久设备 ID 指纹，不主动创建 Cookie。 */
function guard_ban_device_fingerprint()
{
    $value = strtolower(trim((string) ($_COOKIE['km_guard_device'] ?? '')));
    if (!preg_match('/^[a-f0-9]{32}$/', $value)) { return ''; }
    return hash('sha256', $value);
}

/** 超级管理员设备指纹集合：这些设备不能被永久封禁。 */
function guard_superadmin_device_fingerprints()
{
    static $set = null;
    if ($set === null) {
        $set = [];
        try {
            $rows = DB::all('SELECT d.fingerprint FROM ' . DB::table('guard_devices') . ' d INNER JOIN ' . DB::table('users') . " u ON u.id = d.user_id WHERE u.role = 'superadmin' AND d.fingerprint <> ''");
            foreach ($rows as $row) {
                $fp = strtolower((string) ($row['fingerprint'] ?? ''));
                if ($fp !== '') { $set[$fp] = true; }
            }
        } catch (Throwable $e) {
        }
    }
    return $set;
}

/** 超级管理员设备最近使用过的 IP 集合：这些 IP 不能被永久封禁。 */
function guard_superadmin_ip_set()
{
    static $set = null;
    if ($set === null) {
        $set = [];
        try {
            $rows = DB::all('SELECT DISTINCT d.ip FROM ' . DB::table('guard_devices') . ' d INNER JOIN ' . DB::table('users') . " u ON u.id = d.user_id WHERE u.role = 'superadmin' AND d.ip <> ''");
            foreach ($rows as $row) {
                $ip = (string) ($row['ip'] ?? '');
                if ($ip !== '') { $set[$ip] = true; }
            }
        } catch (Throwable $e) {
        }
    }
    return $set;
}

function guard_device_is_superadmin($fingerprint)
{
    $fingerprint = strtolower(trim((string) $fingerprint));
    if ($fingerprint === '') { return false; }
    $set = guard_superadmin_device_fingerprints();
    if (isset($set[$fingerprint])) { return true; }
    return hash_equals($fingerprint, guard_ban_device_fingerprint()) && is_superadmin(current_user());
}

function guard_ip_is_superadmin($ip)
{
    $ip = trim((string) $ip);
    if ($ip === '') { return false; }
    $set = guard_superadmin_ip_set();
    if (isset($set[$ip])) { return true; }
    return $ip === realtime_guard_ip() && is_superadmin(current_user());
}

/** 封禁前检查超管保护，返回拒绝原因；空字符串表示可以封禁。 */
function guard_ban_protected_reason($type, $value, $ipValue = '')
{
    if ((string) $type === 'device') {
        if (guard_device_is_superadmin($value)) {
            return '该设备属于超级管理员，已受保护，不能封禁';
        }
        if ((string) $ipValue !== '' && guard_ip_is_superadmin($ipValue)) {
            return '该设备与超级管理员设备共用 IP，封禁会连带锁死超管，已受保护';
        }
    }
    if ((string) $type === 'ip' && guard_ip_is_superadmin($value)) {
        return '该 IP 属于超级管理员设备，已受保护，不能封禁';
    }
    return '';
}

/**清理历史遗留的超管设备 / IP 封禁记录，升级后也不会把超管锁在门外。 */
function guard_ban_cleanup_superadmin()
{
    $ips = array_keys(guard_superadmin_ip_set());
    $fps = array_keys(guard_superadmin_device_fingerprints());
    if (!$ips && !$fps) { return; }
    try {
        foreach ($fps as $fp) {
            DB::run('DELETE FROM ' . DB::table('guard_bans') . " WHERE ban_type = 'device' AND ban_value = ?", [$fp]);
            DB::run('DELETE FROM ' . DB::table('guard_bans') . " WHERE ban_type = 'device' AND ip_value = ?", [guard_ban_device_last_ip($fp)]);
        }
        foreach ($ips as $ip) {
            DB::run('DELETE FROM ' . DB::table('guard_bans') . " WHERE ban_type = 'ip' AND ban_value = ?", [$ip]);
            DB::run('DELETE FROM ' . DB::table('guard_bans') . " WHERE ban_type = 'device' AND ip_value = ?", [$ip]);
        }
    } catch (Throwable $e) {
    }
}

function guard_ban_ensure_table()
{
    static $done = false;
    if ($done) { return; }
    $done = true;
    try {
        $table = DB::table('guard_bans');
        if (DB::$driver === 'sqlite') {
            DB::run('CREATE TABLE IF NOT EXISTS ' . $table . " (id INTEGER PRIMARY KEY AUTOINCREMENT, ban_type VARCHAR(16) DEFAULT '', ban_value VARCHAR(128) DEFAULT '', ip_value VARCHAR(64) DEFAULT '', reason VARCHAR(255) DEFAULT '', source_uid INT DEFAULT 0, created_by INT DEFAULT 0, created_at VARCHAR(20) DEFAULT '', hits INT DEFAULT 0, last_hit_at VARCHAR(20) DEFAULT '', UNIQUE(ban_type, ban_value))");
        } else {
            DB::run('CREATE TABLE IF NOT EXISTS ' . $table . " (id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, ban_type VARCHAR(16) DEFAULT '', ban_value VARCHAR(128) DEFAULT '', ip_value VARCHAR(64) DEFAULT '', reason VARCHAR(255) DEFAULT '', source_uid INT DEFAULT 0, created_by INT DEFAULT 0, created_at VARCHAR(20) DEFAULT '', hits INT DEFAULT 0, last_hit_at VARCHAR(20) DEFAULT '', UNIQUE KEY guard_ban_unique (ban_type, ban_value)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
        }
        // 旧站点补列：记录这条 IP / 设备封禁由哪个账号的永久封禁连带产生，账号解封时可精准解除。
        try { DB::run('ALTER TABLE ' . $table . ' ADD COLUMN source_uid INT DEFAULT 0'); } catch (Throwable $e) {}
    } catch (Throwable $e) {
        // 表创建失败时保持页面可用；封禁接口会返回明确错误。
    }
    guard_ban_cleanup_superadmin();
}

function guard_ban_normalize_value($type, $value)
{
    $value = trim((string) $value);
    if ($type === 'ip') {
        return filter_var($value, FILTER_VALIDATE_IP) ? $value : '';
    }
    if ($type === 'device') {
        return preg_match('/^[a-f0-9]{64}$/', $value) ? $value : '';
    }
    return '';
}

function guard_ban_add($type, $value, $reason = '', $createdBy = 0, $ipValue = '', $sourceUid = 0)
{
    guard_ban_ensure_table();
    $type = in_array($type, ['ip', 'device'], true) ? $type : '';
    $value = guard_ban_normalize_value($type, $value);
    if ($type === '' || $value === '') { return [false, '封禁目标格式不正确']; }
    $protected = guard_ban_protected_reason($type, $value, $ipValue);
    if ($protected !== '') { return [false, $protected]; }
    $ipValue = trim((string) $ipValue);
    if (!filter_var($ipValue, FILTER_VALIDATE_IP)) { $ipValue = ''; }
    if ($type === 'ip') { $ipValue = ''; }
    $sourceUid = max(0, (int) $sourceUid);
    $reason = mb_substr(trim((string) $reason), 0, 255);
    if ($reason === '') { $reason = $type === 'ip' ? '管理员手动封禁 IP' : '管理员手动封禁设备'; }
    try {
        $row = DB::one('SELECT id FROM ' . DB::table('guard_bans') . ' WHERE ban_type = ? AND ban_value = ? LIMIT 1', [$type, $value]);
        if ($row) {
            DB::run('UPDATE ' . DB::table('guard_bans') . ' SET ip_value = ?, reason = ?, source_uid = ?, created_by = ?, created_at = ? WHERE id = ?',
                [$ipValue, $reason, $sourceUid, (int) $createdBy, now(), (int) $row['id']]);
        } else {
            DB::insert('guard_bans', [
                'ban_type' => $type,
                'ban_value' => $value,
                'ip_value' => $ipValue,
                'reason' => $reason,
                'source_uid' => $sourceUid,
                'created_by' => (int) $createdBy,
                'created_at' => now(),
                'hits' => 0,
                'last_hit_at' => '',
            ]);
        }
        return [true, $type === 'ip' ? '已永久封禁该 IP' : '已永久封禁该设备' . ($ipValue !== '' ? '（同时锁定常用 IP）' : '')];
    } catch (Throwable $e) {
        return [false, '写入封禁记录失败'];
    }
}

/** 账号被设为永久封禁时，把最近登录 IP 与设备一并送入木卫守护；返回可展示的联动结果。 */
function account_ban_link_guard($uid, $reason, $createdBy = 0, $target = null)
{
    $uid = (int) $uid;
    if ($uid <= 0) { return []; }
    $reason = mb_substr(trim((string) $reason), 0, 220);
    $reasonText = '永久封禁账号 UID ' . $uid . '：' . $reason;
    $parts = [];
    $lastIp = '';
    try {
        $lastLogin = DB::one('SELECT ip FROM ' . DB::table('login_logs') . ' WHERE user_id = ? AND result = ? AND ip <> ? ORDER BY id DESC LIMIT 1', [$uid, 'success', '']);
        $lastIp = trim((string) ($lastLogin['ip'] ?? ''));
    } catch (Throwable $e) {}
    if ($lastIp === '' && is_array($target)) {
        $lastIp = trim((string) ($target['last_ip'] ?? ''));
    }
    if ($lastIp !== '' && filter_var($lastIp, FILTER_VALIDATE_IP)) {
        list($ipOk, $ipMsg) = guard_ban_add('ip', $lastIp, $reasonText, (int) $createdBy, '', $uid);
        $parts[] = $ipOk ? 'IP ' . $lastIp : 'IP 未封禁（' . $ipMsg . '）';
    }
    $fingerprint = '';
    try {
        $fingerprint = (string) DB::val('SELECT fingerprint FROM ' . DB::table('guard_devices') . ' WHERE user_id = ? AND fingerprint <> ? ORDER BY last_at DESC, id DESC LIMIT 1', [$uid, ''], '');
    } catch (Throwable $e) {}
    if ($fingerprint !== '') {
        list($devOk, $devMsg) = guard_ban_add('device', $fingerprint, $reasonText, (int) $createdBy, $lastIp, $uid);
        $parts[] = $devOk ? '设备指纹' : '设备未封禁（' . $devMsg . '）';
    }
    return $parts;
}

/** 解封账号时，只自动解除由该账号永久封禁连带产生的 IP / 设备封禁，不动管理员手动封禁记录。 */
function guard_ban_release_account($uid)
{
    guard_ban_ensure_table();
    $uid = (int) $uid;
    $result = ['total' => 0, 'ip' => 0, 'device' => 0];
    if ($uid <= 0) { return $result; }
    $prefix = '永久封禁账号 UID ' . $uid . '：';
    try {
        try {
            $rows = DB::all('SELECT id, ban_type FROM ' . DB::table('guard_bans') . ' WHERE source_uid = ? OR (source_uid = 0 AND reason LIKE ?)', [$uid, $prefix . '%']);
        } catch (Throwable $e) {
            // 极少数主机无法补列时，退回按封禁原因前缀匹配旧记录。
            $rows = DB::all('SELECT id, ban_type FROM ' . DB::table('guard_bans') . ' WHERE reason LIKE ?', [$prefix . '%']);
        }
        foreach ($rows as $row) {
            if (!guard_ban_remove((int) $row['id'])) { continue; }
            $result['total']++;
            if ((string) $row['ban_type'] === 'ip') { $result['ip']++; } else { $result['device']++; }
        }
    } catch (Throwable $e) {
    }
    return $result;
}

/** 设备封禁时取该设备最近一次使用的 IP，用于换浏览器后仍按同 IP 拦截。 */
function guard_ban_device_last_ip($fingerprint)
{
    $fingerprint = strtolower(trim((string) $fingerprint));
    if (!preg_match('/^[a-f0-9]{64}$/', $fingerprint)) { return ''; }
    try {
        $ip = (string) DB::val('SELECT ip FROM ' . DB::table('guard_devices') . ' WHERE fingerprint = ? ORDER BY last_at DESC, id DESC LIMIT 1', [$fingerprint], '');
        return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '';
    } catch (Throwable $e) {
        return '';
    }
}

function guard_ban_remove($id)
{
    guard_ban_ensure_table();
    try {
        DB::run('DELETE FROM ' . DB::table('guard_bans') . ' WHERE id = ?', [(int) $id]);
        return true;
    } catch (Throwable $e) {
        return false;
    }
}

function guard_ban_list($type = '')
{
    guard_ban_ensure_table();
    try {
        if (in_array($type, ['ip', 'device'], true)) {
            return DB::all('SELECT * FROM ' . DB::table('guard_bans') . ' WHERE ban_type = ? ORDER BY id DESC LIMIT 200', [$type]);
        }
        return DB::all('SELECT * FROM ' . DB::table('guard_bans') . ' ORDER BY id DESC LIMIT 200');
    } catch (Throwable $e) {
        return [];
    }
}

function guard_ban_match($ip = '', $fingerprint = '')
{
    guard_ban_ensure_table();
    // 超管设备 / 超管 IP 不受历史封禁记录影响，避免升级前已有的误封把站点锁死。
    if ($ip !== '' && guard_ip_is_superadmin($ip)) { return null; }
    if ($fingerprint !== '' && guard_device_is_superadmin($fingerprint)) { return null; }
    try {
        if ($ip !== '') {
            $row = DB::one('SELECT * FROM ' . DB::table('guard_bans') . " WHERE ban_type = 'ip' AND ban_value = ? LIMIT 1", [$ip]);
            if ($row) { return $row; }
            // 设备封禁会记录常用 IP；同一网络换浏览器也会命中。
            $row = DB::one('SELECT * FROM ' . DB::table('guard_bans') . " WHERE ban_type = 'device' AND ip_value = ? LIMIT 1", [$ip]);
            if ($row) { return $row; }
            // 兼容升级前的设备封禁记录：没有 ip_value 时，用该设备已知的最近 IP 补判。
            try {
                $row = DB::one('SELECT b.* FROM ' . DB::table('guard_bans') . ' b INNER JOIN ' . DB::table('guard_devices') . ' d ON d.fingerprint = b.ban_value WHERE b.ban_type = ? AND b.ip_value = ? AND d.ip = ? LIMIT 1', ['device', '', $ip]);
                if ($row) { return $row; }
            } catch (Throwable $e) {
            }
        }
        if ($fingerprint !== '') {
            $row = DB::one('SELECT * FROM ' . DB::table('guard_bans') . " WHERE ban_type = 'device' AND ban_value = ? LIMIT 1", [$fingerprint]);
            if ($row) { return $row; }
        }
    } catch (Throwable $e) {
    }
    return null;
}

function guard_ban_hit($ban)
{
    if (!is_array($ban) || empty($ban['id'])) { return; }
    try {
        DB::run('UPDATE ' . DB::table('guard_bans') . ' SET hits = hits + 1, last_hit_at = ? WHERE id = ?', [now(), (int) $ban['id']]);
    } catch (Throwable $e) {
    }
}

function guard_ban_admin_bypass()
{
    if (!function_exists('current_user')) { return false; }
    $user = current_user();
    return $user && function_exists('is_admin') && is_admin($user);
}

/** 登录页允许被永久封禁的 IP 访问，便于管理员 / 超级管理员登录后台自行解封。 */
function guard_ban_login_bypass()
{
    $page = strtolower(trim((string) ($_GET['page'] ?? '')));
    return $page === 'login';
}

function guard_ban404_video_extensions()
{
    return ['mp4', 'm4v', 'mov', 'webm', 'ogv', 'ogg', 'mpeg', 'mpg', 'avi', 'mkv', 'wmv', 'flv', '3gp'];
}

function guard_ban404_config()
{
    $media = trim((string) setting('guard_ban404_media', ''));
    $media = str_replace('\\', '/', $media);
    $mediaOk = $media !== '' && strpos($media, 'uploads/security_guard/ban404/') === 0
        && strpos($media, '..') === false && is_file(APP_ROOT . '/' . $media);
    $type = strtolower((string) setting('guard_ban404_media_type', ''));
    if (!in_array($type, ['image', 'video'], true)) {
        $ext = strtolower((string) pathinfo($media, PATHINFO_EXTENSION));
        $type = in_array($ext, guard_ban404_video_extensions(), true) ? 'video' : 'image';
    }
    $title = trim((string) setting('guard_ban404_title', '访问已被限制'));
    $message = (string) setting('guard_ban404_message', "该设备或所在 IP 已被木卫守护永久封禁。\n如有疑问，请联系站点管理员。");
    return [
        'enabled' => (string) setting('guard_ban404_enabled', '1') === '1',
        'title' => $title !== '' ? $title : '访问已被限制',
        'message' => trim($message) !== '' ? $message : '该设备已被木卫守护永久封禁。',
        'media' => $mediaOk ? $media : '',
        'media_type' => $mediaOk ? $type : 'image',
        'media_name' => $mediaOk ? (string) setting('guard_ban404_media_name', basename($media)) : '',
        'media_url' => $mediaOk ? upload_url($media) : '',
    ];
}

function guard_ban_404()
{
    http_response_code(404);
    header('Content-Type: text/html; charset=utf-8');
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('X-Robots-Tag: noindex, nofollow');
    $config = guard_ban404_config();
    if (!$config['enabled']) {
        echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>404 Not Found</title></head><body><h1>404 Not Found</h1><p>The requested URL was not found on this server.</p></body></html>';
        exit;
    }
    $title = e($config['title']);
    $message = nl2br(e($config['message']));
    $mediaHtml = '';
    if ($config['media'] !== '' && $config['media_url'] !== '') {
        if ($config['media_type'] === 'video') {
            $mediaHtml = '<div class="ban404-media-wrap"><video class="ban404-media" autoplay muted loop playsinline controls preload="metadata"><source src="' . e($config['media_url']) . '">您的浏览器不支持视频播放。</video></div>';
        } else {
            $mediaHtml = '<div class="ban404-media-wrap"><img class="ban404-media" src="' . e($config['media_url']) . '" alt="' . e($config['media_name']) . '"></div>';
        }
    }
    echo '<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><title>' . $title . ' · 404 · 木漏茶室</title>'
        . '<style>*{box-sizing:border-box}body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:24px 16px;background:radial-gradient(900px 540px at 15% -10%,#ffffff 0%,#eef7fd 48%,#dcecf7 100%);color:#28495d;font-family:-apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif}'
        . '.ban404-card{width:min(720px,100%);padding:22px 20px 20px;border:1px solid rgba(170,205,225,.8);border-radius:24px;background:rgba(255,255,255,.92);box-shadow:0 26px 70px rgba(82,132,166,.16);text-align:center}'
        . '.ban404-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;background:rgba(91,151,183,.12);color:#3f7996;font-size:11px;letter-spacing:.12em}'
        . '.ban404-snow{width:42px;height:42px;margin:10px auto 6px;display:block;opacity:.9}'
        . '.ban404-media-wrap{margin:16px auto 18px;border-radius:16px;overflow:hidden;background:#eef7fc;box-shadow:0 12px 30px rgba(72,130,160,.12)}'
        . '.ban404-media{display:block;width:100%;max-height:min(56vh,520px);height:auto;object-fit:contain;margin:0 auto;background:#eef7fc}'
        . 'video.ban404-media{min-height:180px}'
        . '.ban404-title{font-size:23px;line-height:1.35;margin:12px 0 8px;letter-spacing:.04em;font-weight:700;color:#24495f}'
        . '.ban404-message{font-size:13px;line-height:1.9;margin:0;color:#6b8da3;word-break:break-word}'
        . '.ban404-footer{margin-top:18px;padding-top:12px;border-top:1px dashed rgba(150,190,212,.5);font-size:10.5px;letter-spacing:.08em;color:#8ca9bb}'
        . '@media(max-width:520px){body{padding:18px 12px}.ban404-card{padding:18px 14px 16px;border-radius:20px}.ban404-title{font-size:20px}.ban404-media-wrap{margin:13px auto 15px}}'
        . '</style></head><body><main class="ban404-card">'
        . '<div class="ban404-badge">404 · ACCESS RESTRICTED</div>'
        . '<svg class="ban404-snow" viewBox="0 0 64 64" fill="none" stroke="#8fbcd8" stroke-width="2"><g stroke-linecap="round"><path d="M32 6v52M10 19l44 26M54 19L10 45"/><path d="M32 14l-5 5M32 14l5 5M32 50l-5-5M32 50l5-5"/><circle cx="32" cy="32" r="5" fill="#eaf5fb"/></g></svg>'
        . $mediaHtml
        . '<h1 class="ban404-title">' . $title . '</h1>'
        . '<p class="ban404-message">' . $message . '</p>'
        . '<div class="ban404-footer">木漏茶室 · 木卫守护</div>'
        . '</main></body></html>';
    exit;
}

function realtime_guard_is_admin_context()
{
    if (!function_exists('current_user') || !current_user()) { return false; }
    if (!is_admin(current_user())) { return false; }
    return (string) input('page', '') === 'admin' || strpos((string) ($_SERVER['SCRIPT_NAME'] ?? ''), '/admin/') !== false;
}

/** 记录一条实时保护事件；IP 使用 REMOTE_ADDR，避免伪造 X-Forwarded-For。 */
function realtime_guard_event($kind, $identifier = '', $fingerprint = null, $userId = null)
{
    try {
        if ($fingerprint === null) { $fingerprint = guard_ban_device_fingerprint(); }
        if ($userId === null) {
            $user = function_exists('current_user') ? current_user() : null;
            $userId = $user ? (int) $user['id'] : 0;
        }
        DB::insert('security_events', [
            'kind' => mb_substr((string) $kind, 0, 32),
            'ip' => mb_substr(realtime_guard_ip(), 0, 64),
            'identifier' => mb_substr((string) $identifier, 0, 128),
            'fingerprint' => mb_substr((string) $fingerprint, 0, 64),
            'user_id' => (int) $userId,
            'created_at' => now(),
        ]);
    } catch (Throwable $e) {
    }
}

function realtime_guard_detect()
{
    $uri = rawurldecode((string) ($_SERVER['REQUEST_URI'] ?? ''));
    if (mb_strlen($uri) > 3000) { $uri = mb_substr($uri, 0, 3000); }
    $ua = (string) ($_SERVER['HTTP_USER_AGENT'] ?? '');
    $method = strtoupper((string) ($_SERVER['REQUEST_METHOD'] ?? 'GET'));

    $needles = ['uri' => $uri, 'ua' => $ua, 'method' => $method];
    foreach ((array) $_GET as $key => $value) {
        if (is_scalar($value)) {
            $needles['get:' . mb_substr((string) $key, 0, 40)] = mb_substr((string) $value, 0, 500);
        }
    }

    $rules = [
        'sqli' => ['label' => 'SQL 注入', 're' => '~((?:union\s+(?:all\s+)?select)|(?:select\s+[^?&;\s]{0,80}\s+from\b)|(?:sleep|benchmark)\s*\(|information_schema|extractvalue\s*\(|updatexml\s*\(|(?:or|and)\s+1\s*=\s*1)~i', 'fields' => ['uri', 'get']],
        'xss' => ['label' => 'XSS 注入', 're' => '~(<script\b|javascript\s*:|on(?:error|load|click)\s*=|document\.cookie|eval\s*\()~i', 'fields' => ['uri', 'get']],
        'traversal' => ['label' => '路径穿越', 're' => '~((?:\.\./)|(?:%2e%2e)|(?:/etc/passwd)|(?:php://)|(?:data://)|(?:expect://)|(?:proc/self))~i', 'fields' => ['uri', 'get']],
        'rce' => ['label' => '命令执行', 're' => '~((?:[;|]\s*(?:cat|wget|curl|bash|sh|nc|python)\s)|(?:\$\([^)]{0,80}\))|(?:`[^`]{0,80}`))~i', 'fields' => ['uri', 'get']],
        'scanner' => ['label' => '扫描器', 're' => '~(sqlmap|nikto|nmap|masscan|acunetix|nessus|dirbuster|gobuster|zgrab|whatweb)~i', 'fields' => ['ua']],
    ];

    foreach ($rules as $id => $rule) {
        foreach ($needles as $field => $value) {
            $fieldPrefix = strpos($field, 'get:') === 0 ? 'get' : $field;
            if (!in_array($fieldPrefix, $rule['fields'], true)) { continue; }
            if ($value !== '' && preg_match($rule['re'], $value)) {
                return ['id' => $id, 'label' => $rule['label'], 'field' => $field];
            }
        }
    }
    if (in_array($method, ['TRACE', 'TRACK'], true)) {
        return ['id' => 'method', 'label' => '危险请求方法', 'field' => 'method'];
    }
    return null;
}

function realtime_guard_block_minutes()
{
    return max(1, min(1440, (int) setting('realtime_guard_block_minutes', '30')));
}

function realtime_guard_block($ip, $reason, $minutes = 0)
{
    $ip = trim((string) $ip);
    if (!filter_var($ip, FILTER_VALIDATE_IP)) { return; }
    $minutes = $minutes > 0 ? max(1, min(1440, (int) $minutes)) : realtime_guard_block_minutes();
    $until = time() + $minutes * 60;
    try {
        $row = DB::one('SELECT id, until, hits FROM ' . DB::table('guard_blocks') . ' WHERE ip = ? LIMIT 1', [$ip]);
        if ($row) {
            DB::run('UPDATE ' . DB::table('guard_blocks') . ' SET reason = ?, until = ?, hits = ?, updated_at = ? WHERE id = ?',
                [mb_substr((string) $reason, 0, 255), max((int) $row['until'], $until), (int) $row['hits'] + 1, now(), (int) $row['id']]);
        } else {
            DB::insert('guard_blocks', [
                'ip' => mb_substr($ip, 0, 64),
                'reason' => mb_substr((string) $reason, 0, 255),
                'until' => $until,
                'hits' => 1,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    } catch (Throwable $e) {
    }
}

function realtime_guard_block_row($ip)
{
    try {
        $row = DB::one('SELECT * FROM ' . DB::table('guard_blocks') . ' WHERE ip = ? LIMIT 1', [(string) $ip]);
        if (!$row) { return null; }
        if ((int) $row['until'] <= time()) {
            DB::run('DELETE FROM ' . DB::table('guard_blocks') . ' WHERE id = ?', [(int) $row['id']]);
            return null;
        }
        return $row;
    } catch (Throwable $e) {
        return null;
    }
}

function realtime_guard_forbidden($reason = '')
{
    $minutes = realtime_guard_block_minutes();
    @header('Retry-After: ' . ($minutes * 60));
    http_response_code(403);
    if (strpos((string) ($_SERVER['HTTP_ACCEPT'] ?? ''), 'application/json') !== false
        || strtolower((string) ($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '')) === 'xmlhttprequest') {
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['ok' => false, 'msg' => '请求已被实时保护拦截，请稍后再试'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    header('Content-Type: text/html; charset=utf-8');
    $reason = htmlspecialchars((string) $reason, ENT_QUOTES, 'UTF-8');
    echo <<<HTML
<!DOCTYPE html><html lang="zh-CN"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>安全保护 · 木漏茶室</title>
<style>
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;background:radial-gradient(900px 500px at 20% 0%,#fff,#eaf5fc 60%,#dbeaf6);color:#2b4a5e;font-family:-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;padding:24px}
.card{max-width:460px;width:100%;background:rgba(255,255,255,.94);border:1px solid #d9e9f5;border-radius:22px;padding:34px 28px;box-shadow:0 24px 60px rgba(110,155,195,.18);text-align:center}
.shield{width:56px;height:56px;margin:0 auto 14px;border-radius:50%;display:flex;align-items:center;justify-content:center;background:#e9f5fc;color:#5e9fc4;font-size:26px}
h1{font-size:17px;font-weight:600;margin:0 0 10px;letter-spacing:.06em}
p{font-size:13px;color:#7692a5;line-height:1.9;margin:0 0 8px}
small{font-size:11px;color:#a5bac9}
</style></head><body><div class="card">
<div class="shield">🛡</div>
<h1>当前访问已被实时保护拦截</h1>
<p>系统检测到本次请求存在风险，已临时限制当前 IP 的访问。</p>
<p><small>{$reason}</small></p>
<small>如果你是站长，请登录后台「木卫守护 → 实时保护」解除拦截。</small>
</div></body></html>
HTML;
    exit;
}

function realtime_guard_device_token()
{
    $name = 'km_guard_device';
    $value = (string) ($_COOKIE[$name] ?? '');
    if (preg_match('/^[a-f0-9]{32}$/', $value)) { return $value; }
    try { $value = bin2hex(random_bytes(16)); } catch (Throwable $e) { $value = md5(uniqid('', true)); }
    if (!headers_sent()) {
        $https = (!empty($_SERVER['HTTPS']) && strtolower((string) $_SERVER['HTTPS']) !== 'off')
            || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https');
        setcookie($name, $value, [
            'expires' => time() + 365 * 86400,
            'path' => '/',
            'secure' => $https,
            'httponly' => true,
            'samesite' => 'Lax',
        ]);
    }
    $_COOKIE[$name] = $value;
    return $value;
}

function realtime_guard_is_bot()
{
    $ua = strtolower((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''));
    return $ua !== '' && preg_match('/bot|spider|crawl|slurp|bingpreview|facebookexternalhit|curl|wget|python-requests/', $ua);
}

function realtime_guard_record_device()
{
    if (setting('realtime_guard_device_log', '1') !== '1') { return; }
    if (PHP_SAPI === 'cli' || realtime_guard_is_bot()) { return; }
    try {
        $token = realtime_guard_device_token();
        $fingerprint = hash('sha256', $token);
        $uid = function_exists('current_user') && current_user() ? (int) current_user()['id'] : 0;
        $ip = realtime_guard_ip();
        $ua = mb_substr((string) ($_SERVER['HTTP_USER_AGENT'] ?? ''), 0, 255);
        $row = DB::one('SELECT id, user_id, visits FROM ' . DB::table('guard_devices') . ' WHERE fingerprint = ? LIMIT 1', [$fingerprint]);
        if ($row) {
            DB::run('UPDATE ' . DB::table('guard_devices') . ' SET user_id = ?, ip = ?, ua = ?, last_at = ?, visits = ? WHERE id = ?',
                [$uid, mb_substr($ip, 0, 64), $ua, now(), (int) $row['visits'] + 1, (int) $row['id']]);
            return;
        }
        DB::insert('guard_devices', [
            'fingerprint' => $fingerprint,
            'user_id' => $uid,
            'ip' => mb_substr($ip, 0, 64),
            'ua' => $ua,
            'first_at' => now(),
            'last_at' => now(),
            'visits' => 1,
        ]);
        realtime_guard_event('rt_new_device', 'UID ' . $uid . ' · ' . mb_substr($ua, 0, 90));
    } catch (Throwable $e) {
    }
}

function realtime_guard_self_check($rebuild = false)
{
    $files = ['inc/realtime_guard.php', 'assets/js/realtime-guard.js'];
    $hashes = [];
    $missing = [];
    foreach ($files as $file) {
        $full = APP_ROOT . '/' . $file;
        if (is_file($full)) { $hashes[$file] = hash_file('sha256', $full); }
        else { $hashes[$file] = ''; $missing[] = $file; }
    }
    $current = json_encode($hashes, JSON_UNESCAPED_SLASHES);
    $baseline = (string) setting('realtime_guard_file_hashes', '');
    if ($rebuild || trim($baseline) === '') {
        set_setting('realtime_guard_file_hashes', $current);
        return ['ok' => true, 'checked' => count($files), 'changed' => [], 'missing' => $missing, 'rebuilt' => true];
    }
    $old = json_decode($baseline, true);
    $changed = [];
    if (is_array($old)) {
        foreach ($hashes as $file => $hash) {
            if (($old[$file] ?? '') !== $hash) { $changed[] = $file; }
        }
    } else {
        $changed = array_keys($hashes);
    }
    if ($changed && security_recent_count('rt_self_tamper', '', 300) === 0) {
        realtime_guard_event('rt_self_tamper', implode('、', $changed));
    }
    return ['ok' => !$changed && !$missing, 'checked' => count($files), 'changed' => $changed, 'missing' => $missing, 'rebuilt' => false];
}

function realtime_guard_login_fail_count()
{
    $since = date('Y-m-d H:i:s', time() - 900);
    try {
        return (int) DB::val('SELECT COUNT(*) FROM ' . DB::table('security_events')
            . ' WHERE kind = ? AND ip = ? AND created_at >= ?', ['login_fail', realtime_guard_ip(), $since], 0);
    } catch (Throwable $e) {
        return 0;
    }
}

function realtime_guard_boot()
{
    if (PHP_SAPI === 'cli') { return; }
    $ip = realtime_guard_ip();
    if ($ip === '') { return; }

    // 永久封禁优先级最高；已登录管理员直接放行，登录页也放行以便管理员自行解封。
    if (!guard_ban_admin_bypass() && !guard_ban_login_bypass()) {
        $ban = guard_ban_match($ip, guard_ban_device_fingerprint());
        if ($ban) {
            guard_ban_hit($ban);
            guard_ban_404();
        }
    }

    if (!realtime_guard_enabled()) { return; }
    $adminContext = realtime_guard_is_admin_context();
    $block = realtime_guard_block_row($ip);
    if ($block && !$adminContext) {
        realtime_guard_event('rt_block_hit', mb_substr((string) ($block['reason'] ?? ''), 0, 120));
        realtime_guard_forbidden('该 IP 已被临时限制访问。');
    }

    realtime_guard_record_device();

    if ($adminContext) {
        if (empty($_SESSION['rt_self_checked_at']) || time() - (int) $_SESSION['rt_self_checked_at'] > 300) {
            $_SESSION['rt_self_checked_at'] = time();
            realtime_guard_self_check();
        }
        return;
    }

    $hit = realtime_guard_detect();
    if ($hit) {
        $path = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH);
        realtime_guard_event('rt_attack_' . $hit['id'], $hit['label'] . ' · ' . mb_substr($path, 0, 100));
        realtime_guard_block($ip, '实时检测：' . $hit['label']);
        realtime_guard_event('rt_block', $hit['label'] . ' · ' . mb_substr($path, 0, 100));
        realtime_guard_forbidden('检测到风险请求，已临时限制访问。');
    }

    if (realtime_guard_login_fail_count() >= 10) {
        realtime_guard_event('rt_bruteforce', '15 分钟内登录失败达到 10 次');
        realtime_guard_block($ip, '连续登录失败，疑似暴力破解');
        realtime_guard_event('rt_block', '连续登录失败，疑似暴力破解');
        realtime_guard_forbidden('登录失败次数过多，已临时限制访问。');
    }

    if (empty($_SESSION['rt_self_checked_at']) || time() - (int) $_SESSION['rt_self_checked_at'] > 300) {
        $_SESSION['rt_self_checked_at'] = time();
        realtime_guard_self_check();
    }
}

function guard_admin_device_rows($limit = 12)
{
    $limit = max(1, min(30, (int) $limit));
    try {
        $rows = DB::all('SELECT * FROM ' . DB::table('guard_devices') . ' ORDER BY last_at DESC, id DESC LIMIT ' . $limit);
    } catch (Throwable $e) {
        return [];
    }
    $deviceBans = [];
    foreach (guard_ban_list('device') as $ban) {
        $deviceBans[(string) $ban['ban_value']] = true;
    }
    $out = [];
    foreach ($rows as $row) {
        $ua = (string) ($row['ua'] ?? '');
        $ip = (string) ($row['ip'] ?? '');
        $uid = (int) ($row['user_id'] ?? 0);
        $user = $uid > 0 && function_exists('user_by_id') ? user_by_id($uid) : null;
        $fingerprint = (string) ($row['fingerprint'] ?? '');
        $type = client_device_category($ua);
        $out[] = [
            'id' => (int) $row['id'],
            'fingerprint' => $fingerprint,
            'fingerprint_short' => substr($fingerprint, 0, 12) . '…',
            'ip' => $ip,
            'ip_is_private' => $ip !== '' && ip_is_private($ip),
            'is_current_ip' => $ip !== '' && $ip === realtime_guard_ip(),
            'location' => $ip !== '' ? ip_location_detail_text($ip) : '未知属地',
            'ua' => $ua,
            'ua_short' => mb_substr($ua, 0, 96),
            'device_type' => $type,
            'device_type_label' => ['mobile' => '手机端', 'apple' => '苹果端', 'desktop' => '电脑端', 'tablet' => '平板端'][$type] ?? '电脑端',
            'device_icon' => ['mobile' => '📱', 'apple' => '🍎', 'desktop' => '💻', 'tablet' => '📟'][$type] ?? '💻',
            'user_id' => $uid,
            'user_name' => $user ? display_name($user) : '游客',
            'is_superadmin' => $user ? is_superadmin($user) : false,
            'is_superadmin_ip' => $ip !== '' && guard_ip_is_superadmin($ip),
            'visits' => (int) ($row['visits'] ?? 0),
            'note' => (string) ($row['note'] ?? ''),
            'first_at' => (string) ($row['first_at'] ?? ''),
            'last_at' => (string) ($row['last_at'] ?? ''),
            'is_current' => $fingerprint !== '' && hash_equals($fingerprint, guard_ban_device_fingerprint()),
            'is_banned' => isset($deviceBans[$fingerprint]),
        ];
    }
    return $out;
}

function guard_admin_ban_rows()
{
    $bans = guard_ban_list();
    $deviceTypes = [];
    try {
        $devices = DB::all('SELECT fingerprint, ua, ip FROM ' . DB::table('guard_devices') . ' ORDER BY last_at DESC LIMIT 100');
        foreach ($devices as $d) {
            $deviceTypes[(string) $d['fingerprint']] = client_device_category_label((string) ($d['ua'] ?? ''));
        }
    } catch (Throwable $e) {
    }
    $out = [];
    foreach ($bans as $ban) {
        $creator = ((int) ($ban['created_by'] ?? 0)) > 0 && function_exists('user_by_id') ? user_by_id((int) $ban['created_by']) : null;
        $out[] = [
            'id' => (int) $ban['id'],
            'ban_type' => (string) $ban['ban_type'],
            'ban_value' => (string) $ban['ban_value'],
            'ip_value' => (string) ($ban['ip_value'] ?? ''),
            'ban_value_short' => mb_strlen((string) $ban['ban_value'], 'UTF-8') > 32 ? mb_substr((string) $ban['ban_value'], 0, 28, 'UTF-8') . '…' : (string) $ban['ban_value'],
            'type_label' => (string) $ban['ban_type'] === 'ip' ? 'IP' : '设备',
            'device_type_label' => (string) $ban['ban_type'] === 'device' ? ($deviceTypes[(string) $ban['ban_value']] ?? '设备') : '',
            'reason' => (string) ($ban['reason'] ?? ''),
            'created_by_name' => $creator ? display_name($creator) : '管理员',
            'created_at' => (string) ($ban['created_at'] ?? ''),
            'hits' => (int) ($ban['hits'] ?? 0),
            'last_hit_at' => (string) ($ban['last_hit_at'] ?? ''),
        ];
    }
    return $out;
}

function realtime_guard_kind_label($kind, $identifier = '')
{
    $labels = [
        'rt_attack_sqli' => 'SQL 注入',
        'rt_attack_xss' => 'XSS 注入',
        'rt_attack_traversal' => '路径穿越',
        'rt_attack_rce' => '命令执行',
        'rt_attack_scanner' => '扫描器',
        'rt_attack_method' => '危险请求方法',
        'rt_bruteforce' => '暴力破解',
        'rt_devtools' => 'F12 / 开发者工具',
        'rt_debug_refresh' => 'F12 / 右键刷新',
        'rt_debug_refresh_on' => '自动刷新开启',
        'rt_debug_refresh_off' => '自动刷新关闭',
        'rt_new_device' => '陌生设备',
        'rt_block' => 'IP 拦截',
        'rt_block_hit' => '拦截命中',
        'rt_self_tamper' => '文件被改动',
        'rt_unblock' => '解除拦截',
        'rt_ban_ip' => '永久封禁 IP',
        'rt_ban_device' => '永久封禁设备',
        'rt_unban_ip' => '解除 IP 封禁',
        'rt_unban_device' => '解除设备封禁',
        'rt_guard_on' => '实时保护开启',
        'rt_guard_off' => '实时保护关闭',
    ];
    if ($kind === 'rt_attack_sqli') { return 'SQL 注入'; }
    if (isset($labels[$kind])) { return $labels[$kind]; }
    if (strpos($kind, 'rt_attack_') === 0) { return '攻击请求'; }
    return $kind !== '' ? $kind : '安全事件';
}

function realtime_guard_status($limit = 12)
{
    $limit = max(1, min(50, (int) $limit));
    $since = date('Y-m-d 00:00:00');
    $out = [
        'enabled' => realtime_guard_enabled(),
        'block_minutes' => realtime_guard_block_minutes(),
        'stats' => ['blocked' => 0, 'events_today' => 0, 'attacks_today' => 0, 'hits_today' => 0, 'devices_today' => 0, 'refresh_today' => 0, 'banned_ips' => 0, 'banned_devices' => 0],
        'refresh_enabled' => realtime_guard_refresh_enabled(),
        'refresh_setting' => setting('realtime_guard_refresh_enabled', '0') === '1',
        'refresh_latest' => null,
        'events' => [],
        'blocks' => [],
        'devices' => [],
        'bans' => [],
        'self_check' => ['ok' => true, 'changed' => [], 'missing' => []],
    ];
    try {
        $eventsTable = DB::table('security_events');
        $blocksTable = DB::table('guard_blocks');
        $devicesTable = DB::table('guard_devices');
        $out['stats']['blocked'] = (int) DB::val('SELECT COUNT(*) FROM ' . $blocksTable . ' WHERE until > ?', [time()], 0);
        $out['stats']['events_today'] = (int) DB::val('SELECT COUNT(*) FROM ' . $eventsTable . ' WHERE created_at >= ?', [$since], 0);
        $out['stats']['attacks_today'] = (int) DB::val('SELECT COUNT(*) FROM ' . $eventsTable . " WHERE created_at >= ? AND (kind LIKE 'rt_attack%' OR kind = 'rt_bruteforce')", [$since], 0);
        $out['stats']['hits_today'] = (int) DB::val('SELECT COUNT(*) FROM ' . $eventsTable . ' WHERE created_at >= ? AND kind = ?', [$since, 'rt_block_hit'], 0);
        $out['stats']['devices_today'] = (int) DB::val('SELECT COUNT(*) FROM ' . $devicesTable . ' WHERE first_at >= ?', [$since], 0);
        $out['stats']['refresh_today'] = (int) DB::val('SELECT COUNT(*) FROM ' . $eventsTable . ' WHERE kind = ? AND created_at >= ?', ['rt_debug_refresh', $since], 0);
        $latestRefresh = DB::one('SELECT kind, ip, identifier, created_at FROM ' . $eventsTable . ' WHERE kind = ? ORDER BY id DESC LIMIT 1', ['rt_debug_refresh']);
        if ($latestRefresh) {
            $out['refresh_latest'] = [
                'ip' => (string) $latestRefresh['ip'],
                'identifier' => (string) $latestRefresh['identifier'],
                'created_at' => (string) $latestRefresh['created_at'],
            ];
        }
        $blocks = DB::all('SELECT ip, reason, until, hits, created_at FROM ' . $blocksTable . ' WHERE until > ? ORDER BY until DESC LIMIT ' . $limit, [time()]);
        $blockMap = [];
        foreach ($blocks as $row) {
            $out['blocks'][] = [
                'ip' => (string) $row['ip'],
                'reason' => (string) $row['reason'],
                'until' => (int) $row['until'],
                'hits' => (int) $row['hits'],
                'created_at' => (string) $row['created_at'],
            ];
            $blockMap[(string) $row['ip']] = (int) $row['until'];
        }
        $out['bans'] = guard_admin_ban_rows();
        $deviceBanMap = [];
        $ipBanMap = [];
        foreach ($out['bans'] as $ban) {
            if ((string) $ban['ban_type'] === 'device') { $deviceBanMap[(string) $ban['ban_value']] = (int) $ban['id']; }
            if ((string) $ban['ban_type'] === 'ip') { $ipBanMap[(string) $ban['ban_value']] = (int) $ban['id']; }
        }
        $rows = DB::all('SELECT kind, ip, identifier, fingerprint, user_id, created_at FROM ' . $eventsTable . " WHERE kind LIKE 'rt_%' ORDER BY id DESC LIMIT " . $limit);
        foreach ($rows as $row) {
            $ip = (string) $row['ip'];
            $fingerprint = (string) ($row['fingerprint'] ?? '');
            $uid = (int) ($row['user_id'] ?? 0);
            $device = null;
            if ($fingerprint !== '') {
                $device = DB::one('SELECT fingerprint, user_id, ip, ua, note, last_at FROM ' . $devicesTable . ' WHERE fingerprint = ? LIMIT 1', [$fingerprint]);
            }
            if (!$device && $ip !== '') {
                $device = DB::one('SELECT fingerprint, user_id, ip, ua, note, last_at FROM ' . $devicesTable . ' WHERE ip = ? AND user_id > 0 ORDER BY last_at DESC, id DESC LIMIT 1', [$ip]);
            }
            if ($device) {
                if ($fingerprint === '') { $fingerprint = (string) ($device['fingerprint'] ?? ''); }
                if ($uid <= 0) { $uid = (int) ($device['user_id'] ?? 0); }
            }
            $user = $uid > 0 && function_exists('user_by_id') ? user_by_id($uid) : null;
            $type = client_device_category((string) ($device['ua'] ?? ''));
            $deviceBanId = $fingerprint !== '' && isset($deviceBanMap[$fingerprint]) ? $deviceBanMap[$fingerprint] : 0;
            $ipBanId = $ip !== '' && isset($ipBanMap[$ip]) ? $ipBanMap[$ip] : 0;
            $out['events'][] = [
                'kind' => (string) $row['kind'],
                'label' => realtime_guard_kind_label((string) $row['kind'], (string) $row['identifier']),
                'ip' => $ip,
                'location' => $ip !== '' ? ip_location_detail_text($ip) : '未知属地',
                'identifier' => (string) $row['identifier'],
                'created_at' => (string) $row['created_at'],
                'fingerprint' => $fingerprint,
                'user_id' => $uid,
                'user_name' => $user ? display_name($user) : '',
                'is_superadmin_device' => $user ? is_superadmin($user) : false,
                'is_superadmin_ip' => $ip !== '' && guard_ip_is_superadmin($ip),
                'device_type_label' => ['mobile' => '手机端', 'apple' => '苹果端', 'desktop' => '电脑端', 'tablet' => '平板端'][$type] ?? '电脑端',
                'device_icon' => ['mobile' => '📱', 'apple' => '🍎', 'desktop' => '💻', 'tablet' => '📟'][$type] ?? '💻',
                'ua' => (string) ($device['ua'] ?? ''),
                'ua_short' => mb_substr((string) ($device['ua'] ?? ''), 0, 96),
                'note' => (string) ($device['note'] ?? ''),
                'is_current' => $fingerprint !== '' && hash_equals($fingerprint, guard_ban_device_fingerprint()),
                'is_banned' => $deviceBanId > 0,
                'device_ban_id' => $deviceBanId,
                'is_ip_banned' => $ipBanId > 0,
                'ip_ban_id' => $ipBanId,
                'ip_is_private' => $ip !== '' && ip_is_private($ip),
                'is_current_ip' => $ip !== '' && $ip === realtime_guard_ip(),
                'is_temp_blocked' => isset($blockMap[$ip]),
                'block_until' => (int) ($blockMap[$ip] ?? 0),
            ];
        }
        $out['devices'] = guard_admin_device_rows(12);
        $out['stats']['banned_ips'] = count(array_filter($out['bans'], function ($b) { return $b['ban_type'] === 'ip'; }));
        $out['stats']['banned_devices'] = count(array_filter($out['bans'], function ($b) { return $b['ban_type'] === 'device'; }));
    } catch (Throwable $e) {
    }
    $out['self_check'] = realtime_guard_self_check(false);
    return $out;
}
