| 1 | <?php |
| 2 | declare(strict_types=1); |
| 3 | |
| 4 | const ALLIANTIES_SESSION_TTL = 86400 * 30; |
| 5 | const ALLIANTIES_DEFAULT_AUTH = 'https://auth.timfalken.com'; |
| 6 | const ALLIANTIES_DEFAULT_CLIENT_ID = 'projects.timfalken.com'; |
| 7 | const ALLIANTIES_DEFAULT_BASE = 'https://projects.timfalken.com/allianties'; |
| 8 | const ALLIANTIES_TEST_USERS = 8; |
| 9 | |
| 10 | function dataDir(): string |
| 11 | { |
| 12 | $override = getenv('ALLIANTIES_DATA_DIR'); |
| 13 | if (is_string($override) && $override !== '') { |
| 14 | return rtrim($override, '/'); |
| 15 | } |
| 16 | return dirname(__DIR__) . '/data'; |
| 17 | } |
| 18 | |
| 19 | function ensureDataDir(): string |
| 20 | { |
| 21 | $dir = dataDir(); |
| 22 | if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) { |
| 23 | throw new RuntimeException('De datamap moet schrijfbaar zijn.'); |
| 24 | } |
| 25 | $deny = $dir . '/.htaccess'; |
| 26 | if (!is_file($deny)) { |
| 27 | @file_put_contents($deny, "Require all denied\n"); |
| 28 | } |
| 29 | $sessions = $dir . '/sessions'; |
| 30 | if (!is_dir($sessions)) { |
| 31 | @mkdir($sessions, 0775, true); |
| 32 | } |
| 33 | return $dir; |
| 34 | } |
| 35 | |
| 36 | function localDev(): bool |
| 37 | { |
| 38 | $host = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST); |
| 39 | return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true) |
| 40 | && in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true); |
| 41 | } |
| 42 | |
| 43 | function config(): array |
| 44 | { |
| 45 | $dir = ensureDataDir(); |
| 46 | $path = $dir . '/config.php'; |
| 47 | $lock = fopen($dir . '/config.lock', 'c'); |
| 48 | if ($lock === false) { |
| 49 | throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.'); |
| 50 | } |
| 51 | try { |
| 52 | if (!flock($lock, LOCK_EX)) { |
| 53 | throw new RuntimeException('De configuratie kon niet worden vergrendeld.'); |
| 54 | } |
| 55 | if (!is_file($path)) { |
| 56 | $template = <<<'PHP' |
| 57 | <?php |
| 58 | // Vul deze waarden op de server in. Lege velden gebruiken omgevingsvariabelen. |
| 59 | // Productie-URL: https://projects.timfalken.com/allianties |
| 60 | // client_id is het geregistreerde domein: projects.timfalken.com. |
| 61 | // Het geheim komt uit https://auth.timfalken.com/admin (het BESTAANDE geheim |
| 62 | // van dit domein; NIET opnieuw genereren, dat breekt de andere sites). |
| 63 | // Voeg daar ook het callback-pad /allianties/callback.php toe. |
| 64 | // Dit bestand wordt niet gedeployed en staat niet in git. |
| 65 | return [ |
| 66 | 'auth_url' => 'https://auth.timfalken.com', |
| 67 | 'base_url' => 'https://projects.timfalken.com/allianties', |
| 68 | 'client_id' => 'projects.timfalken.com', |
| 69 | 'client_secret' => '', |
| 70 | ]; |
| 71 | PHP; |
| 72 | if (file_put_contents($path, $template) !== strlen($template)) { |
| 73 | throw new RuntimeException('data/config.php kon niet worden gemaakt.'); |
| 74 | } |
| 75 | } |
| 76 | $values = require $path; |
| 77 | if (!is_array($values)) { |
| 78 | throw new RuntimeException('data/config.php moet een array teruggeven.'); |
| 79 | } |
| 80 | } finally { |
| 81 | flock($lock, LOCK_UN); |
| 82 | fclose($lock); |
| 83 | } |
| 84 | foreach ([ |
| 85 | 'auth_url' => 'ALLIANTIES_AUTH_URL', |
| 86 | 'base_url' => 'ALLIANTIES_BASE_URL', |
| 87 | 'client_id' => 'ALLIANTIES_CLIENT_ID', |
| 88 | 'client_secret' => 'ALLIANTIES_CLIENT_SECRET', |
| 89 | ] as $key => $env) { |
| 90 | if (($values[$key] ?? '') === '') { |
| 91 | $values[$key] = getenv($env) ?: ''; |
| 92 | } |
| 93 | } |
| 94 | if (($values['auth_url'] ?? '') === '') { |
| 95 | $values['auth_url'] = ALLIANTIES_DEFAULT_AUTH; |
| 96 | } |
| 97 | if (($values['client_id'] ?? '') === '') { |
| 98 | $values['client_id'] = ALLIANTIES_DEFAULT_CLIENT_ID; |
| 99 | } |
| 100 | return $values; |
| 101 | } |
| 102 | |
| 103 | function authConfigured(): bool |
| 104 | { |
| 105 | $c = config(); |
| 106 | return ($c['client_secret'] ?? '') !== '' |
| 107 | && ($c['client_id'] ?? '') !== '' |
| 108 | && ($c['base_url'] ?? '') !== ''; |
| 109 | } |
| 110 | |
| 111 | function baseUrl(): string |
| 112 | { |
| 113 | if (localDev()) { |
| 114 | $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/'); |
| 115 | if ($dir === '/' || $dir === '.') { |
| 116 | $dir = ''; |
| 117 | } |
| 118 | return 'http://' . $_SERVER['HTTP_HOST'] . $dir; |
| 119 | } |
| 120 | $base = rtrim((string) (config()['base_url'] ?? ''), '/'); |
| 121 | if (!str_starts_with($base, 'https://')) { |
| 122 | throw new RuntimeException( |
| 123 | "Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie " |
| 124 | . '(https://projects.timfalken.com/allianties), of zet ALLIANTIES_BASE_URL.' |
| 125 | ); |
| 126 | } |
| 127 | return $base; |
| 128 | } |
| 129 | |
| 130 | function authUrl(): string |
| 131 | { |
| 132 | $url = rtrim((string) (config()['auth_url'] ?? ALLIANTIES_DEFAULT_AUTH), '/'); |
| 133 | return $url !== '' ? $url : ALLIANTIES_DEFAULT_AUTH; |
| 134 | } |
| 135 | |
| 136 | function authRequest(string $path, ?array $form = null, ?string $token = null): array |
| 137 | { |
| 138 | $ch = curl_init(authUrl() . $path); |
| 139 | $headers = ['Accept: application/json', 'User-Agent: Allianties/1.0']; |
| 140 | if ($token) { |
| 141 | $headers[] = 'Authorization: Bearer ' . $token; |
| 142 | } |
| 143 | curl_setopt_array($ch, [ |
| 144 | CURLOPT_RETURNTRANSFER => true, |
| 145 | CURLOPT_TIMEOUT => 15, |
| 146 | CURLOPT_HTTPHEADER => $headers, |
| 147 | ]); |
| 148 | if ($form !== null) { |
| 149 | curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]); |
| 150 | } |
| 151 | $body = curl_exec($ch); |
| 152 | $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE); |
| 153 | $err = curl_error($ch); |
| 154 | curl_close($ch); |
| 155 | $data = is_string($body) ? json_decode($body, true) : null; |
| 156 | if ($status !== 200 || !is_array($data)) { |
| 157 | $hint = $err !== '' ? ' (' . $err . ')' : ''; |
| 158 | throw new RuntimeException( |
| 159 | 'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint |
| 160 | ); |
| 161 | } |
| 162 | return $data; |
| 163 | } |
| 164 | |
| 165 | /** @return array{0:string,1:string,2:?string} id, name, avatar */ |
| 166 | function authIdentity(array $profile): array |
| 167 | { |
| 168 | if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) { |
| 169 | throw new RuntimeException('Het profiel mist een id of gebruikersnaam.'); |
| 170 | } |
| 171 | $raw = $profile['id']; |
| 172 | $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw)); |
| 173 | if (!$numeric || (int) $raw < 1) { |
| 174 | throw new RuntimeException('Ongeldig account-id.'); |
| 175 | } |
| 176 | $id = (int) $raw; |
| 177 | $avatar = null; |
| 178 | foreach (['avatar_url', 'avatar', 'picture', 'icon', 'image'] as $k) { |
| 179 | if (isset($profile[$k]) && is_string($profile[$k]) && str_starts_with($profile[$k], 'https://')) { |
| 180 | $avatar = $profile[$k]; |
| 181 | break; |
| 182 | } |
| 183 | } |
| 184 | if ($avatar === null) { |
| 185 | $avatar = authUrl() . '/avatar/' . $id; |
| 186 | } |
| 187 | return ['auth:' . $id, $profile['username'], $avatar]; |
| 188 | } |
| 189 | |
| 190 | function isValidUserId(string $id): bool |
| 191 | { |
| 192 | if (preg_match('/^auth:[1-9][0-9]{0,17}$/', $id)) { |
| 193 | return true; |
| 194 | } |
| 195 | return (bool) preg_match('/^local:test_user_([1-9]|1[0-6])$/', $id); |
| 196 | } |
| 197 | |
| 198 | function loginUser(string $id, string $name, ?string $avatar = null): void |
| 199 | { |
| 200 | if (!isValidUserId($id)) { |
| 201 | throw new RuntimeException('Ongeldig account.'); |
| 202 | } |
| 203 | $name = trim($name); |
| 204 | if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) { |
| 205 | throw new RuntimeException('Ongeldige gebruikersnaam.'); |
| 206 | } |
| 207 | session_regenerate_id(true); |
| 208 | $_SESSION['user'] = $id; |
| 209 | $_SESSION['name'] = $name; |
| 210 | $_SESSION['avatar'] = $avatar; |
| 211 | $_SESSION['csrf'] = bin2hex(random_bytes(24)); |
| 212 | $_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL; |
| 213 | } |
| 214 | |
| 215 | function logoutUser(): void |
| 216 | { |
| 217 | $_SESSION = []; |
| 218 | if (ini_get('session.use_cookies')) { |
| 219 | $p = session_get_cookie_params(); |
| 220 | setcookie(session_name(), '', [ |
| 221 | 'expires' => time() - 3600, |
| 222 | 'path' => $p['path'] ?? '/', |
| 223 | 'secure' => (bool) ($p['secure'] ?? false), |
| 224 | 'httponly' => true, |
| 225 | 'samesite' => 'Lax', |
| 226 | ]); |
| 227 | } |
| 228 | session_destroy(); |
| 229 | } |
| 230 | |
| 231 | function currentUser(): ?array |
| 232 | { |
| 233 | $id = $_SESSION['user'] ?? null; |
| 234 | $name = $_SESSION['name'] ?? null; |
| 235 | if (!is_string($id) || $id === '' || !is_string($name)) { |
| 236 | return null; |
| 237 | } |
| 238 | if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) { |
| 239 | return null; |
| 240 | } |
| 241 | $avatar = $_SESSION['avatar'] ?? null; |
| 242 | return [ |
| 243 | 'id' => $id, |
| 244 | 'name' => $name, |
| 245 | 'avatar' => is_string($avatar) ? $avatar : null, |
| 246 | ]; |
| 247 | } |
| 248 | |
| 249 | function requireUser(): array |
| 250 | { |
| 251 | $u = currentUser(); |
| 252 | if (!$u) { |
| 253 | jsonFail('login', 401); |
| 254 | } |
| 255 | return $u; |
| 256 | } |
| 257 | |
| 258 | function csrfToken(): string |
| 259 | { |
| 260 | if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) { |
| 261 | $_SESSION['csrf'] = bin2hex(random_bytes(24)); |
| 262 | } |
| 263 | return $_SESSION['csrf']; |
| 264 | } |
| 265 | |
| 266 | function requireCsrf(): void |
| 267 | { |
| 268 | if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') { |
| 269 | return; |
| 270 | } |
| 271 | $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? ''; |
| 272 | if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) { |
| 273 | jsonFail('csrf', 403); |
| 274 | } |
| 275 | } |
| 276 | |
| 277 | function jsonOut(array $data, int $status = 200): never |
| 278 | { |
| 279 | http_response_code($status); |
| 280 | header('Content-Type: application/json; charset=utf-8'); |
| 281 | header('Cache-Control: no-store'); |
| 282 | echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); |
| 283 | exit; |
| 284 | } |
| 285 | |
| 286 | function jsonFail(string $message, int $status = 400): never |
| 287 | { |
| 288 | jsonOut(['ok' => false, 'error' => $message], $status); |
| 289 | } |
| 290 | |
| 291 | function readJsonBody(): array |
| 292 | { |
| 293 | $raw = file_get_contents('php://input'); |
| 294 | if (!is_string($raw) || $raw === '') { |
| 295 | return $_POST; |
| 296 | } |
| 297 | $data = json_decode($raw, true); |
| 298 | return is_array($data) ? $data : []; |
| 299 | } |
| 300 | |
| 301 | function safeNext(mixed $next): ?string |
| 302 | { |
| 303 | if (!is_string($next) || $next === '') { |
| 304 | return null; |
| 305 | } |
| 306 | // Only a relative path on this app, no scheme, no protocol-relative, no backslash. |
| 307 | if (preg_match('#^[a-z]+://#i', $next) || str_starts_with($next, '//') || str_contains($next, '\\')) { |
| 308 | return null; |
| 309 | } |
| 310 | if ($next[0] === '/') { |
| 311 | return null; |
| 312 | } |
| 313 | if (!preg_match('@^[A-Za-z0-9._~/?\#=&%\-]+$@', $next)) { |
| 314 | return null; |
| 315 | } |
| 316 | return $next; |
| 317 | } |
| 318 | |
| 319 | function startAlliantiesSession(): void |
| 320 | { |
| 321 | if (session_status() === PHP_SESSION_ACTIVE) { |
| 322 | return; |
| 323 | } |
| 324 | $dir = ensureDataDir() . '/sessions'; |
| 325 | if (!is_dir($dir)) { |
| 326 | @mkdir($dir, 0775, true); |
| 327 | } |
| 328 | session_name('allianties_session'); |
| 329 | ini_set('session.use_strict_mode', '1'); |
| 330 | ini_set('session.gc_maxlifetime', (string) ALLIANTIES_SESSION_TTL); |
| 331 | session_save_path($dir); |
| 332 | $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/'; |
| 333 | if ($path === '//') { |
| 334 | $path = '/'; |
| 335 | } |
| 336 | $secure = !localDev(); |
| 337 | session_set_cookie_params([ |
| 338 | 'lifetime' => ALLIANTIES_SESSION_TTL, |
| 339 | 'path' => $path, |
| 340 | 'secure' => $secure, |
| 341 | 'httponly' => true, |
| 342 | 'samesite' => 'Lax', |
| 343 | ]); |
| 344 | session_start(); |
| 345 | if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') { |
| 346 | setcookie(session_name(), session_id(), [ |
| 347 | 'expires' => time() + ALLIANTIES_SESSION_TTL, |
| 348 | 'path' => $path, |
| 349 | 'secure' => $secure, |
| 350 | 'httponly' => true, |
| 351 | 'samesite' => 'Lax', |
| 352 | ]); |
| 353 | } |
| 354 | if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) { |
| 355 | $_SESSION['expires'] = time() + ALLIANTIES_SESSION_TTL; |
| 356 | } |
| 357 | } |
| 358 | |
| 359 | if (!defined('ALLIANTIES_NO_SESSION')) { |
| 360 | startAlliantiesSession(); |
| 361 | } |
projects-timfalken-com allianties