BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / bootstrap.php

bootstrap.php

bootstrap.php 12.8 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
187function authAvatarUrl(array $profile): ?string
188{
189 foreach (['avatar_url', 'avatar', 'picture'] as $k) {
190 if (isset($profile[$k]) && is_string($profile[$k])) {
191 $url = safeAvatarUrl($profile[$k]);
192 if ($url !== null) {
193 return $url;
194 }
195 }
196 }
197 return null;
198}
199
200/**
201 * Parse GET /api/friends from auth.timfalken.com into Meteors user ids
202 * (`auth:{id}`), names and avatars. Invalid entries are skipped.
203 *
204 * @return list<array{id:string,name:string,avatar:?string}>
205 */
206function parseAuthFriends($data): array
207{
208 if (!is_array($data) || !isset($data['friends']) || !is_array($data['friends'])) {
209 return [];
210 }
211 $out = [];
212 foreach ($data['friends'] as $f) {
213 if (!is_array($f) || !isset($f['id'])) {
214 continue;
215 }
216 $raw = $f['id'];
217 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
218 if (!$numeric || (int) $raw < 1) {
219 continue;
220 }
221 $name = isset($f['username']) && is_string($f['username']) ? trim($f['username']) : '';
222 if ($name === '' || mb_strlen($name) > 64) {
223 $name = 'auth:' . (int) $raw;
224 }
225 $out[] = [
226 'id' => 'auth:' . (int) $raw,
227 'name' => $name,
228 'avatar' => authAvatarUrl($f),
229 ];
230 }
231 return $out;
232}
233
234/** Local testers test_user_1 and test_user_2 are friends of each other. */
235function localTestFriends(string $userId): array
236{
237 if ($userId === 'local:test_user_1') {
238 return [['id' => 'local:test_user_2', 'name' => 'test_user_2', 'avatar' => null]];
239 }
240 if ($userId === 'local:test_user_2') {
241 return [['id' => 'local:test_user_1', 'name' => 'test_user_1', 'avatar' => null]];
242 }
243 return [];
244}
245
246/** @return array{0:string,1:string,2:?string} id, name, avatar */
247function authIdentity(array $profile): array
248{
249 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
250 throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');
251 }
252 $raw = $profile['id'];
253 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
254 if (!$numeric || (int) $raw < 1) {
255 throw new RuntimeException('Ongeldig account-id.');
256 }
257 return ['auth:' . (int) $raw, $profile['username'], authAvatarUrl($profile)];
258}
259
260/**
261 * Where to go after a login (t1193). Only an explicit 'online' (login
262 * started from the Online screen) returns to online play; everything else
263 * (menu login, missing or unknown value) returns to the main menu.
264 */
265function loginReturnTarget($param): string
266{
267 return $param === 'online' ? 'online' : 'menu';
268}
269
270/** Relative page to land on after a login for a loginReturnTarget() value. */
271function loginReturnPath(?string $target): string
272{
273 return $target === 'online' ? 'index.html?online=1' : 'index.html';
274}
275
276function loginUser(string $id, string $name, ?string $avatar = null): void
277{
278 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) {
279 throw new RuntimeException('Ongeldig account.');
280 }
281 $name = trim($name);
282 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {
283 throw new RuntimeException('Ongeldige gebruikersnaam.');
284 }
285 session_regenerate_id(true);
286 $_SESSION['user'] = $id;
287 $_SESSION['name'] = $name;
288 $_SESSION['avatar'] = safeAvatarUrl($avatar);
289 $_SESSION['csrf'] = bin2hex(random_bytes(24));
290 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
291}
292
293function logoutUser(): void
294{
295 $_SESSION = [];
296 if (ini_get('session.use_cookies')) {
297 $p = session_get_cookie_params();
298 setcookie(session_name(), '', [
299 'expires' => time() - 3600,
300 'path' => $p['path'] ?? '/',
301 'secure' => (bool) ($p['secure'] ?? false),
302 'httponly' => true,
303 'samesite' => 'Lax',
304 ]);
305 }
306 session_destroy();
307}
308
309function currentUser(): ?array
310{
311 $id = $_SESSION['user'] ?? null;
312 $name = $_SESSION['name'] ?? null;
313 if (!is_string($id) || $id === '' || !is_string($name)) {
314 return null;
315 }
316 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
317 return null;
318 }
319 $avatar = $_SESSION['avatar'] ?? null;
320 return [
321 'id' => $id,
322 'name' => $name,
323 'avatar' => is_string($avatar) ? safeAvatarUrl($avatar) : null,
324 ];
325}
326
327function requireUser(): array
328{
329 $u = currentUser();
330 if (!$u) {
331 jsonFail('Log in om verder te gaan.', 401);
332 }
333 return $u;
334}
335
336function csrfToken(): string
337{
338 if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
339 $_SESSION['csrf'] = bin2hex(random_bytes(24));
340 }
341 return $_SESSION['csrf'];
342}
343
344function requireCsrf(): void
345{
346 if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
347 return;
348 }
349 $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
350 if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
351 jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);
352 }
353}
354
355function jsonOut(array $data, int $status = 200): never
356{
357 http_response_code($status);
358 header('Content-Type: application/json; charset=utf-8');
359 header('Cache-Control: no-store');
360 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
361 exit;
362}
363
364function jsonFail(string $message, int $status = 400): never
365{
366 jsonOut(['ok' => false, 'error' => $message], $status);
367}
368
369function readJsonBody(): array
370{
371 $raw = file_get_contents('php://input');
372 if (!is_string($raw) || $raw === '') {
373 return $_POST;
374 }
375 $data = json_decode($raw, true);
376 return is_array($data) ? $data : [];
377}
378
379function startMeteorsSession(): void
380{
381 if (session_status() === PHP_SESSION_ACTIVE) {
382 return;
383 }
384 $dir = ensureDataDir() . '/sessions';
385 if (!is_dir($dir)) {
386 @mkdir($dir, 0775, true);
387 }
388 session_name('meteors_session');
389 ini_set('session.use_strict_mode', '1');
390 ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);
391 session_save_path($dir);
392 $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
393 if ($path === '//') {
394 $path = '/';
395 }
396 $secure = !localDev();
397 session_set_cookie_params([
398 'lifetime' => METEORS_SESSION_TTL,
399 'path' => $path,
400 'secure' => $secure,
401 'httponly' => true,
402 'samesite' => 'Lax',
403 ]);
404 session_start();
405 if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
406 setcookie(session_name(), session_id(), [
407 'expires' => time() + METEORS_SESSION_TTL,
408 'path' => $path,
409 'secure' => $secure,
410 'httponly' => true,
411 'samesite' => 'Lax',
412 ]);
413 }
414 if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
415 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
416 }
417}
418
419if (!defined('METEORS_NO_SESSION')) {
420 startMeteorsSession();
421}