BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / lib / bootstrap.php

bootstrap.php

fix: scroll naar boven bij wisselen van dag
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 5 weeks ago
8dd1bc1f History
bootstrap.php 19.4 KiB Download Raw
1<?php
2declare(strict_types=1);
3require_once __DIR__.'/Storybook.php';
4ini_set('display_errors', '0');
5ini_set('log_errors', '1');
6ini_set('error_log', dataDir().'/php-errors.log');
7header('X-Content-Type-Options: nosniff');
8header('Referrer-Policy: same-origin');
9header("Content-Security-Policy: default-src 'self'; img-src 'self' https://auth.timfalken.com; style-src 'self'; script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
10header('Cache-Control: no-store');
11
12function dataDir(): string {
13 $env = getenv('VERHALENBOEK_DATA_DIR');
14 if (is_string($env) && $env !== '') return rtrim($env, '/');
15 return dirname(__DIR__).'/data';
16}
17
18function db(): PDO {
19 static $db;
20 if ($db) return $db;
21 $dir = dataDir();
22 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) throw new RuntimeException('De datamap moet bestaan en schrijfbaar zijn.');
23 $db = new PDO('sqlite:'.$dir.'/verhalenboek.sqlite', null, null, [
24 PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
25 PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
26 ]);
27 $db->exec('PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;');
28 $db->exec('CREATE TABLE IF NOT EXISTS users (
29 id TEXT PRIMARY KEY,
30 name TEXT NOT NULL,
31 role TEXT NOT NULL DEFAULT \'user\' CHECK(role IN (\'admin\',\'user\')),
32 theme TEXT NOT NULL DEFAULT \'system\' CHECK(theme IN (\'system\',\'light\',\'dark\')),
33 font TEXT NOT NULL DEFAULT \'serif\' CHECK(font IN (\'serif\',\'sans\',\'rounded\')),
34 created INTEGER NOT NULL
35 );
36 CREATE TABLE IF NOT EXISTS sessions (id TEXT PRIMARY KEY, payload TEXT NOT NULL, expires INTEGER NOT NULL);
37 CREATE TABLE IF NOT EXISTS days (
38 id INTEGER PRIMARY KEY AUTOINCREMENT,
39 date TEXT NOT NULL UNIQUE,
40 title TEXT NOT NULL,
41 created INTEGER NOT NULL,
42 updated INTEGER NOT NULL
43 );
44 CREATE TABLE IF NOT EXISTS stories (
45 id INTEGER PRIMARY KEY AUTOINCREMENT,
46 day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
47 position INTEGER NOT NULL CHECK(position BETWEEN 1 AND 3),
48 title TEXT NOT NULL,
49 created INTEGER NOT NULL,
50 updated INTEGER NOT NULL,
51 UNIQUE(day_id, position)
52 );
53 CREATE TABLE IF NOT EXISTS paragraphs (
54 id INTEGER PRIMARY KEY AUTOINCREMENT,
55 story_id INTEGER NOT NULL REFERENCES stories(id) ON DELETE CASCADE,
56 position INTEGER NOT NULL CHECK(position >= 1),
57 body TEXT NOT NULL,
58 UNIQUE(story_id, position)
59 );
60 CREATE TABLE IF NOT EXISTS reads (
61 user_id TEXT NOT NULL REFERENCES users(id),
62 day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
63 read_at INTEGER NOT NULL,
64 PRIMARY KEY(user_id, day_id)
65 );
66 CREATE TABLE IF NOT EXISTS api_keys (
67 id INTEGER PRIMARY KEY AUTOINCREMENT,
68 user_id TEXT NOT NULL REFERENCES users(id),
69 name TEXT NOT NULL,
70 token_hash TEXT NOT NULL UNIQUE,
71 token_prefix TEXT NOT NULL,
72 token_cipher TEXT NOT NULL DEFAULT \'\',
73 created INTEGER NOT NULL,
74 revoked INTEGER
75 );');
76 $columns = array_column($db->query('PRAGMA table_info(api_keys)')->fetchAll(), 'name');
77 if (!in_array('token_cipher', $columns, true)) {
78 $db->exec("ALTER TABLE api_keys ADD COLUMN token_cipher TEXT NOT NULL DEFAULT ''");
79 }
80 return $db;
81}
82
83function query(string $sql, array $args = []): PDOStatement {
84 $statement = db()->prepare($sql);
85 $statement->execute($args);
86 return $statement;
87}
88
89final class DatabaseSessions implements SessionHandlerInterface {
90 public function open(string $path, string $name): bool { return true; }
91 public function close(): bool { return true; }
92 public function read(string $id): string|false {
93 return query('SELECT payload FROM sessions WHERE id=? AND expires>?', [$id, time()])->fetchColumn() ?: '';
94 }
95 public function write(string $id, string $data): bool {
96 query('INSERT OR REPLACE INTO sessions (id, payload, expires) VALUES (?,?,?)', [$id, $data, time() + 86400]);
97 return true;
98 }
99 public function destroy(string $id): bool {
100 query('DELETE FROM sessions WHERE id=?', [$id]);
101 return true;
102 }
103 public function gc(int $max_lifetime): int|false {
104 return query('DELETE FROM sessions WHERE expires<?', [time()])->rowCount();
105 }
106}
107
108function localDev(): bool {
109 $host = parse_url('http://'.($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
110 return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
111 && in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
112}
113
114function config(): array {
115 $dir = dataDir();
116 $path = $dir.'/config.php';
117 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
118 $lock = fopen($dir.'/config.lock', 'c');
119 if ($lock === false) throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
120 try {
121 if (!flock($lock, LOCK_EX)) throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
122 if (!file_exists($path)) {
123 $secret = bin2hex(random_bytes(32));
124 $template = <<<PHP
125<?php
126// Vul deze waarden op deze server in. Lege velden gebruiken omgevingsvariabelen.
127// Productie-URL: https://projects.timfalken.com/verhaaltjesboek
128// client_id is het geregistreerde domein, meestal projects.timfalken.com.
129// Het geheim komt uit https://auth.timfalken.com/admin en hoort alleen in dit bestand.
130// key_secret versleutelt API-sleutels zodat een beheerder ze opnieuw kan tonen. Laat die staan.
131return [
132 'base_url' => '',
133 'client_id' => '',
134 'client_secret' => '',
135 'key_secret' => '$secret',
136];
137
138PHP;
139 if (file_put_contents($path, $template) !== strlen($template)) throw new RuntimeException('data/config.php kon niet worden gemaakt.');
140 }
141 $values = require $path;
142 if (!is_array($values)) throw new RuntimeException('data/config.php moet een array teruggeven.');
143 $values = ensureKeySecret($path, $values);
144 } finally {
145 flock($lock, LOCK_UN);
146 fclose($lock);
147 }
148 foreach (['base_url' => 'VERHALENBOEK_BASE_URL', 'client_id' => 'VERHALENBOEK_CLIENT_ID', 'client_secret' => 'VERHALENBOEK_CLIENT_SECRET'] as $key => $env) {
149 if (($values[$key] ?? '') === '') $values[$key] = getenv($env) ?: '';
150 }
151 return $values;
152}
153
154function ensureKeySecret(string $path, array $values): array {
155 $secret = $values['key_secret'] ?? '';
156 if (is_string($secret) && preg_match('/^[a-f0-9]{64}$/', $secret)) return $values;
157 $secret = bin2hex(random_bytes(32));
158 $values['key_secret'] = $secret;
159 $raw = file_get_contents($path);
160 if (!is_string($raw)) throw new RuntimeException('data/config.php kon niet worden gelezen.');
161 if (preg_match("/'key_secret'\\s*=>\\s*'[^']*'/", $raw)) {
162 $updated = preg_replace("/'key_secret'\\s*=>\\s*'[^']*'/", "'key_secret' => '".$secret."'", $raw, 1);
163 } else {
164 $updated = preg_replace("/(\\r?\\n)(\\];)/", "$1 'key_secret' => '".$secret."',$1$2", $raw, 1);
165 }
166 if (!is_string($updated) || !str_contains($updated, $secret) || file_put_contents($path, $updated) !== strlen($updated)) {
167 throw new RuntimeException('key_secret kon niet in data/config.php worden gezet.');
168 }
169 return $values;
170}
171
172function authPublicBase(): string {
173 if (localDev()) return baseUrl();
174 $base = rtrim((string)(config()['base_url'] ?? ''), '/');
175 if (str_starts_with($base, 'https://')) return $base;
176 $env = getenv('VERHALENBOEK_BASE_URL');
177 if (is_string($env) && str_starts_with($env = rtrim($env, '/'), 'https://')) return $env;
178 return '';
179}
180
181function authHint(string $kind): string {
182 $base = authPublicBase();
183 $keys = ($base !== '' ? $base : '').'/#/sleutels';
184 $docs = ($base !== '' ? $base.'/' : '').'docs.php';
185 $how = 'Stuur de header Authorization: Bearer vb_… met een API-sleutel. Een beheerder maakt sleutels aan onder Sleutels op '.$keys.'. Uitleg: '.$docs;
186 return match ($kind) {
187 'missing' => 'Er is geen Authorization-header. '.$how,
188 'format' => 'De Authorization-header heeft het verkeerde formaat. Gebruik Bearer, gevolgd door vb_ en 64 hexadecimale tekens. '.$how,
189 'rejected' => 'Deze API-sleutel is onbekend of ingetrokken. '.$how,
190 'writer' => 'Dit mag alleen met een API-sleutel of als beheerder. '.$how,
191 'admin' => 'Sleutels beheren kan alleen als ingelogde beheerder, niet met een API-sleutel. Open Sleutels op '.$keys.'. Uitleg: '.$docs,
192 'users' => 'Gebruikers beheren kan alleen als ingelogde beheerder, niet met een API-sleutel. Open Beheer op '.($base !== '' ? $base : '').'/#/beheer. Uitleg: '.$docs,
193 default => $how,
194 };
195}
196
197function baseUrl(): string {
198 if (localDev()) {
199 $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
200 if ($dir === '/' || $dir === '.') $dir = '';
201 return 'http://'.$_SERVER['HTTP_HOST'].$dir;
202 }
203 $base = rtrim((string)config()['base_url'], '/');
204 if (!str_starts_with($base, 'https://')) throw new RuntimeException("Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie, of zet VERHALENBOEK_BASE_URL. De datamap wordt niet meegedeployed.");
205 return $base;
206}
207
208function assetVersion(): string {
209 static $version;
210 if ($version !== null) return $version;
211 $file = dirname(__DIR__).'/asset-version.txt';
212 if (is_readable($file)) {
213 $hash = trim((string)file_get_contents($file));
214 if ($hash !== '' && preg_match('/^[0-9a-f]{7,64}$/i', $hash)) return $version = $hash;
215 }
216 $env = getenv('CI_COMMIT_SHA') ?: getenv('VERHALENBOEK_ASSET_VERSION') ?: '';
217 if (is_string($env) && preg_match('/^[0-9a-f]{7,64}$/i', trim($env))) return $version = trim($env);
218 $git = dirname(__DIR__, 2).'/.git';
219 if (is_dir($git)) {
220 $out = @shell_exec('git -C '.escapeshellarg(dirname($git)).' rev-parse HEAD 2>/dev/null');
221 if (is_string($out) && preg_match('/^[0-9a-f]{7,64}$/i', trim($out))) return $version = trim($out);
222 }
223 $js = dirname(__DIR__).'/assets/app.js';
224 return $version = is_file($js) ? (string)filemtime($js) : '0';
225}
226
227function assetUrl(string $path): string {
228 $path = ltrim($path, '/');
229 $version = rawurlencode(assetVersion());
230 return str_contains($path, '?') ? $path.'&v='.$version : $path.'?v='.$version;
231}
232
233function pwaHead(): void {
234 $icon = htmlspecialchars(assetUrl('assets/favicon.svg'), ENT_QUOTES);
235 $png32 = htmlspecialchars(assetUrl('assets/favicon-32.png'), ENT_QUOTES);
236 $png16 = htmlspecialchars(assetUrl('assets/favicon-16.png'), ENT_QUOTES);
237 $mask = htmlspecialchars(assetUrl('assets/mask-icon.svg'), ENT_QUOTES);
238 $script = htmlspecialchars(assetUrl('assets/pwa.js'), ENT_QUOTES);
239 echo <<<HTML
240<link rel="icon" href="{$icon}" type="image/svg+xml" sizes="any">
241<link rel="icon" href="{$png32}" type="image/png" sizes="32x32">
242<link rel="icon" href="{$png16}" type="image/png" sizes="16x16">
243<link rel="apple-touch-icon" href="assets/apple-touch-icon.png" sizes="180x180">
244<link rel="manifest" href="manifest.webmanifest">
245<link rel="mask-icon" href="{$mask}" color="#3a5fc8">
246<meta name="mobile-web-app-capable" content="yes">
247<meta name="apple-mobile-web-app-capable" content="yes">
248<meta name="apple-mobile-web-app-title" content="Verhalenboek">
249<meta name="apple-mobile-web-app-status-bar-style" content="default">
250<script src="{$script}"></script>
251
252HTML;
253}
254
255function authRequest(string $path, ?array $form = null, ?string $token = null): array {
256 $ch=curl_init('https://auth.timfalken.com'.$path);
257 $headers = ['Accept: application/json', 'User-Agent: Verhalenboek/1.0'];
258 if ($token) $headers[] = 'Authorization: Bearer '.$token;
259 curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => $headers]);
260 if ($form !== null) curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
261 $body = curl_exec($ch);
262 $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
263 curl_close($ch);
264 $data = is_string($body) ? json_decode($body, true) : null;
265 if ($status !== 200 || !is_array($data)) throw new RuntimeException('De authenticatiedienst is niet bereikbaar of de sessie is verlopen. Log opnieuw in.');
266 return $data;
267}
268
269/** @return array{0:string,1:string} */
270function authIdentity(array $profile): array {
271 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
272 throw new RuntimeException('Het accountantwoord mist een id of gebruikersnaam.');
273 }
274 $raw = $profile['id'];
275 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
276 if (!$numeric || (int)$raw < 1) throw new RuntimeException('Ongeldig account-id.');
277 return ['auth:'.(int)$raw, $profile['username']];
278}
279
280function loginUser(string $id, string $name): void {
281 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) throw new RuntimeException('Ongeldig account.');
282 $name = trim($name);
283 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) throw new RuntimeException('Ongeldige gebruikersnaam.');
284 transaction(function () use ($id, $name): void {
285 $existing = query('SELECT id FROM users WHERE id=?', [$id])->fetch();
286 if ($existing) {
287 query('UPDATE users SET name=? WHERE id=?', [$name, $id]);
288 return;
289 }
290 $count = (int)query('SELECT COUNT(*) FROM users')->fetchColumn();
291 query('INSERT INTO users (id, name, role, theme, font, created) VALUES (?,?,?,?,?,?)', [
292 $id, $name, $count === 0 ? 'admin' : 'user', 'system', 'serif', time(),
293 ]);
294 });
295 session_regenerate_id(true);
296 $_SESSION['user'] = $id;
297 $_SESSION['csrf'] = bin2hex(random_bytes(24));
298}
299
300config();
301session_name('verhalenboek_session');
302ini_set('session.use_strict_mode', '1');
303$sessionLifetime = 86400;
304$sessionPath = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/').'/';
305if ($sessionPath === '//') $sessionPath = '/';
306$sessionSecure = !localDev();
307session_set_cookie_params(['lifetime' => $sessionLifetime, 'path' => $sessionPath, 'secure' => $sessionSecure, 'httponly' => true, 'samesite' => 'Lax']);
308session_set_save_handler(new DatabaseSessions(), true);
309session_start();
310if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
311 setcookie(session_name(), session_id(), [
312 'expires' => time() + $sessionLifetime,
313 'path' => $sessionPath,
314 'secure' => $sessionSecure,
315 'httponly' => true,
316 'samesite' => 'Lax',
317 ]);
318}
319if (localDev() && !in_array($_SESSION['user'] ?? '', ['local:test_user_1', 'local:test_user_2'], true)) {
320 unset($_SESSION['token'], $_SESSION['expires'], $_SESSION['validated']);
321 loginUser('local:test_user_1', 'test_user_1');
322}
323
324function user(): string {
325 if (!isset($_SESSION['user'])) fail('Log in om verder te gaan.', 401, 'missing');
326 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
327 unset($_SESSION['user']);
328 fail('Je sessie is verlopen. Log opnieuw in.', 401, 'missing');
329 }
330 return $_SESSION['user'];
331}
332
333function fail(string $message, int $status = 400, ?string $auth = null): never {
334 http_response_code($status);
335 header('Content-Type: application/json; charset=utf-8');
336 $body = ['error' => $message];
337 if ($auth !== null) {
338 $body['how_to_authenticate'] = authHint($auth);
339 $body['hint'] = $body['how_to_authenticate'];
340 if ($status === 401) header('WWW-Authenticate: Bearer');
341 }
342 echo json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
343 exit;
344}
345
346function jsonOut(mixed $data, int $status = 200): never {
347 http_response_code($status);
348 header('Content-Type: application/json; charset=utf-8');
349 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
350 exit;
351}
352
353function bearerToken(): ?string {
354 $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
355 if ($header === '' && function_exists('getallheaders')) {
356 $headers = getallheaders();
357 if (is_array($headers)) {
358 foreach ($headers as $name => $value) {
359 if (strcasecmp((string)$name, 'Authorization') === 0) { $header = (string)$value; break; }
360 }
361 }
362 }
363 if ($header === '') return null;
364 if (preg_match('/^Bearer\s+(\S+)\s*$/i', $header, $match)) return $match[1];
365 throw new AppException('De Authorization-header heeft het verkeerde formaat.', 401, 'format');
366}
367
368function authenticate(): array {
369 $token = bearerToken();
370 if ($token !== null) return actorFromToken($token);
371 $id = user();
372 if (!localDev() && time() - ($_SESSION['validated'] ?? 0) > 60) {
373 try {
374 authRequest('/api/me', null, (string)($_SESSION['token'] ?? ''));
375 if (($_SESSION['expires'] ?? 0) - time() < 900) {
376 $extended = authRequest('/api/session/extend', [], (string)$_SESSION['token']);
377 $_SESSION['expires'] = time() + (int)$extended['expires_in'];
378 }
379 $_SESSION['validated'] = time();
380 } catch (Throwable $e) {
381 unset($_SESSION['user']);
382 fail('Log opnieuw in.', 401, 'missing');
383 }
384 }
385 $row = query('SELECT id, role FROM users WHERE id=?', [$id])->fetch();
386 if (!$row) fail('Log opnieuw in.', 401, 'missing');
387 return ['kind' => 'user', 'userId' => $row['id'], 'role' => $row['role']];
388}
389
390function requireCsrf(array $actor): void {
391 if ($actor['kind'] === 'token') return;
392 $sent = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
393 $expected = $_SESSION['csrf'] ?? '';
394 if (!is_string($sent) || !is_string($expected) || $expected === '' || !hash_equals($expected, $sent)) {
395 fail('Ongeldige sessie. Laad de pagina opnieuw.', 403);
396 }
397}
398
399function requireWriter(array $actor): void {
400 if ($actor['kind'] === 'token') return;
401 if (($actor['role'] ?? '') !== 'admin') fail('Alleen een beheerder mag dit wijzigen.', 403, 'writer');
402}
403
404function requireAdminSession(array $actor, string $message = 'Alleen een beheerder mag sleutels beheren.', string $auth = 'admin'): void {
405 if ($actor['kind'] !== 'user' || ($actor['role'] ?? '') !== 'admin') fail($message, 403, $auth);
406}
407
408function requireReader(array $actor): void {
409 if ($actor['kind'] !== 'user') fail('Leesstatus hoort bij een ingelogde lezer.', 403);
410}
411
412function readJson(): array {
413 $raw = file_get_contents('php://input');
414 if ($raw === false || trim($raw) === '') throw new AppException('De aanvraag heeft een JSON-object nodig.');
415 try {
416 $data = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
417 } catch (JsonException) {
418 throw new AppException('De JSON is ongeldig.');
419 }
420 if (!is_array($data) || array_is_list($data)) throw new AppException('De JSON moet een object zijn.');
421 return $data;
422}
423
424function apiRoute(): string {
425 $candidates = [];
426 $info = $_SERVER['PATH_INFO'] ?? '';
427 if (is_string($info) && $info !== '') $candidates[] = $info;
428 $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
429 if (preg_match('#/api\.php(/.*)$#', $uri, $match)) $candidates[] = $match[1];
430 foreach ($candidates as $candidate) {
431 $candidate = '/'.trim((string)$candidate, '/');
432 if ($candidate !== '/') return $candidate;
433 }
434 return '/';
435}