'https://auth.timfalken.com', 'base_url' => 'https://projects.timfalken.com/allianties', 'client_id' => 'projects.timfalken.com', 'client_secret' => '', ]; PHP; if (file_put_contents($path, $template) !== strlen($template)) { throw new RuntimeException('data/config.php kon niet worden gemaakt.'); } } $values = require $path; if (!is_array($values)) { throw new RuntimeException('data/config.php moet een array teruggeven.'); } } finally { flock($lock, LOCK_UN); fclose($lock); } foreach ([ 'auth_url' => 'ALLIANTIES_AUTH_URL', 'base_url' => 'ALLIANTIES_BASE_URL', 'client_id' => 'ALLIANTIES_CLIENT_ID', 'client_secret' => 'ALLIANTIES_CLIENT_SECRET', ] as $key => $env) { if (($values[$key] ?? '') === '') { $values[$key] = getenv($env) ?: ''; } } if (($values['auth_url'] ?? '') === '') { $values['auth_url'] = ALLIANTIES_DEFAULT_AUTH; } if (($values['client_id'] ?? '') === '') { $values['client_id'] = ALLIANTIES_DEFAULT_CLIENT_ID; } return $values; } function authConfigured(): bool { $c = config(); return ($c['client_secret'] ?? '') !== '' && ($c['client_id'] ?? '') !== '' && ($c['base_url'] ?? '') !== ''; } function baseUrl(): string { if (localDev()) { $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/'); if ($dir === '/' || $dir === '.') { $dir = ''; } return 'http://' . $_SERVER['HTTP_HOST'] . $dir; } $base = rtrim((string) (config()['base_url'] ?? ''), '/'); if (!str_starts_with($base, 'https://')) { throw new RuntimeException( "Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie " . '(https://projects.timfalken.com/allianties), of zet ALLIANTIES_BASE_URL.' ); } return $base; } function authUrl(): string { $url = rtrim((string) (config()['auth_url'] ?? ALLIANTIES_DEFAULT_AUTH), '/'); return $url !== '' ? $url : ALLIANTIES_DEFAULT_AUTH; } function authRequest(string $path, ?array $form = null, ?string $token = null): array { $ch = curl_init(authUrl() . $path); $headers = ['Accept: application/json', 'User-Agent: Allianties/1.0']; if ($token) { $headers[] = 'Authorization: Bearer ' . $token; } curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => $headers, ]); if ($form !== null) { curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]); } $body = curl_exec($ch); $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $err = curl_error($ch); curl_close($ch); $data = is_string($body) ? json_decode($body, true) : null; if ($status !== 200 || !is_array($data)) { $hint = $err !== '' ? ' (' . $err . ')' : ''; throw new RuntimeException( 'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint ); } return $data; } /** @return array{0:string,1:string,2:?string} id, name, avatar */ function authIdentity(array $profile): array { if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) { throw new RuntimeException('Het profiel mist een id of gebruikersnaam.'); } $raw = $profile['id']; $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw)); if (!$numeric || (int) $raw < 1) { throw new RuntimeException('Ongeldig account-id.'); } $id = (int) $raw; $avatar = null; foreach (['avatar_url', 'avatar', 'picture', 'icon', 'image'] as $k) { if (isset($profile[$k]) && is_string($profile[$k]) && str_starts_with($profile[$k], 'https://')) { $avatar = $profile[$k]; break; } } if ($avatar === null) { $avatar = authUrl() . '/avatar/' . $id; } return ['auth:' . $id, $profile['username'], $avatar]; } function isValidUserId(string $id): bool { if (preg_match('/^auth:[1-9][0-9]{0,17}$/', $id)) { return true; } return (bool) preg_match('/^local:test_user_([1-9]|1[0-6])$/', $id); } function loginUser(string $id, string $name, ?string $avatar = null): void { if (!isValidUserId($id)) { throw new RuntimeException('Ongeldig account.'); } $name = trim($name); if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) { throw new RuntimeException('Ongeldige gebruikersnaam.'); } session_regenerate_id(true); $_SESSION['user'] = $id; $_SESSION['name'] = $name; $_SESSION['avatar'] = $avatar; $_SESSION['csrf'] = bin2hex(random_bytes(24)); $_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL; } function logoutUser(): void { $_SESSION = []; if (ini_get('session.use_cookies')) { $p = session_get_cookie_params(); setcookie(session_name(), '', [ 'expires' => time() - 3600, 'path' => $p['path'] ?? '/', 'secure' => (bool) ($p['secure'] ?? false), 'httponly' => true, 'samesite' => 'Lax', ]); } session_destroy(); } function currentUser(): ?array { $id = $_SESSION['user'] ?? null; $name = $_SESSION['name'] ?? null; if (!is_string($id) || $id === '' || !is_string($name)) { return null; } if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) { return null; } $avatar = $_SESSION['avatar'] ?? null; return [ 'id' => $id, 'name' => $name, 'avatar' => is_string($avatar) ? $avatar : null, ]; } function requireUser(): array { $u = currentUser(); if (!$u) { jsonFail('login', 401); } return $u; } function csrfToken(): string { if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(24)); } return $_SESSION['csrf']; } function requireCsrf(): void { if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') { return; } $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ''; if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) { jsonFail('csrf', 403); } } function jsonOut(array $data, int $status = 200): never { http_response_code($status); header('Content-Type: application/json; charset=utf-8'); header('Cache-Control: no-store'); echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); exit; } function jsonFail(string $message, int $status = 400): never { jsonOut(['ok' => false, 'error' => $message], $status); } function readJsonBody(): array { $raw = file_get_contents('php://input'); if (!is_string($raw) || $raw === '') { return $_POST; } $data = json_decode($raw, true); return is_array($data) ? $data : []; } function safeNext(mixed $next): ?string { if (!is_string($next) || $next === '') { return null; } // Only a relative path on this app, no scheme, no protocol-relative, no backslash. if (preg_match('#^[a-z]+://#i', $next) || str_starts_with($next, '//') || str_contains($next, '\\')) { return null; } if ($next[0] === '/') { return null; } if (!preg_match('@^[A-Za-z0-9._~/?\#=&%\-]+$@', $next)) { return null; } return $next; } function startAlliantiesSession(): void { if (session_status() === PHP_SESSION_ACTIVE) { return; } $dir = ensureDataDir() . '/sessions'; if (!is_dir($dir)) { @mkdir($dir, 0775, true); } session_name('allianties_session'); ini_set('session.use_strict_mode', '1'); ini_set('session.gc_maxlifetime', (string) ALLIANTIES_SESSION_TTL); session_save_path($dir); $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/'; if ($path === '//') { $path = '/'; } $secure = !localDev(); session_set_cookie_params([ 'lifetime' => ALLIANTIES_SESSION_TTL, 'path' => $path, 'secure' => $secure, 'httponly' => true, 'samesite' => 'Lax', ]); session_start(); if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') { setcookie(session_name(), session_id(), [ 'expires' => time() + ALLIANTIES_SESSION_TTL, 'path' => $path, 'secure' => $secure, 'httponly' => true, 'samesite' => 'Lax', ]); } if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) { $_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL; } } if (!defined('ALLIANTIES_NO_SESSION')) { startAlliantiesSession(); } /** HTTP status for a stable API error code. not_host → 403 (only the host may change rules or start). */ function apiHttpStatus(string $code): int { return match ($code) { 'login' => 401, 'not_in_game', 'not_host', 'csrf' => 403, default => 400, }; }