philippurbschat.de/dinos/api_proxy.php
Philipp Urbschat f393beb7ff
feat: inkubator-standard & modul-autodiscovery
- Dynamische Modulerkennung via module.json in ModuleService.php
- Kaskadierender Env-Loader fuer zentrale API-Keys (GEMINI_API_KEY)
- Graceful Auth fuer alle Subprojekte (dinos, plants, storymachine, test)
- Wiederverwendbares Starter-Template in _template/
- test-Modul auf philippurbschat.de Dark-Design modernisiert
2026-09-13 00:23:16 +02:00

95 lines
2.7 KiB
PHP

<?php
// DATEI: dinos/api_proxy.php
$authFile = __DIR__ . '/../auth.php';
if (file_exists($authFile)) {
$current_project = basename(__DIR__);
require_once $authFile;
}
header('Content-Type: application/json');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
echo json_encode(['error' => 'Nur POST-Anfragen sind erlaubt.']);
exit;
}
// 1. API-Schlüssel sicher aus .env laden
$apiKey = '';
$envFiles = [__DIR__ . '/.env', __DIR__ . '/../home/.env'];
foreach ($envFiles as $envFile) {
if (file_exists($envFile)) {
foreach (file($envFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#') continue;
if (strpos($line, '=') !== false) {
list($k, $v) = explode('=', $line, 2);
if (trim($k) === 'GEMINI_API_KEY') {
$apiKey = trim(trim($v), '"\'');
break 2;
}
}
}
}
}
if (empty($apiKey)) {
http_response_code(500);
echo json_encode(['error' => 'API-Schlüssel nicht konfiguriert.']);
exit;
}
// 2. JSON-Daten empfangen
$json_input = file_get_contents('php://input');
$request_data = json_decode($json_input, true);
if (json_last_error() !== JSON_ERROR_NONE || !isset($request_data['apiUrl']) || !isset($request_data['payload'])) {
http_response_code(400);
echo json_encode(['error' => 'Ungültige Anfrage-Daten.']);
exit;
}
$apiUrl = $request_data['apiUrl'];
$payload = $request_data['payload'];
// 3. SSRF-Schutz: Nur generativelanguage.googleapis.com erlauben
$parsed = parse_url($apiUrl);
if (!isset($parsed['host']) || $parsed['host'] !== 'generativelanguage.googleapis.com') {
http_response_code(403);
echo json_encode(['error' => 'Ungültiges API-Ziel.']);
exit;
}
// 4. Ziel-URL mit API-Schlüssel zusammensetzen
$separator = (strpos($apiUrl, '?') !== false) ? '&' : '?';
$fullApiUrl = $apiUrl . $separator . 'key=' . $apiKey;
// 5. Anfrage mit cURL an Google API senden
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $fullApiUrl,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
],
CURLOPT_TIMEOUT => 90,
]);
$response_body = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if (curl_errno($ch)) {
http_response_code(500);
echo json_encode(['error' => 'Fehler bei Weiterleitung an Google: ' . curl_error($ch)]);
exit;
}
curl_close($ch);
http_response_code($http_code);
echo $response_body;
?>