normalizeClientVersion($raw); if ($version !== '') { return $version; } } return '1.0.17'; } private function presenceKey(int $userId): string { return 'gigax:site_presence:user:' . $userId; } private function connectionKey(int $userId): string { return 'gigax:fresh_connection:user:' . $userId; } private function touchSitePresence(int $userId): void { Cache::put($this->presenceKey($userId), now()->timestamp, now()->addMinutes(5)); } private function secondsSincePresence(int $userId): ?int { $stamp = Cache::get($this->presenceKey($userId)); return $stamp === null ? null : max(0, now()->timestamp - (int) $stamp); } private function secondsSinceHeartbeat(int $userId): ?int { $heartbeat = Cache::get('gigax:heartbeat:user:' . $userId); if (!is_array($heartbeat) || !isset($heartbeat['heartbeat_at'])) { return null; } return max(0, now()->timestamp - (int) $heartbeat['heartbeat_at']); } private function mandatoryUpdateResponse(string $received = '') { $required = $this->currentClientVersion(); return response()->json([ 'success' => false, 'update_required' => true, 'mandatory_update' => true, 'received_version' => $received, 'required_version' => $required, 'download_url' => self::DOWNLOAD_URL, 'message' => 'Atualização obrigatória do GIGAX Arena App.', ], 426, [ 'Cache-Control' => 'no-store, no-cache, must-revalidate', 'X-GIGAX-Required-Version' => $required, 'X-GIGAX-Download' => self::DOWNLOAD_URL, ]); } private function requireCurrentVersion(?string $received) { $required = $this->normalizeClientVersion($this->currentClientVersion()); $receivedRaw = trim((string) $received); $receivedVersion = $this->normalizeClientVersion($receivedRaw); /* * Alguns heartbeats do cliente podem chegar sem client_version no JSON, * porém com User-Agent oficial "GIGAX-Arena/x.y.z". * * Não devemos derrubar uma sessão já autenticada só porque o campo * client_version veio vazio. Nesse caso usamos a versão declarada no * User-Agent do cliente. */ if ($receivedVersion === '') { $userAgent = trim((string) request()->userAgent()); if (preg_match('/GIGAX-Arena\/(\d+\.\d+\.\d+)/i', $userAgent, $m)) { $receivedRaw = $m[1]; $receivedVersion = $this->normalizeClientVersion($m[1]); } } if ( $required !== '' && $receivedVersion !== '' && hash_equals($required, $receivedVersion) ) { return null; } Log::warning('GIGAX_VERSION_MISMATCH', [ 'received_raw' => $receivedRaw, 'received_normalized' => $receivedVersion, 'required' => $required, 'user_agent' => request()->userAgent(), 'route' => optional(request()->route())->uri(), 'ip' => request()->ip(), ]); return $this->mandatoryUpdateResponse( $receivedVersion !== '' ? $receivedVersion : $receivedRaw ); } private function removeUserFromWaitingQueues(int $userId): void { try { if (Schema::hasTable('mix_queue_players') && Schema::hasColumn('mix_queue_players', 'user_id')) { $q = DB::table('mix_queue_players')->where('user_id', $userId); if (Schema::hasColumn('mix_queue_players', 'left_at')) $q->whereNull('left_at')->update(['left_at' => now()]); else $q->delete(); } foreach (['mix_queue_main','mix_queue_secondary'] as $table) { if (Schema::hasTable($table) && Schema::hasColumn($table, 'user_id')) { DB::table($table)->where('user_id', $userId)->delete(); } } } catch (\Throwable $e) { Log::warning('GIGAX lease: falha removendo fila', ['user_id'=>$userId,'error'=>$e->getMessage()]); } } /** * Mantém os parâmetros SQLSRV corretos SEM abrir uma nova conexão em * cada heartbeat. O código antigo fazia purge/reconnect em toda requisição, * multiplicando conexões TCP e agravando SQLSTATE[08001]. * * A reconexão agora acontece somente quando uma operação realmente detecta * falha de transporte/conexão. */ private function refreshSqlsrvConnection(): void { $connection = (string) (config('database.default') ?: 'sqlsrv'); if ($connection !== 'sqlsrv') { return; } $host = getenv('DB_HOST') ?: config('database.connections.sqlsrv.host'); $port = getenv('DB_PORT') ?: config('database.connections.sqlsrv.port'); $database = getenv('DB_DATABASE') ?: config('database.connections.sqlsrv.database'); $username = getenv('DB_USERNAME') ?: config('database.connections.sqlsrv.username'); $password = getenv('DB_PASSWORD'); if ($password === false) { $password = config('database.connections.sqlsrv.password'); } Config::set('database.connections.sqlsrv.host', $host); Config::set('database.connections.sqlsrv.port', $port); Config::set('database.connections.sqlsrv.database', $database); Config::set('database.connections.sqlsrv.username', $username); Config::set('database.connections.sqlsrv.password', $password); DB::setDefaultConnection('sqlsrv'); } private function isSqlConnectionFailure(\Throwable $e): bool { $message = strtolower($e->getMessage()); $code = strtolower((string) $e->getCode()); return str_contains($message, 'sqlstate[08001]') || str_contains($message, 'tcp provider') || str_contains($message, 'connection refused') || str_contains($message, 'actively refused') || str_contains($message, 'wait operation timed out') || str_contains($message, 'communication link failure') || str_contains($message, 'server is unavailable') || str_contains($message, 'sqlstate[40001]') || str_contains($message, 'deadlock') || str_contains($message, 'deadlocked') || str_contains($message, 'deadlock victim') || str_contains($message, 'error 1205') || $code === '40001' || $code === '1205'; } /** * Executa a operação normalmente. Somente se a conexão estiver stale/indisponível * descarta o PDO e tenta UMA reconexão. Nunca entra em loop de reconnect. */ private function withSqlsrvRetry(callable $callback) { $this->refreshSqlsrvConnection(); $lastError = null; for ($attempt = 1; $attempt <= 3; $attempt++) { try { return $callback(); } catch (\Throwable $e) { $lastError = $e; if (!$this->isSqlConnectionFailure($e) || $attempt >= 3) { throw $e; } Log::warning('GIGAX_SQL_RETRY', [ 'attempt' => $attempt, 'code' => (string) $e->getCode(), 'error' => $e->getMessage(), ]); // Para falha de transporte, descarta o PDO. Em deadlock, apenas // aguarda um intervalo curto e repete a operação já revertida. $message = strtolower($e->getMessage()); $transportFailure = str_contains($message, 'sqlstate[08001]') || str_contains($message, 'tcp provider') || str_contains($message, 'connection refused') || str_contains($message, 'actively refused') || str_contains($message, 'wait operation timed out') || str_contains($message, 'communication link failure') || str_contains($message, 'server is unavailable'); if ($transportFailure) { DB::purge('sqlsrv'); DB::reconnect('sqlsrv'); } usleep(150000 * $attempt); } } throw $lastError ?? new \RuntimeException('Falha SQLSRV sem exceção detalhada.'); } private function deviceAuthCacheKey(string $deviceUuid): string { return 'gigax:device-auth:' . hash('sha256', $deviceUuid); } private function devicePersistCacheKey(string $deviceUuid): string { return 'gigax:device-persist:' . hash('sha256', $deviceUuid); } private function cacheDeviceAuth(object $device): void { Cache::put( $this->deviceAuthCacheKey((string) $device->device_uuid), [ 'id' => (int) $device->id, 'user_id' => (int) $device->user_id, 'device_uuid' => (string) $device->device_uuid, 'device_token_hash' => (string) $device->device_token_hash, 'network_hwid_hash' => (string) $device->network_hwid_hash, 'machine_hwid_hash' => (string) ($device->machine_hwid_hash ?? ''), 'status' => (string) ($device->status ?? 'active'), 'client_version' => (string) ($device->client_version ?? ''), ], now()->addMinutes(15) ); } private function cachedDeviceObject(string $deviceUuid): ?object { $cached = Cache::get($this->deviceAuthCacheKey($deviceUuid)); if (!is_array($cached) || empty($cached['id']) || empty($cached['user_id'])) { return null; } return (object) $cached; } private function sqlUnavailableResponse(\Throwable $e, string $operation) { $retryAfter = 3; $transient = $this->isSqlConnectionFailure($e); Log::error('GIGAX_SQL_EXACT_ERROR', [ 'operation' => $operation, 'transient' => $transient, 'class' => get_class($e), 'code' => (string) $e->getCode(), 'message' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine(), ]); return response()->json([ 'success' => false, 'temporary_unavailable' => $transient, 'operation' => $operation, 'message' => $transient ? 'Banco de dados temporariamente indisponível. Tente novamente.' : 'Falha interna ao iniciar a sessão do GIGAX Arena App.', 'retry_after' => $transient ? $retryAfter : 0, ], $transient ? 503 : 500, [ 'Retry-After' => (string) ($transient ? $retryAfter : 0), 'Cache-Control' => 'no-store', ]); } public function createPairToken(Request $request) { $this->refreshSqlsrvConnection(); $userId = (int) Auth::id(); if ($userId <= 0 && $request->hasSession()) { $userId = (int) $request->session()->get('user_id'); } abort_if($userId <= 0, 401, 'Login necessário.'); $plain = Str::random(64); $requiredVersion = $this->currentClientVersion(); // Nova conexão do JOGAR AGORA. $this->touchSitePresence($userId); Cache::forget($this->connectionKey($userId)); // 5 minutos: o mesmo token sobrevive ao download, troca do EXE e relaunch. try { $this->withSqlsrvRetry(function () use ($userId, $plain) { DB::table('gigax_arena_app_pair_tokens')->insert([ 'user_id' => $userId, 'token_hash' => hash('sha256', $plain), 'expires_at' => now()->addMinutes(5), 'created_at' => now(), 'updated_at' => now(), ]); }); } catch (\Throwable $e) { return $this->sqlUnavailableResponse($e, 'pair_token'); } return response()->json([ 'success' => true, 'protocol_url' => 'gigaxarena://auth?token=' . rawurlencode($plain) . '&mode=lite&background=1' . '&required_version=' . rawurlencode($requiredVersion), 'expires_in' => 300, 'required_version' => $requiredVersion, 'mandatory_update' => true, 'download_url' => self::DOWNLOAD_URL, ], 200, [ 'Cache-Control' => 'no-store, no-cache, must-revalidate', ]); } public function exchange(Request $request) { $this->refreshSqlsrvConnection(); $data = $request->validate([ 'pair_token' => ['required', 'string', 'min:32', 'max:200'], 'device_uuid' => ['required', 'string', 'max:64'], 'machine_hwid_hash' => ['required', 'string', 'max:128'], 'network_hwid_hash' => ['required', 'string', 'max:128'], 'computer_name' => ['nullable', 'string', 'max:120'], 'windows_user' => ['nullable', 'string', 'max:120'], 'os_version' => ['nullable', 'string', 'max:255'], 'client_version' => ['nullable', 'string', 'max:40'], ]); if ($response = $this->requireCurrentVersion($data['client_version'] ?? null)) return $response; try { return $this->withSqlsrvRetry(function () use ($data, $request) { return DB::transaction(function () use ($data, $request) { $pair = DB::table('gigax_arena_app_pair_tokens') ->where('token_hash', hash('sha256', $data['pair_token'])) ->whereNull('consumed_at') ->where('expires_at', '>', now()) ->lockForUpdate() ->first(); if (!$pair) { return response()->json([ 'success' => false, 'message' => 'Token inválido ou expirado.', ], 401); } $existingNetwork = DB::table('gigax_arena_app_devices') ->where('network_hwid_hash', $data['network_hwid_hash']) ->first(); if ($existingNetwork && $existingNetwork->status === 'banned') { return response()->json([ 'success' => false, 'message' => 'Dispositivo ou HWID de rede bloqueado.', ], 403); } // O banco permite o mesmo network_hwid_hash para usuarios diferentes // (a unicidade existente e por user_id + network_hwid_hash). Um vinculo // ativo anterior nao deve bloquear um login autenticado por pair_token. // HWIDs/dispositivos explicitamente banidos continuam bloqueados acima. if ($existingNetwork && (int) $existingNetwork->user_id !== (int) $pair->user_id) { Log::notice('GIGAX_EXCHANGE_HWID_REUSED', [ 'pair_user_id' => (int) $pair->user_id, 'existing_user_id' => (int) $existingNetwork->user_id, 'network_hwid_hash' => (string) $data['network_hwid_hash'], 'machine_hwid_hash' => (string) $data['machine_hwid_hash'], 'device_uuid' => (string) $data['device_uuid'], 'existing_device_id' => (int) $existingNetwork->id, 'existing_device_uuid' => (string) $existingNetwork->device_uuid, ]); } $plainDeviceToken = Str::random(96); $devicePayload = [ 'user_id' => (int) $pair->user_id, 'machine_hwid_hash' => $data['machine_hwid_hash'], 'network_hwid_hash' => $data['network_hwid_hash'], 'device_token_hash' => hash('sha256', $plainDeviceToken), 'computer_name' => $data['computer_name'] ?? null, 'windows_user' => $data['windows_user'] ?? null, 'os_version' => $data['os_version'] ?? null, 'client_version' => $data['client_version'] ?? null, 'status' => 'active', 'is_online' => true, 'registered_at' => now(), 'last_seen_at' => now(), 'updated_at' => now(), ]; DB::table('gigax_arena_app_devices')->updateOrInsert( ['device_uuid' => $data['device_uuid']], $devicePayload + ['created_at' => now()] ); $device = DB::table('gigax_arena_app_devices') ->where('device_uuid', $data['device_uuid']) ->lockForUpdate() ->first(); if (!$device) { throw new \RuntimeException('O dispositivo não foi localizado após o cadastro.'); } // Cache curto para que os heartbeats seguintes não façam SELECT no // SQL Server a cada chamada. $this->cacheDeviceAuth($device); $plainSessionToken = Str::random(96); $plainRefreshToken = Str::random(96); /* * gigax_app_sessions.device_id possui FK para gigax_app_devices.id. * O cadastro principal deste controller fica em gigax_arena_app_devices, * portanto sincronizamos o dispositivo na tabela pai correta antes de * criar a sessão. Isso elimina o erro FK_gigax_session_device. */ $sessionDeviceId = $this->syncSessionDeviceRecord($device); $this->syncAppSession( (int) $pair->user_id, $sessionDeviceId, $plainSessionToken, $plainRefreshToken ); $this->syncAntiCheatPresence( (int) $pair->user_id, (string) $data['machine_hwid_hash'] ); DB::table('gigax_arena_app_pair_tokens') ->where('id', $pair->id) ->update([ 'consumed_at' => now(), 'updated_at' => now(), ]); Log::info('GIGAX Arena App: dispositivo registrado e sessão criada', [ 'user_id' => $pair->user_id, 'device_id' => $device->id, 'device_uuid' => $data['device_uuid'], 'network_hwid_hash' => $data['network_hwid_hash'], ]); Cache::put($this->connectionKey((int) $pair->user_id), [ 'device_uuid' => (string) $data['device_uuid'], 'version' => (string) ($data['client_version'] ?? ''), 'connected_at' => now()->toIso8601String(), ], now()->addHours(12)); $this->touchSitePresence((int) $pair->user_id); // /api/gigax-app/exchange roda sem middleware de sessao web. // Nao acessar $request->session() aqui: o cliente autentica por pair-token. return response()->json([ 'success' => true, 'device_token' => $plainDeviceToken, 'session_token' => $plainSessionToken, 'refresh_token' => $plainRefreshToken, 'device_id' => (string) $device->id, 'user_id' => (string) $pair->user_id, 'message' => 'Máquina registrada e sessão iniciada com sucesso.', ]); }, 3); }); } catch (\Throwable $e) { return $this->sqlUnavailableResponse($e, 'exchange'); } } /** * GIGAX V159: * quando a fila remove o jogador por AWAY >= 200s, a sessao fica * is_online=0 e expires_at vencido. Resume/heartbeat nao podem * reativar silenciosamente; e necessario novo login/exchange. */ private function queueAwayRequiresRelogin(int $userId, string $deviceUuid): bool { try { if ( !Schema::hasTable('gigax_app_sessions') || !Schema::hasTable('gigax_app_devices') || !Schema::hasColumn('gigax_app_sessions', 'user_id') || !Schema::hasColumn('gigax_app_sessions', 'device_id') || !Schema::hasColumn('gigax_app_sessions', 'is_online') || !Schema::hasColumn('gigax_app_sessions', 'expires_at') || !Schema::hasColumn('gigax_app_devices', 'device_uuid') ) { return false; } // O ID de gigax_arena_app_devices NAO e o ID da FK da sessao. // Resolve pelo UUID na tabela pai, sem alterar o dispositivo. return DB::table('gigax_app_sessions as s') ->join('gigax_app_devices as d', 'd.id', '=', 's.device_id') ->where('s.user_id', $userId) ->where('d.device_uuid', $deviceUuid) ->where('s.is_online', false) ->where('s.expires_at', '<=', now()) ->exists(); } catch (\Throwable $e) { Log::warning('GIGAX V159: falha ao consultar reautenticacao obrigatoria', [ 'user_id' => $userId, 'device_uuid_hash' => hash('sha256', $deviceUuid), 'error' => $e->getMessage(), ]); // Nao permitir reativacao silenciosa se a verificacao falhar. throw $e; } } public function resume(Request $request) { $this->refreshSqlsrvConnection(); $data = $request->validate([ 'device_uuid' => ['required', 'string', 'max:64'], 'device_token' => ['required', 'string', 'max:200'], 'machine_hwid_hash' => ['required', 'string', 'max:128'], 'network_hwid_hash' => ['required', 'string', 'max:128'], 'client_version' => ['nullable', 'string', 'max:40'], ]); if ($response = $this->requireCurrentVersion($data['client_version'] ?? null)) return $response; try { $device = $this->withSqlsrvRetry(function () use ($data) { return DB::table('gigax_arena_app_devices') ->where('device_uuid', $data['device_uuid']) ->first(); }); } catch (\Throwable $e) { return $this->sqlUnavailableResponse($e, 'resume'); } if ( !$device || !hash_equals( (string) $device->device_token_hash, hash('sha256', $data['device_token']) ) ) { return response()->json([ 'success' => false, 'message' => 'Credencial do dispositivo inválida.', ], 401); } if ($device->status === 'banned') { return response()->json([ 'success' => false, 'message' => 'Dispositivo bloqueado: ' . ($device->ban_reason ?: 'sem motivo informado'), ], 403); } if (!hash_equals((string) $device->network_hwid_hash, $data['network_hwid_hash'])) { return response()->json([ 'success' => false, 'message' => 'HWID de rede divergente. Revalidação administrativa necessária.', ], 403); } $this->cacheDeviceAuth($device); try { $resumeResponse = $this->withSqlsrvRetry(function () use ($data, $device) { if ($this->queueAwayRequiresRelogin((int) $device->user_id, (string) $device->device_uuid)) { return response()->json([ 'success' => false, 'reauth_required' => true, 'reason' => 'QUEUE_AWAY_200S', 'message' => 'Sessao encerrada por ausencia na fila por 200 segundos. Faca login novamente no GIGAX Anti-Cheat.', ], 401); } DB::transaction(function () use ($data, $device) { DB::table('gigax_arena_app_devices') ->where('id', $device->id) ->update([ 'machine_hwid_hash' => $data['machine_hwid_hash'], 'client_version' => $data['client_version'] ?? $device->client_version, 'is_online' => true, 'last_seen_at' => now(), 'updated_at' => now(), ]); $sessionDeviceId = $this->syncSessionDeviceRecord($device); $this->touchExistingAppSession((int) $device->user_id, $sessionDeviceId); $this->syncAntiCheatPresence( (int) $device->user_id, (string) $data['machine_hwid_hash'] ); }, 3); }); // O 401 criado no callback precisa ser devolvido ao cliente. if ($resumeResponse !== null) { Cache::forget('gigax:heartbeat:user:' . (int) $device->user_id); Cache::forget($this->connectionKey((int) $device->user_id)); return $resumeResponse; } } catch (\Throwable $e) { return $this->sqlUnavailableResponse($e, 'resume_write'); } return response()->json([ 'success' => true, 'user_id' => (string) $device->user_id, 'status' => 'online', 'ac_online' => true, ]); } public function heartbeat(Request $request) { $data = $request->validate([ 'device_uuid' => ['required', 'string', 'max:64'], 'device_token' => ['required', 'string', 'max:200'], 'network_hwid_hash' => ['required', 'string', 'max:128'], 'match_id' => ['nullable', 'string', 'max:120'], 'match_active' => ['nullable'], 'risk_current' => ['nullable', 'integer'], 'risk_peak' => ['nullable', 'integer'], 'macro_peak' => ['nullable', 'integer'], 'macro_last_reported' => ['nullable', 'integer'], 'client_version' => ['nullable', 'string', 'max:40'], ]); if ($response = $this->requireCurrentVersion($data['client_version'] ?? null)) { return $response; } $device = $this->cachedDeviceObject($data['device_uuid']); // Somente o primeiro heartbeat (ou cache expirado) consulta o dispositivo. if (!$device) { try { $device = $this->withSqlsrvRetry(function () use ($data) { return DB::table('gigax_arena_app_devices') ->where('device_uuid', $data['device_uuid']) ->first(); }); } catch (\Throwable $e) { return $this->sqlUnavailableResponse($e, 'heartbeat_auth'); } if ($device) { $this->cacheDeviceAuth($device); } } if ( !$device || !hash_equals( (string) $device->device_token_hash, hash('sha256', $data['device_token']) ) ) { return response()->json([ 'success' => false, 'message' => 'Credencial do dispositivo inválida.', ], 401); } if ( (string) $device->status === 'banned' || !hash_equals( (string) $device->network_hwid_hash, (string) $data['network_hwid_hash'] ) ) { return response()->json([ 'success' => false, 'banned' => true, 'message' => 'Dispositivo bloqueado ou HWID de rede divergente.', ], 403); } // Presença imediata em cache: o site pode enxergar o AC vivo sem exigir // escrita SQL em cada heartbeat. $heartbeatVersion = $this->normalizeClientVersion( (string) ($data['client_version'] ?? '') ); if ($heartbeatVersion === '') { $userAgent = trim((string) $request->userAgent()); if (preg_match('/GIGAX-Arena\/(\d+\.\d+\.\d+)/i', $userAgent, $m)) { $heartbeatVersion = $this->normalizeClientVersion($m[1]); } } /* * HOT PATH V1 * * O cache do servidor e baseado em arquivo. Cache::add/forget usa lock * exclusivo e, no diagnostico real, foi a operacao de cache mais cara. * Reaproveitamos o proprio registro de heartbeat para controlar: * - persistencia SQL (maximo 1x/60s por dispositivo); * - backoff de 10s quando o SQL falha; * - renovacao da conexao fresca (maximo 1x/60s). * * Token, HWID, banimento e versao continuam validados em TODO heartbeat. */ $now = now(); $nowTs = $now->timestamp; $heartbeatCacheKey = 'gigax:heartbeat:user:' . (int) $device->user_id; $previousHeartbeat = Cache::get($heartbeatCacheKey); $previousHeartbeat = is_array($previousHeartbeat) ? $previousHeartbeat : []; $lastDbPersistedAt = (int) ($previousHeartbeat['db_persisted_at'] ?? 0); $lastDbPersistAttemptAt = (int) ($previousHeartbeat['db_persist_attempt_at'] ?? 0); $lastConnectionRefreshAt = (int) ($previousHeartbeat['connection_refreshed_at'] ?? 0); $dbPersistDue = $lastDbPersistedAt <= 0 || ($nowTs - $lastDbPersistedAt) >= 60; $dbRetryAllowed = $lastDbPersistAttemptAt <= 0 || ($nowTs - $lastDbPersistAttemptAt) >= 10; $shouldPersist = $dbPersistDue && $dbRetryAllowed; $refreshConnection = $lastConnectionRefreshAt <= 0 || ($nowTs - $lastConnectionRefreshAt) >= 60; $heartbeatPayload = [ 'device_uuid' => (string) $device->device_uuid, 'heartbeat_at' => $nowTs, 'client_version' => $heartbeatVersion, 'risk_current' => (int) ($data['risk_current'] ?? 0), 'risk_peak' => (int) ($data['risk_peak'] ?? 0), 'db_persisted_at' => $lastDbPersistedAt, 'db_persist_attempt_at' => $shouldPersist ? $nowTs : $lastDbPersistAttemptAt, 'connection_refreshed_at' => $refreshConnection ? $nowTs : $lastConnectionRefreshAt, ]; Cache::put($heartbeatCacheKey, $heartbeatPayload, $now->copy()->addMinutes(5)); // A fila usa heartbeat fresco como fonte principal. Esta chave continua // sendo renovada para compatibilidade, mas nao precisa gerar I/O a cada pulso. if ($refreshConnection) { Cache::put( $this->connectionKey((int) $device->user_id), [ 'device_uuid' => (string) $device->device_uuid, 'version' => $heartbeatVersion !== '' ? $heartbeatVersion : $this->currentClientVersion(), 'connected_at' => $now->toIso8601String(), ], $now->copy()->addHours(12) ); } $persisted = false; $dbDegraded = false; // Persistencia pesada continua em 1x/60s. Se o SQL estiver degradado, // o heartbeat autenticado permanece vivo em cache e aguarda 10s antes // de uma nova tentativa, evitando tempestade de conexoes/retries. if ($shouldPersist) { $reauthRequired = false; try { $this->withSqlsrvRetry(function () use ($device, $heartbeatVersion, &$reauthRequired) { $reauthRequired = $this->queueAwayRequiresRelogin( (int) $device->user_id, (string) $device->device_uuid ); if ($reauthRequired) { return; } DB::transaction(function () use ($device, $heartbeatVersion) { // A versao ja foi validada por requireCurrentVersion() e // as credenciais/HWID foram verificados neste heartbeat. // Propaga a versao real tanto para o registro principal // quanto para a tabela de dispositivo vinculada a sessao. $authenticatedDevice = clone $device; $authenticatedDevice->client_version = $heartbeatVersion; DB::table('gigax_arena_app_devices') ->where('id', (int) $device->id) ->update([ 'client_version' => $heartbeatVersion, 'is_online' => true, 'last_seen_at' => now(), 'updated_at' => now(), ]); $sessionDeviceId = $this->syncSessionDeviceRecord($authenticatedDevice); $this->touchExistingAppSession( (int) $device->user_id, $sessionDeviceId ); $this->syncAntiCheatPresence( (int) $device->user_id, (string) ( $device->machine_hwid_hash ?: $device->device_uuid ) ); }); }); if ($reauthRequired) { // Evento raro e de seguranca: invalida presenca/fresh connection // para impedir que a fila reutilize um heartbeat anterior. Cache::forget($heartbeatCacheKey); Cache::forget($this->connectionKey((int) $device->user_id)); return response()->json([ 'success' => false, 'reauth_required' => true, 'reason' => 'QUEUE_AWAY_200S', 'message' => 'Sessao encerrada por ausencia na fila por 200 segundos. Faca login novamente no GIGAX Anti-Cheat.', ], 401); } $persisted = true; $heartbeatPayload['db_persisted_at'] = $nowTs; Cache::put($heartbeatCacheKey, $heartbeatPayload, $now->copy()->addMinutes(5)); } catch (\Throwable $e) { $dbDegraded = true; Log::warning('GIGAX_HEARTBEAT_SQL_DEGRADED', [ 'user_id' => (int) $device->user_id, 'device_uuid' => (string) $device->device_uuid, 'error' => $e->getMessage(), ]); } } $matchId = isset($data['match_id']) && is_numeric($data['match_id']) ? (int) $data['match_id'] : null; // O Match Guard so precisa resolver incidente quando existe uma partida // identificada. Ele roda junto da persistencia de 60s, em vez de abrir // SQL em todo heartbeat. Isso preserva o bloqueio de seguranca e reduz // drasticamente consultas sem incidente. if ($persisted && $matchId !== null && $matchId > 0) { try { app(AcMatchGuardService::class) ->resolveForHeartbeat((int) $device->user_id, $matchId); } catch (\Throwable $e) { if (!$this->isSqlConnectionFailure($e)) { throw $e; } $dbDegraded = true; Log::warning('GIGAX_MATCH_GUARD_SQL_DEGRADED', [ 'user_id' => (int) $device->user_id, 'match_id' => $matchId, 'error' => $e->getMessage(), ]); } } return response()->json([ 'success' => true, 'user_id' => (string) $device->user_id, 'match_guard' => 'online', 'ac_online' => true, 'heartbeat_at' => now()->toIso8601String(), 'db_persisted' => $persisted, 'degraded' => $dbDegraded, 'persist_interval_seconds' => 60, ]); } public function clientManifest() { $version = $this->currentClientVersion(); return response()->json([ 'success' => true, 'app' => 'GIGAX Arena App', 'required_version' => $version, 'mandatory_update' => true, 'download_url' => self::DOWNLOAD_URL . '?v=' . rawurlencode($version), ], 200, [ 'Cache-Control' => 'no-store, no-cache, must-revalidate', ]); } public function sitePresence(Request $request) { $userId = (int) Auth::id(); if ($userId <= 0 && $request->hasSession()) { $userId = (int) $request->session()->get('user_id'); } abort_if($userId <= 0, 401, 'Login necessário.'); $this->touchSitePresence($userId); return response()->json([ 'success' => true, 'site_active' => true, 'timeout_seconds' => self::SITE_TIMEOUT_SECONDS, 'required_version' => $this->currentClientVersion(), ]); } public function siteLease(Request $request) { $data = $request->validate([ 'device_uuid' => ['required','string','max:64'], 'device_token' => ['required','string','max:200'], 'client_version' => ['required','string','max:40'], ]); if ($response = $this->requireCurrentVersion($data['client_version'] ?? null)) return $response; $device = DB::table('gigax_arena_app_devices')->where('device_uuid',$data['device_uuid'])->first(); if (!$device || !hash_equals((string)$device->device_token_hash, hash('sha256',$data['device_token']))) { return response()->json(['success'=>false,'site_active'=>false,'message'=>'Credencial inválida.'],401); } $userId = (int) $device->user_id; $age = $this->secondsSincePresence($userId); $heartbeatAge = $this->secondsSinceHeartbeat($userId); $heartbeatActive = $heartbeatAge !== null && $heartbeatAge <= self::HEARTBEAT_TIMEOUT_SECONDS; $connection = Cache::get($this->connectionKey($userId)); $connectionAge = PHP_INT_MAX; if (is_array($connection) && !empty($connection['connected_at'])) { try { $connectionAge = max( 0, now()->timestamp - \Illuminate\Support\Carbon::parse( (string) $connection['connected_at'] )->timestamp ); } catch (\Throwable $e) { $connectionAge = PHP_INT_MAX; } } // Fila sem limite enquanto o AC responde. Após o exchange, há até 180s // para o primeiro heartbeat. Se o cliente cair sem conseguir avisar o servidor, // a remoção automática da fila só acontece após 180s sem heartbeat. $startupGrace = $connectionAge <= self::HEARTBEAT_TIMEOUT_SECONDS; $active = $heartbeatActive || $startupGrace; $left = $heartbeatActive ? max(0, self::HEARTBEAT_TIMEOUT_SECONDS - (int) $heartbeatAge) : ($startupGrace ? max(0, self::HEARTBEAT_TIMEOUT_SECONDS - (int) $connectionAge) : 0); if (!$active) { Cache::forget($this->connectionKey($userId)); $this->removeUserFromWaitingQueues($userId); DB::table('gigax_arena_app_devices')->where('id',$device->id)->update([ 'is_online'=>false, 'updated_at'=>now(), ]); if (Schema::hasTable('gx_anticheat_status')) { $u=['updated_at'=>now()]; if (Schema::hasColumn('gx_anticheat_status','ac_online')) $u['ac_online']=false; if (Schema::hasColumn('gx_anticheat_status','anti_cheat_online')) $u['anti_cheat_online']=false; if (Schema::hasColumn('gx_anticheat_status','online')) $u['online']=false; if (Schema::hasColumn('gx_anticheat_status','ready')) $u['ready']=false; if (Schema::hasColumn('gx_anticheat_status','is_ready')) $u['is_ready']=false; if (Schema::hasColumn('gx_anticheat_status','status')) $u['status']='offline'; if (Schema::hasColumn('gx_anticheat_status','connection_status')) $u['connection_status']='offline'; DB::table('gx_anticheat_status')->where('user_id',$userId)->update($u); } } return response()->json([ 'success'=>true, 'site_active'=>$active, 'seconds_left'=>$left, 'site_presence_age'=>$age, 'heartbeat_age'=>$heartbeatAge, 'heartbeat_active'=>$heartbeatActive, 'timeout_seconds'=>self::SITE_TIMEOUT_SECONDS, 'reconnect_required'=>!$active, 'required_version'=>$this->currentClientVersion(), ]); } /** * Garante que o dispositivo usado pelo cliente moderno também exista em * gigax_app_devices, que é a tabela referenciada pela FK de * gigax_app_sessions.device_id. * * Retorna sempre o ID válido da tabela pai de gigax_app_sessions. */ private function syncSessionDeviceRecord(object $arenaDevice): int { if (!Schema::hasTable('gigax_app_devices')) { throw new \RuntimeException( 'A tabela gigax_app_devices não existe, mas é obrigatória para gigax_app_sessions.' ); } $columns = Schema::getColumnListing('gigax_app_devices'); $has = static fn (string $column): bool => in_array($column, $columns, true); $deviceUuid = trim((string) ($arenaDevice->device_uuid ?? '')); if ($deviceUuid === '') { throw new \RuntimeException('device_uuid vazio ao sincronizar gigax_app_devices.'); } $existing = DB::table('gigax_app_devices') ->where('device_uuid', $deviceUuid) ->lockForUpdate() ->first(); $payload = []; $candidateValues = [ 'user_id' => (int) ($arenaDevice->user_id ?? 0), 'machine_hwid_hash' => (string) ($arenaDevice->machine_hwid_hash ?? ''), 'network_hwid_hash' => (string) ($arenaDevice->network_hwid_hash ?? ''), 'device_token_hash' => (string) ($arenaDevice->device_token_hash ?? ''), 'computer_name' => $arenaDevice->computer_name ?? null, 'windows_user' => $arenaDevice->windows_user ?? null, 'os_version' => $arenaDevice->os_version ?? null, 'client_version' => $arenaDevice->client_version ?? null, 'status' => (string) ($arenaDevice->status ?? 'active'), 'is_online' => true, 'last_seen' => now(), 'last_seen_at' => now(), 'updated_at' => now(), ]; foreach ($candidateValues as $column => $value) { if ($has($column)) { $payload[$column] = $value; } } if ($existing) { // O UUID pode ter sido legitimamente vinculado a outra conta // em um novo exchange. Nao deixe tokens de sessoes anteriores // validos para o dispositivo agora associado a outro usuario. // Este metodo e chamado dentro da transacao de exchange/resume/heartbeat. $previousOwnerId = (int) ($existing->user_id ?? 0); $currentOwnerId = (int) ($arenaDevice->user_id ?? 0); if ($currentOwnerId <= 0) { throw new \RuntimeException('Usuario do dispositivo invalido ao sincronizar sessao.'); } if ($previousOwnerId !== $currentOwnerId) { if ( !Schema::hasTable('gigax_app_sessions') || !Schema::hasColumn('gigax_app_sessions', 'device_id') || !Schema::hasColumn('gigax_app_sessions', 'user_id') || !Schema::hasColumn('gigax_app_sessions', 'is_online') || !Schema::hasColumn('gigax_app_sessions', 'expires_at') ) { throw new \RuntimeException('Nao foi possivel validar sessoes antigas do dispositivo.'); } $revoked = DB::table('gigax_app_sessions') ->where('device_id', (int) $existing->id) ->where('user_id', '<>', $currentOwnerId) ->update([ 'is_online' => false, 'expires_at' => now()->subSecond(), ]); Log::notice('GIGAX_APP_DEVICE_OWNER_CHANGED_SESSIONS_REVOKED', [ 'device_id' => (int) $existing->id, 'revoked_sessions' => (int) $revoked, ]); } if ($payload !== []) { DB::table('gigax_app_devices') ->where('id', $existing->id) ->update($payload); } return (int) $existing->id; } $insert = ['device_uuid' => $deviceUuid] + $payload; if ($has('created_at')) { $insert['created_at'] = now(); } if ($has('registered_at')) { $insert['registered_at'] = now(); } $id = DB::table('gigax_app_devices')->insertGetId($insert); if ($id <= 0) { throw new \RuntimeException('Não foi possível criar o dispositivo em gigax_app_devices.'); } return (int) $id; } private function syncAppSession( int $userId, int $deviceId, string $plainSessionToken, string $plainRefreshToken ): void { if (!Schema::hasTable('gigax_app_sessions')) { Log::warning('gigax_app_sessions não existe; sessão do aplicativo não foi registrada.', [ 'user_id' => $userId, 'device_id' => $deviceId, ]); return; } if ( !Schema::hasTable('gigax_app_devices') || !DB::table('gigax_app_devices')->where('id', $deviceId)->exists() ) { throw new \RuntimeException( 'Dispositivo pai inválido para gigax_app_sessions: ' . $deviceId ); } $existing = DB::table('gigax_app_sessions') ->where('user_id', $userId) ->where('device_id', $deviceId) ->lockForUpdate() ->first(); $payload = [ 'refresh_token' => hash('sha256', $plainRefreshToken), 'session_token' => hash('sha256', $plainSessionToken), 'expires_at' => now()->addDays(30), 'last_heartbeat' => now(), 'is_online' => true, ]; if ($existing) { DB::table('gigax_app_sessions') ->where('id', $existing->id) ->update($payload); return; } DB::table('gigax_app_sessions')->insert($payload + [ 'user_id' => $userId, 'device_id' => $deviceId, 'created_at' => now(), ]); } private function touchExistingAppSession(int $userId, int $deviceId): void { if (!Schema::hasTable('gigax_app_sessions')) { return; } if ( !Schema::hasTable('gigax_app_devices') || !DB::table('gigax_app_devices')->where('id', $deviceId)->exists() ) { Log::warning('Heartbeat ignorado: dispositivo pai ausente em gigax_app_devices.', [ 'user_id' => $userId, 'device_id' => $deviceId, ]); return; } $updated = DB::table('gigax_app_sessions') ->where('user_id', $userId) ->where('device_id', $deviceId) ->update([ 'last_heartbeat' => now(), 'is_online' => true, ]); /* * Compatibilidade com dispositivos registrados antes da criação * automática da sessão. Cria uma sessão técnica sem depender do cliente. */ if ($updated === 0) { DB::table('gigax_app_sessions')->insert([ 'user_id' => $userId, 'device_id' => $deviceId, 'refresh_token' => hash('sha256', Str::random(96)), 'session_token' => hash('sha256', Str::random(96)), 'created_at' => now(), 'expires_at' => now()->addDays(30), 'last_heartbeat' => now(), 'is_online' => true, ]); } } private function syncAntiCheatPresence(int $userId, string $hwid): void { if (!Schema::hasTable('gx_anticheat_status')) { Log::warning('gx_anticheat_status não existe; heartbeat do AC não foi registrado.', [ 'user_id' => $userId, ]); return; } $existing = DB::table('gx_anticheat_status') ->where('user_id', $userId) ->lockForUpdate() ->first(); $payload = [ 'hwid' => $hwid, 'ac_online' => true, 'online' => true, 'heartbeat_at' => now(), 'ac_last_seen_at' => now(), 'last_seen_at' => now(), 'updated_at' => now(), ]; if (Schema::hasColumn('gx_anticheat_status', 'ready')) { $payload['ready'] = true; } if (Schema::hasColumn('gx_anticheat_status', 'is_ready')) { $payload['is_ready'] = true; } if (Schema::hasColumn('gx_anticheat_status', 'anti_cheat_online')) { $payload['anti_cheat_online'] = true; } if (Schema::hasColumn('gx_anticheat_status', 'status')) { $payload['status'] = 'online'; } if (Schema::hasColumn('gx_anticheat_status', 'connection_status')) { $payload['connection_status'] = 'online'; } if ($existing) { DB::table('gx_anticheat_status') ->where('user_id', $userId) ->update($payload + [ 'heartbeat' => DB::raw('ISNULL(heartbeat, 0) + 1'), ]); return; } DB::table('gx_anticheat_status')->insert($payload + [ 'user_id' => $userId, 'heartbeat' => 1, 'created_at' => now(), ]); } }