'管理员登录', 'agent_login' => '代理登录', 'agent_register'=> '代理注册', ]; /** * 读取配置缓存 * @return array{enabled:int, endpoints:array, secret:string, site_key:string} */ public static function config(): array { static $cache = null; if ($cache !== null) { return $cache; } $enabled = true; $endpoints = array_keys(self::ENDPOINTS); try { $db = Database::getInstance(); $rows = $db->fetchAll( "SELECT `key`, `value` FROM {$db->table('configs')} WHERE `key` IN ('turnstile_enabled','turnstile_endpoints')" ); $map = []; foreach ($rows as $r) { $map[$r['key']] = $r['value']; } if (isset($map['turnstile_enabled'])) { $enabled = (string) $map['turnstile_enabled'] === '1'; } if (isset($map['turnstile_endpoints']) && trim($map['turnstile_endpoints']) !== '') { $parts = array_filter(array_map('trim', explode(',', $map['turnstile_endpoints']))); $endpoints = array_values(array_intersect(array_keys(self::ENDPOINTS), $parts)); } } catch (\Throwable $e) { // 配置表不可用时保持默认:启用且仅登录注册 } $cache = [ 'enabled' => $enabled ? 1 : 0, 'endpoints' => $endpoints, 'secret' => (string) config('app.turnstile.secret_key', ''), 'site_key' => (string) config('app.turnstile.site_key', ''), ]; return $cache; } /** * 全局是否启用人机验证 */ public static function isEnabled(): bool { $c = self::config(); return $c['enabled'] === 1 && $c['secret'] !== ''; } /** * 指定入口是否需要人机验证 * @param string $endpoint admin_login|agent_login|agent_register */ public static function requiredFor(string $endpoint): bool { if (!self::isEnabled()) { return false; } $c = self::config(); return in_array($endpoint, $c['endpoints'], true); } /** * 校验 Turnstile token * @param string $endpoint 入口标识 */ public static function verifyFor(string $endpoint, ?string $token, ?string $remoteIp = null): bool { if (!self::requiredFor($endpoint)) { return true; } return self::verify($token, $remoteIp); } /** * 校验 Turnstile token(强制) * 未配置 secret 时跳过校验(便于本地开发) */ public static function verify(?string $token, ?string $remoteIp = null): bool { $secret = (string) config('app.turnstile.secret_key', ''); if ($secret === '') { return true; } if ($token === null || $token === '') { return false; } $payload = [ 'secret' => $secret, 'response' => $token, ]; if ($remoteIp) { $payload['remoteip'] = $remoteIp; } $ch = curl_init('https://challenges.cloudflare.com/turnstile/v0/siteverify'); curl_setopt_array($ch, [ CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($payload), CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 10, CURLOPT_HTTPHEADER => ['Content-Type: application/x-www-form-urlencoded'], ]); $body = curl_exec($ch); curl_close($ch); if ($body === false) { return false; } $json = json_decode($body, true); return !empty($json['success']); } }