'ok', 'message' => 'Forwarder deploy webhook. POST Gitea push events.', 'repo_dir' => $repoDir, 'git_head' => $gitHead, 'last_deploy' => $status, ], JSON_UNESCAPED_SLASHES); exit; } if ($_SERVER['REQUEST_METHOD'] !== 'POST') { http_response_code(405); echo json_encode(['error' => 'Method not allowed']); exit; } if ($secret === '') { http_response_code(500); echo json_encode(['error' => 'DEPLOY_WEBHOOK_SECRET not configured']); exit; } $rawBody = file_get_contents('php://input'); if ($rawBody === false || $rawBody === '') { http_response_code(400); echo json_encode(['error' => 'Empty body']); exit; } $signatureHeader = $_SERVER['HTTP_X_GITEA_SIGNATURE'] ?? ''; if ($signatureHeader === '' && !empty($_SERVER['HTTP_X_HUB_SIGNATURE_256'])) { $raw = trim((string) $_SERVER['HTTP_X_HUB_SIGNATURE_256']); $signatureHeader = str_starts_with($raw, 'sha256=') ? substr($raw, 7) : $raw; } if ($signatureHeader === '' || !hash_equals(hash_hmac('sha256', $rawBody, $secret), $signatureHeader)) { http_response_code(403); echo json_encode(['error' => 'Invalid signature']); exit; } $event = $_SERVER['HTTP_X_GITEA_EVENT'] ?? ''; if ($event !== 'push') { http_response_code(200); echo json_encode(['status' => 'ignored', 'reason' => 'Not a push event']); exit; } $payload = json_decode($rawBody, true); if (!is_array($payload)) { http_response_code(400); echo json_encode(['error' => 'Invalid JSON']); exit; } $repoFullName = strtolower((string) ($payload['repository']['full_name'] ?? '')); if ($repoFullName !== $allowedRepo) { http_response_code(403); echo json_encode(['error' => 'Repository not allowed', 'repo' => $repoFullName]); exit; } $ref = (string) ($payload['ref'] ?? ''); if ($ref !== 'refs/heads/' . $deployBranch) { http_response_code(200); echo json_encode(['status' => 'ignored', 'reason' => 'Branch mismatch', 'ref' => $ref]); exit; } $deployScript = $repoDir . '/deploy/deploy-pull.sh'; if (!is_file($deployScript)) { $deployScript = __DIR__ . '/deploy-pull.sh'; } if (!is_file($deployScript)) { http_response_code(500); echo json_encode(['error' => 'deploy-pull.sh missing']); exit; } $logFile = $repoDir . '/storage/deploy-logs/deploy-' . date('Ymd-His') . '.log'; @mkdir(dirname($logFile), 0750, true); $cmd = sprintf( 'nohup env FORWARDER_REPO_DIR=%s DEPLOY_BRANCH=%s bash %s >> %s 2>&1 &', escapeshellarg($repoDir), escapeshellarg($deployBranch), escapeshellarg($deployScript), escapeshellarg($logFile) ); exec($cmd); http_response_code(202); echo json_encode([ 'status' => 'queued', 'log' => $logFile, 'head' => $payload['after'] ?? null, ]);