BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / bootstrap.php

bootstrap.php

bootstrap.php 21.1 KiB Download Raw
1<?php
2declare(strict_types=1);
3
4const METEORS_SESSION_TTL = 86400;
5const METEORS_DEFAULT_AUTH = 'https://auth.timfalken.com';
6const METEORS_DEFAULT_CLIENT_ID = 'projects.timfalken.com';
7const METEORS_DEFAULT_BASE = 'https://projects.timfalken.com/meteors';
8const METEORS_DEFAULT_MISS = 0.30;
9const METEORS_FLIGHT_DURATION = 1.2;
10const METEORS_MAX_PLAYERS = 32;
11const METEORS_PODIUM_SECONDS = 5;
12
13function dataDir(): string
14{
15 $override = getenv('METEORS_DATA_DIR');
16 if (is_string($override) && $override !== '') {
17 return rtrim($override, '/');
18 }
19 return dirname(__DIR__) . '/data';
20}
21
22function ensureDataDir(): string
23{
24 $dir = dataDir();
25 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
26 throw new RuntimeException('De datamap moet schrijfbaar zijn.');
27 }
28 $deny = $dir . '/.htaccess';
29 if (!is_file($deny)) {
30 @file_put_contents($deny, "Require all denied\n");
31 }
32 $sessions = $dir . '/sessions';
33 if (!is_dir($sessions)) {
34 @mkdir($sessions, 0775, true);
35 }
36 return $dir;
37}
38
39function localDev(): bool
40{
41 $host = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
42 return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
43 && in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
44}
45
46function config(): array
47{
48 $dir = ensureDataDir();
49 $path = $dir . '/config.php';
50 $lock = fopen($dir . '/config.lock', 'c');
51 if ($lock === false) {
52 throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
53 }
54 try {
55 if (!flock($lock, LOCK_EX)) {
56 throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
57 }
58 if (!is_file($path)) {
59 $template = <<<'PHP'
60<?php
61// Vul deze waarden op de server in. Lege velden gebruiken omgevingsvariabelen.
62// Productie-URL: https://projects.timfalken.com/meteors
63// client_id is het geregistreerde domein: projects.timfalken.com.
64// Het geheim komt uit https://auth.timfalken.com/admin (het BESTAANDE geheim
65// van dit domein; NIET opnieuw genereren, dat breekt de andere sites).
66// Voeg daar ook het callback-pad /meteors/callback.php toe.
67// Dit bestand wordt niet gedeployed en staat niet in git.
68return [
69 'auth_url' => 'https://auth.timfalken.com',
70 'base_url' => 'https://projects.timfalken.com/meteors',
71 'client_id' => 'projects.timfalken.com',
72 'client_secret' => '',
73];
74PHP;
75 if (file_put_contents($path, $template) !== strlen($template)) {
76 throw new RuntimeException('data/config.php kon niet worden gemaakt.');
77 }
78 }
79 $values = require $path;
80 if (!is_array($values)) {
81 throw new RuntimeException('data/config.php moet een array teruggeven.');
82 }
83 } finally {
84 flock($lock, LOCK_UN);
85 fclose($lock);
86 }
87 foreach ([
88 'auth_url' => 'METEORS_AUTH_URL',
89 'base_url' => 'METEORS_BASE_URL',
90 'client_id' => 'METEORS_CLIENT_ID',
91 'client_secret' => 'METEORS_CLIENT_SECRET',
92 ] as $key => $env) {
93 if (($values[$key] ?? '') === '') {
94 $values[$key] = getenv($env) ?: '';
95 }
96 }
97 if (($values['auth_url'] ?? '') === '') {
98 $values['auth_url'] = METEORS_DEFAULT_AUTH;
99 }
100 if (($values['client_id'] ?? '') === '') {
101 $values['client_id'] = METEORS_DEFAULT_CLIENT_ID;
102 }
103 return $values;
104}
105
106function authConfigured(): bool
107{
108 $c = config();
109 return ($c['client_secret'] ?? '') !== ''
110 && ($c['client_id'] ?? '') !== ''
111 && ($c['base_url'] ?? '') !== '';
112}
113
114function baseUrl(): string
115{
116 if (localDev()) {
117 $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
118 if ($dir === '/' || $dir === '.') {
119 $dir = '';
120 }
121 return 'http://' . $_SERVER['HTTP_HOST'] . $dir;
122 }
123 $base = rtrim((string) (config()['base_url'] ?? ''), '/');
124 if (!str_starts_with($base, 'https://')) {
125 throw new RuntimeException(
126 "Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie "
127 . '(https://projects.timfalken.com/meteors), of zet METEORS_BASE_URL.'
128 );
129 }
130 return $base;
131}
132
133function authUrl(): string
134{
135 $url = rtrim((string) (config()['auth_url'] ?? METEORS_DEFAULT_AUTH), '/');
136 return $url !== '' ? $url : METEORS_DEFAULT_AUTH;
137}
138
139function authRequest(string $path, ?array $form = null, ?string $token = null): array
140{
141 $ch = curl_init(authUrl() . $path);
142 $headers = ['Accept: application/json', 'User-Agent: Meteors/1.0'];
143 if ($token) {
144 $headers[] = 'Authorization: Bearer ' . $token;
145 }
146 curl_setopt_array($ch, [
147 CURLOPT_RETURNTRANSFER => true,
148 CURLOPT_TIMEOUT => 15,
149 CURLOPT_HTTPHEADER => $headers,
150 ]);
151 if ($form !== null) {
152 curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
153 }
154 $body = curl_exec($ch);
155 $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
156 $err = curl_error($ch);
157 curl_close($ch);
158 $data = is_string($body) ? json_decode($body, true) : null;
159 if ($status !== 200 || !is_array($data)) {
160 $hint = $err !== '' ? ' (' . $err . ')' : '';
161 throw new RuntimeException(
162 'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint
163 );
164 }
165 return $data;
166}
167
168/** Safe profile-picture URL from auth (https/http or a same-origin path). */
169function safeAvatarUrl($url): ?string
170{
171 if (!is_string($url)) {
172 return null;
173 }
174 $url = trim($url);
175 if ($url === '' || strlen($url) > 500) {
176 return null;
177 }
178 if (preg_match('#^(javascript|vbscript|data):#i', $url)) {
179 return null;
180 }
181 if (preg_match('#^https?://#i', $url) || str_starts_with($url, '/')) {
182 return $url;
183 }
184 return null;
185}
186
187/**
188 * True when $name is missing or only the numeric auth id (e.g. user
189 * auth:3 shown as "3"). Local test usernames like test_user_1 are real.
190 */
191function isPlaceholderName(string $userId, ?string $name): bool
192{
193 $name = trim((string) $name);
194 if ($name === '' || strcasecmp($name, 'Player') === 0) {
195 return true;
196 }
197 if (str_starts_with($userId, 'auth:')) {
198 $num = substr($userId, 5);
199 return $name === $num || $name === $userId;
200 }
201 return false;
202}
203
204/**
205 * Map an auth.timfalken.com OIDC locale claim (BCP 47, e.g. zh-Hans)
206 * to a Meteors locale id (zh). Unknown values become null.
207 */
208function normalizeAuthLocale($claim): ?string
209{
210 if (!is_string($claim) || $claim === '') {
211 return null;
212 }
213 $id = strtolower(str_replace('_', '-', trim($claim)));
214 if ($id === 'zh-hans' || $id === 'zh-cn' || $id === 'zh-sg' || $id === 'zh-my') {
215 return 'zh';
216 }
217 $known = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es'];
218 if (in_array($id, $known, true)) {
219 return $id;
220 }
221 $primary = explode('-', $id, 2)[0];
222 return in_array($primary, $known, true) ? $primary : null;
223}
224
225/** Locale claim from a token or /api/me payload (user.locale or locale). */
226function authLocaleFromPayload($data): ?string
227{
228 if (!is_array($data)) {
229 return null;
230 }
231 if (isset($data['user']) && is_array($data['user'])) {
232 $fromUser = normalizeAuthLocale($data['user']['locale'] ?? null);
233 if ($fromUser !== null) {
234 return $fromUser;
235 }
236 }
237 return normalizeAuthLocale($data['locale'] ?? null);
238}
239
240function storeAuthLocale(?string $claim): ?string
241{
242 $id = normalizeAuthLocale($claim);
243 if ($id === null) {
244 unset($_SESSION['auth_locale']);
245 return null;
246 }
247 $_SESSION['auth_locale'] = $id;
248 return $id;
249}
250
251function sessionAuthLocale(): ?string
252{
253 return normalizeAuthLocale($_SESSION['auth_locale'] ?? null);
254}
255
256/**
257 * Prefer the session value; when a bearer token is given, refresh from
258 * GET /api/me so a language change on auth.timfalken.com is picked up.
259 */
260function refreshAuthLocale(?string $token): ?string
261{
262 $current = sessionAuthLocale();
263 if (!is_string($token) || $token === '') {
264 return $current;
265 }
266 try {
267 $fresh = authLocaleFromPayload(authRequest('/api/me', null, $token));
268 if ($fresh !== null) {
269 $_SESSION['auth_locale'] = $fresh;
270 return $fresh;
271 }
272 } catch (Throwable $e) {
273 // Keep the value from login / the last successful refresh.
274 }
275 return $current;
276}
277
278/** Numeric auth id from a Meteors user id like auth:3, or null. */
279function authNumericId(string $userId): ?int
280{
281 if (!preg_match('/^auth:([1-9][0-9]{0,17})$/', $userId, $m)) {
282 return null;
283 }
284 return (int) $m[1];
285}
286
287/**
288 * Parse GET /api/profiles from auth.timfalken.com.
289 *
290 * @return list<array{id:string,name:string,avatar:?string}>
291 */
292function parseAuthProfiles($data): array
293{
294 if (!is_array($data) || !isset($data['profiles']) || !is_array($data['profiles'])) {
295 return [];
296 }
297 $out = [];
298 foreach ($data['profiles'] as $p) {
299 if (!is_array($p) || !isset($p['id'])) {
300 continue;
301 }
302 $raw = $p['id'];
303 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
304 if (!$numeric || (int) $raw < 1) {
305 continue;
306 }
307 $name = isset($p['username']) && is_string($p['username']) ? trim($p['username']) : '';
308 if ($name === '' || mb_strlen($name) > 64) {
309 continue;
310 }
311 $out[] = [
312 'id' => 'auth:' . (int) $raw,
313 'name' => $name,
314 'avatar' => authAvatarUrl($p),
315 ];
316 }
317 return $out;
318}
319
320/** Max ids per GET /api/profiles request (auth limit). */
321const AUTH_PROFILES_MAX_IDS = 50;
322
323/**
324 * Public names/avatars for auth:* ids via GET /api/profiles, cached
325 * in Meteors storage for Store::PROFILES_CACHE_TTL seconds. On auth
326 * failure, a stale cache or an empty list is returned (callers keep
327 * existing fallbacks).
328 *
329 * @param list<string> $userIds
330 * @return array<string, array{id:string,name:string,avatar:?string}>
331 */
332function authGetJson(string $path, ?string $token = null): array
333{
334 $hook = $GLOBALS['METEORS_AUTH_GET'] ?? null;
335 if (is_callable($hook)) {
336 return $hook($path, $token);
337 }
338 return authRequest($path, null, $token);
339}
340
341function fetchAuthProfiles(Store $store, array $userIds): array
342{
343 $wanted = [];
344 foreach ($userIds as $id) {
345 if (!is_string($id)) {
346 continue;
347 }
348 $num = authNumericId($id);
349 if ($num !== null) {
350 $wanted['auth:' . $num] = $num;
351 }
352 }
353 if ($wanted === []) {
354 return [];
355 }
356 $ids = array_keys($wanted);
357 $known = $store->readProfilesCache($ids);
358 $missing = [];
359 foreach ($ids as $id) {
360 if (!isset($known[$id])) {
361 $missing[] = $wanted[$id];
362 }
363 }
364 if ($missing === []) {
365 return $known;
366 }
367 $missing = array_values(array_unique($missing));
368 try {
369 $fetched = [];
370 foreach (array_chunk($missing, AUTH_PROFILES_MAX_IDS) as $chunk) {
371 $path = '/api/profiles?ids=' . implode(',', $chunk);
372 foreach (parseAuthProfiles(authGetJson($path)) as $row) {
373 $fetched[] = $row;
374 $known[$row['id']] = $row;
375 }
376 }
377 if ($fetched !== []) {
378 $store->writeProfilesCache($fetched);
379 }
380 } catch (Throwable $e) {
381 $stale = $store->readProfilesCache($ids, null, true);
382 foreach ($stale as $id => $row) {
383 if (!isset($known[$id])) {
384 $known[$id] = $row;
385 }
386 }
387 }
388 return $known;
389}
390
391function authAvatarUrl(array $profile): ?string
392{
393 foreach (['avatar_url', 'avatar', 'picture'] as $k) {
394 if (isset($profile[$k]) && is_string($profile[$k])) {
395 $url = safeAvatarUrl($profile[$k]);
396 if ($url !== null) {
397 return $url;
398 }
399 }
400 }
401 return null;
402}
403
404/**
405 * Parse GET /api/friends from auth.timfalken.com into Meteors user ids
406 * (`auth:{id}`), names and avatars. Invalid entries are skipped.
407 *
408 * @return list<array{id:string,name:string,avatar:?string}>
409 */
410function parseAuthFriends($data): array
411{
412 if (!is_array($data) || !isset($data['friends']) || !is_array($data['friends'])) {
413 return [];
414 }
415 $out = [];
416 foreach ($data['friends'] as $f) {
417 if (!is_array($f) || !isset($f['id'])) {
418 continue;
419 }
420 $raw = $f['id'];
421 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
422 if (!$numeric || (int) $raw < 1) {
423 continue;
424 }
425 $name = isset($f['username']) && is_string($f['username']) ? trim($f['username']) : '';
426 if ($name === '' || mb_strlen($name) > 64) {
427 $name = 'auth:' . (int) $raw;
428 }
429 $out[] = [
430 'id' => 'auth:' . (int) $raw,
431 'name' => $name,
432 'avatar' => authAvatarUrl($f),
433 ];
434 }
435 return $out;
436}
437
438/** Local testers test_user_1 and test_user_2 are friends of each other. */
439function localTestFriends(string $userId): array
440{
441 if ($userId === 'local:test_user_1') {
442 return [['id' => 'local:test_user_2', 'name' => 'test_user_2', 'avatar' => null]];
443 }
444 if ($userId === 'local:test_user_2') {
445 return [['id' => 'local:test_user_1', 'name' => 'test_user_1', 'avatar' => null]];
446 }
447 return [];
448}
449
450/**
451 * Friends of the current viewer from the auth cache, or a fresh
452 * GET /api/friends call. Local testers get the built-in pair.
453 *
454 * @return array{0: list<array{id:string,name:string,avatar:?string}, 1: ?string} friends, error
455 */
456function fetchViewerFriends(Store $store, array $user, $token): array
457{
458 $id = (string) ($user['id'] ?? '');
459 if ($id === '') {
460 return [[], null];
461 }
462 if (is_string($token) && $token !== '') {
463 $cached = $store->readFriendsCache($id);
464 if ($cached !== null) {
465 return [$cached, null];
466 }
467 try {
468 $friends = parseAuthFriends(authRequest('/api/friends', null, $token));
469 $store->writeFriendsCache($id, $friends);
470 return [$friends, null];
471 } catch (Throwable $e) {
472 $stale = $store->readFriendsCache($id, null, true);
473 if ($stale !== null) {
474 return [$stale, null];
475 }
476 return [[], $e->getMessage()];
477 }
478 }
479 if (localDev()) {
480 return [localTestFriends($id), null];
481 }
482 return [[], null];
483}
484
485/**
486 * Viewer's own identity plus friends from auth, keyed by Meteors user id.
487 * Also backfills existing profiles so later (guest) requests can show
488 * the same names without another auth call.
489 *
490 * @return array{0: array<string,array{id:string,name:string,avatar:?string}>, 1: list<array{id:string,name:string,avatar:?string}>, 2: ?string}
491 */
492function leaderboardKnownIdentities(Store $store, ?array $user, $token, array $playerIds = []): array
493{
494 $known = [];
495 $friends = [];
496 $error = null;
497 if ($user && isset($user['id'], $user['name'])) {
498 $known[$user['id']] = [
499 'id' => $user['id'],
500 'name' => (string) $user['name'],
501 'avatar' => $user['avatar'] ?? null,
502 ];
503 [$friends, $error] = fetchViewerFriends($store, $user, $token);
504 foreach ($friends as $f) {
505 if (isset($f['id']) && is_string($f['id'])) {
506 $known[$f['id']] = $f;
507 }
508 }
509 }
510 $ids = $playerIds;
511 foreach ($friends as $f) {
512 if (isset($f['id']) && is_string($f['id'])) {
513 $ids[] = $f['id'];
514 }
515 }
516 if ($user && isset($user['id'])) {
517 $ids[] = (string) $user['id'];
518 }
519 foreach (fetchAuthProfiles($store, $ids) as $id => $ident) {
520 $known[$id] = $ident;
521 }
522 if ($known !== []) {
523 $store->rememberIdentities(array_values($known));
524 }
525 return [$known, $friends, $error];
526}
527
528/** @return array{0:string,1:string,2:?string} id, name, avatar */
529function authIdentity(array $profile): array
530{
531 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
532 throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');
533 }
534 $raw = $profile['id'];
535 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
536 if (!$numeric || (int) $raw < 1) {
537 throw new RuntimeException('Ongeldig account-id.');
538 }
539 return ['auth:' . (int) $raw, $profile['username'], authAvatarUrl($profile)];
540}
541
542/**
543 * Where to go after a login (t1193). Only an explicit 'online' (login
544 * started from the Online screen) returns to online play; everything else
545 * (menu login, missing or unknown value) returns to the main menu.
546 */
547function loginReturnTarget($param): string
548{
549 return $param === 'online' ? 'online' : 'menu';
550}
551
552/** Relative page to land on after a login for a loginReturnTarget() value. */
553function loginReturnPath(?string $target): string
554{
555 return $target === 'online' ? 'index.html?online=1' : 'index.html';
556}
557
558function loginUser(string $id, string $name, ?string $avatar = null): void
559{
560 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) {
561 throw new RuntimeException('Ongeldig account.');
562 }
563 $name = trim($name);
564 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {
565 throw new RuntimeException('Ongeldige gebruikersnaam.');
566 }
567 session_regenerate_id(true);
568 $_SESSION['user'] = $id;
569 $_SESSION['name'] = $name;
570 $_SESSION['avatar'] = safeAvatarUrl($avatar);
571 $_SESSION['csrf'] = bin2hex(random_bytes(24));
572 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
573}
574
575function logoutUser(): void
576{
577 $_SESSION = [];
578 if (ini_get('session.use_cookies')) {
579 $p = session_get_cookie_params();
580 setcookie(session_name(), '', [
581 'expires' => time() - 3600,
582 'path' => $p['path'] ?? '/',
583 'secure' => (bool) ($p['secure'] ?? false),
584 'httponly' => true,
585 'samesite' => 'Lax',
586 ]);
587 }
588 session_destroy();
589}
590
591function currentUser(): ?array
592{
593 $id = $_SESSION['user'] ?? null;
594 $name = $_SESSION['name'] ?? null;
595 if (!is_string($id) || $id === '' || !is_string($name)) {
596 return null;
597 }
598 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
599 return null;
600 }
601 $avatar = $_SESSION['avatar'] ?? null;
602 return [
603 'id' => $id,
604 'name' => $name,
605 'avatar' => is_string($avatar) ? safeAvatarUrl($avatar) : null,
606 ];
607}
608
609function requireUser(): array
610{
611 $u = currentUser();
612 if (!$u) {
613 jsonFail('Log in om verder te gaan.', 401);
614 }
615 return $u;
616}
617
618function csrfToken(): string
619{
620 if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
621 $_SESSION['csrf'] = bin2hex(random_bytes(24));
622 }
623 return $_SESSION['csrf'];
624}
625
626function requireCsrf(): void
627{
628 if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
629 return;
630 }
631 $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
632 if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
633 jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);
634 }
635}
636
637function jsonOut(array $data, int $status = 200): never
638{
639 http_response_code($status);
640 header('Content-Type: application/json; charset=utf-8');
641 header('Cache-Control: no-store');
642 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
643 exit;
644}
645
646function jsonFail(string $message, int $status = 400): never
647{
648 jsonOut(['ok' => false, 'error' => $message], $status);
649}
650
651function readJsonBody(): array
652{
653 $raw = file_get_contents('php://input');
654 if (!is_string($raw) || $raw === '') {
655 return $_POST;
656 }
657 $data = json_decode($raw, true);
658 return is_array($data) ? $data : [];
659}
660
661function startMeteorsSession(): void
662{
663 if (session_status() === PHP_SESSION_ACTIVE) {
664 return;
665 }
666 $dir = ensureDataDir() . '/sessions';
667 if (!is_dir($dir)) {
668 @mkdir($dir, 0775, true);
669 }
670 session_name('meteors_session');
671 ini_set('session.use_strict_mode', '1');
672 ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);
673 session_save_path($dir);
674 $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
675 if ($path === '//') {
676 $path = '/';
677 }
678 $secure = !localDev();
679 session_set_cookie_params([
680 'lifetime' => METEORS_SESSION_TTL,
681 'path' => $path,
682 'secure' => $secure,
683 'httponly' => true,
684 'samesite' => 'Lax',
685 ]);
686 session_start();
687 if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
688 setcookie(session_name(), session_id(), [
689 'expires' => time() + METEORS_SESSION_TTL,
690 'path' => $path,
691 'secure' => $secure,
692 'httponly' => true,
693 'samesite' => 'Lax',
694 ]);
695 }
696 if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
697 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
698 }
699}
700
701if (!defined('METEORS_NO_SESSION')) {
702 startMeteorsSession();
703}