getContent(); $sig = $r->header('X-Hub-Signature-256', ''); if ($secret && ! $this->validSignature($body, $sig, $secret)) { Log::warning('[webhook] firma inválida', ['sig' => substr((string) $sig, 0, 20)]); return response()->json(['ok' => false, 'error' => 'invalid signature'], 401); } $payload = json_decode($body, true) ?: []; $ref = $payload['ref'] ?? ''; $branch = str_starts_with($ref, 'refs/heads/') ? substr($ref, 11) : 'main'; if (! in_array($branch, ['main', 'master'], true)) { Log::info("[webhook] push a '$branch' ignorado"); return response()->json(['ok' => true, 'skipped' => 'branch != main'], 200); } $logFile = storage_path('logs/deploy-' . date('Ymd-His') . '.log'); $this->dispatchDeployInBackground($branch, $logFile); Log::info("[webhook] deploy branch=$branch lanzado log=$logFile"); return response()->json([ 'ok' => true, 'status' => 'deploy started', 'log' => basename($logFile), ], 202); } private function dispatchDeployInBackground(string $branch, string $logFile): void { $script = base_path('deploy-runner.sh'); if (! file_exists($script)) { // Modo fallback: registrar en log y salir Log::warning("[webhook] $script no existe, deploy no ejecutado"); return; } $cmd = sprintf( 'BRANCH=%s BRANCH=%s nohup bash %s > %s 2>&1 &', escapeshellarg($branch), escapeshellarg($branch), escapeshellarg($script), escapeshellarg($logFile) ); exec($cmd); } private function validSignature(string $body, string $sig, string $secret): bool { if (! str_starts_with($sig, 'sha256=')) return false; $expected = 'sha256=' . hash_hmac('sha256', $body, $secret); return hash_equals($expected, $sig); } }