ensureAllowedOrigin(); } protected function ensureAllowedOrigin(): void { $allowedHosts = ['coryd.dev', 'www.coryd.dev']; $origin = $_SERVER['HTTP_ORIGIN'] ?? ''; $referer = $_SERVER['HTTP_REFERER'] ?? ''; $hostAllowed = fn($url) => in_array(parse_url($url, PHP_URL_HOST), $allowedHosts, true); if (!$hostAllowed($origin) && !$hostAllowed($referer)) $this->sendErrorResponse("Forbidden — invalid origin", 403); $allowedSource = $origin ?: $referer; $scheme = parse_url($allowedSource, PHP_URL_SCHEME) ?? 'https'; $host = parse_url($allowedSource, PHP_URL_HOST); header("Access-Control-Allow-Origin: {$scheme}://{$host}"); header("Access-Control-Allow-Headers: Content-Type"); header("Access-Control-Allow-Methods: GET, POST"); } public function handleRequest(): void { $data = $_GET['data'] ?? null; $id = $_GET['id'] ?? null; $cacheDuration = intval($_GET['cacheDuration'] ?? 3600); if (!$data) $this->sendErrorResponse("Missing 'data' parameter", 400); $cacheKey = $this->buildCacheKey($data, $id); if ($this->cache) { $cached = $this->cache->get($cacheKey); if ($cached) { header('Content-Type: application/json'); echo $cached; exit(); } } $query = $id ? "id=eq.$id" : ""; try { $response = $this->fetchFromApi($data, $query); $markdownFields = $_GET['markdown'] ?? []; $markdownFields = is_array($markdownFields) ? $markdownFields : explode(',', $markdownFields); $markdownFields = array_map('trim', array_filter($markdownFields)); if (!empty($response) && !empty($markdownFields)) { foreach ($markdownFields as $field) { if (!empty($response[0][$field])) $response[0]["{$field}_html"] = parseMarkdown($response[0][$field]); } } $json = json_encode($response); if ($this->cache) { $this->cache->setex($cacheKey, $cacheDuration, $json); } header('Content-Type: application/json'); echo $json; } catch (\Exception $e) { $this->sendErrorResponse("PostgREST fetch failed: " . $e->getMessage(), 500); } } private function buildCacheKey(string $data, ?string $id): string { return "proxy_{$data}" . ($id ? "_{$id}" : ""); } } $handler = new ProxyHandler(); $handler->handleRequest();