BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / bootstrap.php

bootstrap.php

bootstrap.php 10.3 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/** @return array{0:string,1:string} */
169function authIdentity(array $profile): array
170{
171 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
172 throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');
173 }
174 $raw = $profile['id'];
175 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
176 if (!$numeric || (int) $raw < 1) {
177 throw new RuntimeException('Ongeldig account-id.');
178 }
179 return ['auth:' . (int) $raw, $profile['username']];
180}
181
182/**
183 * Where to go after a login (t1193). Only an explicit 'online' (login
184 * started from the Online screen) returns to online play; everything else
185 * (menu login, missing or unknown value) returns to the main menu.
186 */
187function loginReturnTarget($param): string
188{
189 return $param === 'online' ? 'online' : 'menu';
190}
191
192/** Relative page to land on after a login for a loginReturnTarget() value. */
193function loginReturnPath(?string $target): string
194{
195 return $target === 'online' ? 'index.html?online=1' : 'index.html';
196}
197
198function loginUser(string $id, string $name): void
199{
200 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $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['csrf'] = bin2hex(random_bytes(24));
211 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
212}
213
214function logoutUser(): void
215{
216 $_SESSION = [];
217 if (ini_get('session.use_cookies')) {
218 $p = session_get_cookie_params();
219 setcookie(session_name(), '', [
220 'expires' => time() - 3600,
221 'path' => $p['path'] ?? '/',
222 'secure' => (bool) ($p['secure'] ?? false),
223 'httponly' => true,
224 'samesite' => 'Lax',
225 ]);
226 }
227 session_destroy();
228}
229
230function currentUser(): ?array
231{
232 $id = $_SESSION['user'] ?? null;
233 $name = $_SESSION['name'] ?? null;
234 if (!is_string($id) || $id === '' || !is_string($name)) {
235 return null;
236 }
237 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
238 return null;
239 }
240 return ['id' => $id, 'name' => $name];
241}
242
243function requireUser(): array
244{
245 $u = currentUser();
246 if (!$u) {
247 jsonFail('Log in om verder te gaan.', 401);
248 }
249 return $u;
250}
251
252function csrfToken(): string
253{
254 if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
255 $_SESSION['csrf'] = bin2hex(random_bytes(24));
256 }
257 return $_SESSION['csrf'];
258}
259
260function requireCsrf(): void
261{
262 if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
263 return;
264 }
265 $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
266 if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
267 jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);
268 }
269}
270
271function jsonOut(array $data, int $status = 200): never
272{
273 http_response_code($status);
274 header('Content-Type: application/json; charset=utf-8');
275 header('Cache-Control: no-store');
276 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
277 exit;
278}
279
280function jsonFail(string $message, int $status = 400): never
281{
282 jsonOut(['ok' => false, 'error' => $message], $status);
283}
284
285function readJsonBody(): array
286{
287 $raw = file_get_contents('php://input');
288 if (!is_string($raw) || $raw === '') {
289 return $_POST;
290 }
291 $data = json_decode($raw, true);
292 return is_array($data) ? $data : [];
293}
294
295function startMeteorsSession(): void
296{
297 if (session_status() === PHP_SESSION_ACTIVE) {
298 return;
299 }
300 $dir = ensureDataDir() . '/sessions';
301 if (!is_dir($dir)) {
302 @mkdir($dir, 0775, true);
303 }
304 session_name('meteors_session');
305 ini_set('session.use_strict_mode', '1');
306 ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);
307 session_save_path($dir);
308 $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
309 if ($path === '//') {
310 $path = '/';
311 }
312 $secure = !localDev();
313 session_set_cookie_params([
314 'lifetime' => METEORS_SESSION_TTL,
315 'path' => $path,
316 'secure' => $secure,
317 'httponly' => true,
318 'samesite' => 'Lax',
319 ]);
320 session_start();
321 if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
322 setcookie(session_name(), session_id(), [
323 'expires' => time() + METEORS_SESSION_TTL,
324 'path' => $path,
325 'secure' => $secure,
326 'httponly' => true,
327 'samesite' => 'Lax',
328 ]);
329 }
330 if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
331 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
332 }
333}
334
335if (!defined('METEORS_NO_SESSION')) {
336 startMeteorsSession();
337}