BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / bootstrap.php

bootstrap.php

bootstrap.php 15.4 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
204function authAvatarUrl(array $profile): ?string
205{
206 foreach (['avatar_url', 'avatar', 'picture'] as $k) {
207 if (isset($profile[$k]) && is_string($profile[$k])) {
208 $url = safeAvatarUrl($profile[$k]);
209 if ($url !== null) {
210 return $url;
211 }
212 }
213 }
214 return null;
215}
216
217/**
218 * Parse GET /api/friends from auth.timfalken.com into Meteors user ids
219 * (`auth:{id}`), names and avatars. Invalid entries are skipped.
220 *
221 * @return list<array{id:string,name:string,avatar:?string}>
222 */
223function parseAuthFriends($data): array
224{
225 if (!is_array($data) || !isset($data['friends']) || !is_array($data['friends'])) {
226 return [];
227 }
228 $out = [];
229 foreach ($data['friends'] as $f) {
230 if (!is_array($f) || !isset($f['id'])) {
231 continue;
232 }
233 $raw = $f['id'];
234 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
235 if (!$numeric || (int) $raw < 1) {
236 continue;
237 }
238 $name = isset($f['username']) && is_string($f['username']) ? trim($f['username']) : '';
239 if ($name === '' || mb_strlen($name) > 64) {
240 $name = 'auth:' . (int) $raw;
241 }
242 $out[] = [
243 'id' => 'auth:' . (int) $raw,
244 'name' => $name,
245 'avatar' => authAvatarUrl($f),
246 ];
247 }
248 return $out;
249}
250
251/** Local testers test_user_1 and test_user_2 are friends of each other. */
252function localTestFriends(string $userId): array
253{
254 if ($userId === 'local:test_user_1') {
255 return [['id' => 'local:test_user_2', 'name' => 'test_user_2', 'avatar' => null]];
256 }
257 if ($userId === 'local:test_user_2') {
258 return [['id' => 'local:test_user_1', 'name' => 'test_user_1', 'avatar' => null]];
259 }
260 return [];
261}
262
263/**
264 * Friends of the current viewer from the auth cache, or a fresh
265 * GET /api/friends call. Local testers get the built-in pair.
266 *
267 * @return array{0: list<array{id:string,name:string,avatar:?string}, 1: ?string} friends, error
268 */
269function fetchViewerFriends(Store $store, array $user, $token): array
270{
271 $id = (string) ($user['id'] ?? '');
272 if ($id === '') {
273 return [[], null];
274 }
275 if (is_string($token) && $token !== '') {
276 $cached = $store->readFriendsCache($id);
277 if ($cached !== null) {
278 return [$cached, null];
279 }
280 try {
281 $friends = parseAuthFriends(authRequest('/api/friends', null, $token));
282 $store->writeFriendsCache($id, $friends);
283 return [$friends, null];
284 } catch (Throwable $e) {
285 $stale = $store->readFriendsCache($id, null, true);
286 if ($stale !== null) {
287 return [$stale, null];
288 }
289 return [[], $e->getMessage()];
290 }
291 }
292 if (localDev()) {
293 return [localTestFriends($id), null];
294 }
295 return [[], null];
296}
297
298/**
299 * Viewer's own identity plus friends from auth, keyed by Meteors user id.
300 * Also backfills existing profiles so later (guest) requests can show
301 * the same names without another auth call.
302 *
303 * @return array{0: array<string,array{id:string,name:string,avatar:?string}>, 1: list<array{id:string,name:string,avatar:?string}>, 2: ?string}
304 */
305function leaderboardKnownIdentities(Store $store, ?array $user, $token): array
306{
307 $known = [];
308 $friends = [];
309 $error = null;
310 if ($user && isset($user['id'], $user['name'])) {
311 $known[$user['id']] = [
312 'id' => $user['id'],
313 'name' => (string) $user['name'],
314 'avatar' => $user['avatar'] ?? null,
315 ];
316 [$friends, $error] = fetchViewerFriends($store, $user, $token);
317 foreach ($friends as $f) {
318 if (isset($f['id']) && is_string($f['id'])) {
319 $known[$f['id']] = $f;
320 }
321 }
322 $store->rememberIdentities(array_values($known));
323 }
324 return [$known, $friends, $error];
325}
326
327/** @return array{0:string,1:string,2:?string} id, name, avatar */
328function authIdentity(array $profile): array
329{
330 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
331 throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');
332 }
333 $raw = $profile['id'];
334 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
335 if (!$numeric || (int) $raw < 1) {
336 throw new RuntimeException('Ongeldig account-id.');
337 }
338 return ['auth:' . (int) $raw, $profile['username'], authAvatarUrl($profile)];
339}
340
341/**
342 * Where to go after a login (t1193). Only an explicit 'online' (login
343 * started from the Online screen) returns to online play; everything else
344 * (menu login, missing or unknown value) returns to the main menu.
345 */
346function loginReturnTarget($param): string
347{
348 return $param === 'online' ? 'online' : 'menu';
349}
350
351/** Relative page to land on after a login for a loginReturnTarget() value. */
352function loginReturnPath(?string $target): string
353{
354 return $target === 'online' ? 'index.html?online=1' : 'index.html';
355}
356
357function loginUser(string $id, string $name, ?string $avatar = null): void
358{
359 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) {
360 throw new RuntimeException('Ongeldig account.');
361 }
362 $name = trim($name);
363 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {
364 throw new RuntimeException('Ongeldige gebruikersnaam.');
365 }
366 session_regenerate_id(true);
367 $_SESSION['user'] = $id;
368 $_SESSION['name'] = $name;
369 $_SESSION['avatar'] = safeAvatarUrl($avatar);
370 $_SESSION['csrf'] = bin2hex(random_bytes(24));
371 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
372}
373
374function logoutUser(): void
375{
376 $_SESSION = [];
377 if (ini_get('session.use_cookies')) {
378 $p = session_get_cookie_params();
379 setcookie(session_name(), '', [
380 'expires' => time() - 3600,
381 'path' => $p['path'] ?? '/',
382 'secure' => (bool) ($p['secure'] ?? false),
383 'httponly' => true,
384 'samesite' => 'Lax',
385 ]);
386 }
387 session_destroy();
388}
389
390function currentUser(): ?array
391{
392 $id = $_SESSION['user'] ?? null;
393 $name = $_SESSION['name'] ?? null;
394 if (!is_string($id) || $id === '' || !is_string($name)) {
395 return null;
396 }
397 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
398 return null;
399 }
400 $avatar = $_SESSION['avatar'] ?? null;
401 return [
402 'id' => $id,
403 'name' => $name,
404 'avatar' => is_string($avatar) ? safeAvatarUrl($avatar) : null,
405 ];
406}
407
408function requireUser(): array
409{
410 $u = currentUser();
411 if (!$u) {
412 jsonFail('Log in om verder te gaan.', 401);
413 }
414 return $u;
415}
416
417function csrfToken(): string
418{
419 if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
420 $_SESSION['csrf'] = bin2hex(random_bytes(24));
421 }
422 return $_SESSION['csrf'];
423}
424
425function requireCsrf(): void
426{
427 if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
428 return;
429 }
430 $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
431 if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
432 jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);
433 }
434}
435
436function jsonOut(array $data, int $status = 200): never
437{
438 http_response_code($status);
439 header('Content-Type: application/json; charset=utf-8');
440 header('Cache-Control: no-store');
441 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
442 exit;
443}
444
445function jsonFail(string $message, int $status = 400): never
446{
447 jsonOut(['ok' => false, 'error' => $message], $status);
448}
449
450function readJsonBody(): array
451{
452 $raw = file_get_contents('php://input');
453 if (!is_string($raw) || $raw === '') {
454 return $_POST;
455 }
456 $data = json_decode($raw, true);
457 return is_array($data) ? $data : [];
458}
459
460function startMeteorsSession(): void
461{
462 if (session_status() === PHP_SESSION_ACTIVE) {
463 return;
464 }
465 $dir = ensureDataDir() . '/sessions';
466 if (!is_dir($dir)) {
467 @mkdir($dir, 0775, true);
468 }
469 session_name('meteors_session');
470 ini_set('session.use_strict_mode', '1');
471 ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);
472 session_save_path($dir);
473 $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
474 if ($path === '//') {
475 $path = '/';
476 }
477 $secure = !localDev();
478 session_set_cookie_params([
479 'lifetime' => METEORS_SESSION_TTL,
480 'path' => $path,
481 'secure' => $secure,
482 'httponly' => true,
483 'samesite' => 'Lax',
484 ]);
485 session_start();
486 if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
487 setcookie(session_name(), session_id(), [
488 'expires' => time() + METEORS_SESSION_TTL,
489 'path' => $path,
490 'secure' => $secure,
491 'httponly' => true,
492 'samesite' => 'Lax',
493 ]);
494 }
495 if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
496 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
497 }
498}
499
500if (!defined('METEORS_NO_SESSION')) {
501 startMeteorsSession();
502}