BlueGit

projects-timfalken-com meteors

Files

meteors / server / lib / bootstrap.php

bootstrap.php

bootstrap.php 9.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/** @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
182function loginUser(string $id, string $name): void
183{
184 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) {
185 throw new RuntimeException('Ongeldig account.');
186 }
187 $name = trim($name);
188 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {
189 throw new RuntimeException('Ongeldige gebruikersnaam.');
190 }
191 session_regenerate_id(true);
192 $_SESSION['user'] = $id;
193 $_SESSION['name'] = $name;
194 $_SESSION['csrf'] = bin2hex(random_bytes(24));
195 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
196}
197
198function logoutUser(): void
199{
200 $_SESSION = [];
201 if (ini_get('session.use_cookies')) {
202 $p = session_get_cookie_params();
203 setcookie(session_name(), '', [
204 'expires' => time() - 3600,
205 'path' => $p['path'] ?? '/',
206 'secure' => (bool) ($p['secure'] ?? false),
207 'httponly' => true,
208 'samesite' => 'Lax',
209 ]);
210 }
211 session_destroy();
212}
213
214function currentUser(): ?array
215{
216 $id = $_SESSION['user'] ?? null;
217 $name = $_SESSION['name'] ?? null;
218 if (!is_string($id) || $id === '' || !is_string($name)) {
219 return null;
220 }
221 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
222 return null;
223 }
224 return ['id' => $id, 'name' => $name];
225}
226
227function requireUser(): array
228{
229 $u = currentUser();
230 if (!$u) {
231 jsonFail('Log in om verder te gaan.', 401);
232 }
233 return $u;
234}
235
236function csrfToken(): string
237{
238 if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
239 $_SESSION['csrf'] = bin2hex(random_bytes(24));
240 }
241 return $_SESSION['csrf'];
242}
243
244function requireCsrf(): void
245{
246 if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
247 return;
248 }
249 $got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
250 if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
251 jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);
252 }
253}
254
255function jsonOut(array $data, int $status = 200): never
256{
257 http_response_code($status);
258 header('Content-Type: application/json; charset=utf-8');
259 header('Cache-Control: no-store');
260 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
261 exit;
262}
263
264function jsonFail(string $message, int $status = 400): never
265{
266 jsonOut(['ok' => false, 'error' => $message], $status);
267}
268
269function readJsonBody(): array
270{
271 $raw = file_get_contents('php://input');
272 if (!is_string($raw) || $raw === '') {
273 return $_POST;
274 }
275 $data = json_decode($raw, true);
276 return is_array($data) ? $data : [];
277}
278
279function startMeteorsSession(): void
280{
281 if (session_status() === PHP_SESSION_ACTIVE) {
282 return;
283 }
284 $dir = ensureDataDir() . '/sessions';
285 if (!is_dir($dir)) {
286 @mkdir($dir, 0775, true);
287 }
288 session_name('meteors_session');
289 ini_set('session.use_strict_mode', '1');
290 ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);
291 session_save_path($dir);
292 $path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
293 if ($path === '//') {
294 $path = '/';
295 }
296 $secure = !localDev();
297 session_set_cookie_params([
298 'lifetime' => METEORS_SESSION_TTL,
299 'path' => $path,
300 'secure' => $secure,
301 'httponly' => true,
302 'samesite' => 'Lax',
303 ]);
304 session_start();
305 if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
306 setcookie(session_name(), session_id(), [
307 'expires' => time() + METEORS_SESSION_TTL,
308 'path' => $path,
309 'secure' => $secure,
310 'httponly' => true,
311 'samesite' => 'Lax',
312 ]);
313 }
314 if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
315 $_SESSION['expires'] = time() + METEORS_SESSION_TTL;
316 }
317}
318
319if (!defined('METEORS_NO_SESSION')) {
320 startMeteorsSession();
321}