BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / lib / bootstrap.php

bootstrap.php

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