BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / lib / bootstrap.php

bootstrap.php

feat: voeg Verhalenboek toe met dagen, leesvoortgang en schrijf-API
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 6 weeks ago
799da657 History
bootstrap.php 15.1 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'; 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 created INTEGER NOT NULL,
73 revoked INTEGER
74 );');
75 return $db;
76}
77
78function query(string $sql, array $args = []): PDOStatement {
79 $statement = db()->prepare($sql);
80 $statement->execute($args);
81 return $statement;
82}
83
84final class DatabaseSessions implements SessionHandlerInterface {
85 public function open(string $path, string $name): bool { return true; }
86 public function close(): bool { return true; }
87 public function read(string $id): string|false {
88 return query('SELECT payload FROM sessions WHERE id=? AND expires>?', [$id, time()])->fetchColumn() ?: '';
89 }
90 public function write(string $id, string $data): bool {
91 query('INSERT OR REPLACE INTO sessions (id, payload, expires) VALUES (?,?,?)', [$id, $data, time() + 86400]);
92 return true;
93 }
94 public function destroy(string $id): bool {
95 query('DELETE FROM sessions WHERE id=?', [$id]);
96 return true;
97 }
98 public function gc(int $max_lifetime): int|false {
99 return query('DELETE FROM sessions WHERE expires<?', [time()])->rowCount();
100 }
101}
102
103function localDev(): bool {
104 $host = parse_url('http://'.($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
105 return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
106 && in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
107}
108
109function config(): array {
110 $dir = dataDir();
111 $path = $dir.'/config.php';
112 if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
113 $lock = fopen($dir.'/config.lock', 'c');
114 if ($lock === false) throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
115 try {
116 if (!flock($lock, LOCK_EX)) throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
117 if (!file_exists($path)) {
118 $template = <<<'PHP'
119<?php
120// Vul deze waarden op deze server in. Lege velden gebruiken omgevingsvariabelen.
121// Productie-URL: https://projects.timfalken.com/verhaaltjesboek
122// client_id is het geregistreerde domein, meestal projects.timfalken.com.
123// Het geheim komt uit https://auth.timfalken.com/admin en hoort alleen in dit bestand.
124return [
125 'base_url' => '',
126 'client_id' => '',
127 'client_secret' => '',
128];
129
130PHP;
131 if (file_put_contents($path, $template) !== strlen($template)) throw new RuntimeException('data/config.php kon niet worden gemaakt.');
132 }
133 $values = require $path;
134 if (!is_array($values)) throw new RuntimeException('data/config.php moet een array teruggeven.');
135 } finally {
136 flock($lock, LOCK_UN);
137 fclose($lock);
138 }
139 foreach (['base_url' => 'VERHALENBOEK_BASE_URL', 'client_id' => 'VERHALENBOEK_CLIENT_ID', 'client_secret' => 'VERHALENBOEK_CLIENT_SECRET'] as $key => $env) {
140 if (($values[$key] ?? '') === '') $values[$key] = getenv($env) ?: '';
141 }
142 return $values;
143}
144
145function baseUrl(): string {
146 if (localDev()) {
147 $dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
148 if ($dir === '/' || $dir === '.') $dir = '';
149 return 'http://'.$_SERVER['HTTP_HOST'].$dir;
150 }
151 $base = rtrim((string)config()['base_url'], '/');
152 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.");
153 return $base;
154}
155
156function assetVersion(): string {
157 static $version;
158 if ($version !== null) return $version;
159 $file = dirname(__DIR__).'/asset-version.txt';
160 if (is_readable($file)) {
161 $hash = trim((string)file_get_contents($file));
162 if ($hash !== '' && preg_match('/^[0-9a-f]{7,64}$/i', $hash)) return $version = $hash;
163 }
164 $env = getenv('CI_COMMIT_SHA') ?: getenv('VERHALENBOEK_ASSET_VERSION') ?: '';
165 if (is_string($env) && preg_match('/^[0-9a-f]{7,64}$/i', trim($env))) return $version = trim($env);
166 $git = dirname(__DIR__, 2).'/.git';
167 if (is_dir($git)) {
168 $out = @shell_exec('git -C '.escapeshellarg(dirname($git)).' rev-parse HEAD 2>/dev/null');
169 if (is_string($out) && preg_match('/^[0-9a-f]{7,64}$/i', trim($out))) return $version = trim($out);
170 }
171 $js = dirname(__DIR__).'/assets/app.js';
172 return $version = is_file($js) ? (string)filemtime($js) : '0';
173}
174
175function assetUrl(string $path): string {
176 $path = ltrim($path, '/');
177 $version = rawurlencode(assetVersion());
178 return str_contains($path, '?') ? $path.'&v='.$version : $path.'?v='.$version;
179}
180
181function authRequest(string $path, ?array $form = null, ?string $token = null): array {
182 $ch=curl_init('https://auth.timfalken.com'.$path);
183 $headers = ['Accept: application/json', 'User-Agent: Verhalenboek/1.0'];
184 if ($token) $headers[] = 'Authorization: Bearer '.$token;
185 curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => $headers]);
186 if ($form !== null) curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
187 $body = curl_exec($ch);
188 $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
189 curl_close($ch);
190 $data = is_string($body) ? json_decode($body, true) : null;
191 if ($status !== 200 || !is_array($data)) throw new RuntimeException('De authenticatiedienst is niet bereikbaar of de sessie is verlopen. Log opnieuw in.');
192 return $data;
193}
194
195/** @return array{0:string,1:string} */
196function authIdentity(array $profile): array {
197 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
198 throw new RuntimeException('Het accountantwoord mist een id of gebruikersnaam.');
199 }
200 $raw = $profile['id'];
201 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
202 if (!$numeric || (int)$raw < 1) throw new RuntimeException('Ongeldig account-id.');
203 return ['auth:'.(int)$raw, $profile['username']];
204}
205
206function loginUser(string $id, string $name): void {
207 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) throw new RuntimeException('Ongeldig account.');
208 $name = trim($name);
209 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) throw new RuntimeException('Ongeldige gebruikersnaam.');
210 transaction(function () use ($id, $name): void {
211 $existing = query('SELECT id FROM users WHERE id=?', [$id])->fetch();
212 if ($existing) {
213 query('UPDATE users SET name=? WHERE id=?', [$name, $id]);
214 return;
215 }
216 $count = (int)query('SELECT COUNT(*) FROM users')->fetchColumn();
217 query('INSERT INTO users (id, name, role, theme, font, created) VALUES (?,?,?,?,?,?)', [
218 $id, $name, $count === 0 ? 'admin' : 'user', 'system', 'serif', time(),
219 ]);
220 });
221 session_regenerate_id(true);
222 $_SESSION['user'] = $id;
223 $_SESSION['csrf'] = bin2hex(random_bytes(24));
224}
225
226config();
227session_name('verhalenboek_session');
228ini_set('session.use_strict_mode', '1');
229$sessionLifetime = 86400;
230$sessionPath = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/').'/';
231if ($sessionPath === '//') $sessionPath = '/';
232$sessionSecure = !localDev();
233session_set_cookie_params(['lifetime' => $sessionLifetime, 'path' => $sessionPath, 'secure' => $sessionSecure, 'httponly' => true, 'samesite' => 'Lax']);
234session_set_save_handler(new DatabaseSessions(), true);
235session_start();
236if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
237 setcookie(session_name(), session_id(), [
238 'expires' => time() + $sessionLifetime,
239 'path' => $sessionPath,
240 'secure' => $sessionSecure,
241 'httponly' => true,
242 'samesite' => 'Lax',
243 ]);
244}
245if (localDev() && !in_array($_SESSION['user'] ?? '', ['local:test_user_1', 'local:test_user_2'], true)) {
246 unset($_SESSION['token'], $_SESSION['expires'], $_SESSION['validated']);
247 loginUser('local:test_user_1', 'test_user_1');
248}
249
250function user(): string {
251 if (!isset($_SESSION['user'])) fail('Log in om verder te gaan.', 401);
252 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
253 unset($_SESSION['user']);
254 fail('Je sessie is verlopen. Log opnieuw in.', 401);
255 }
256 return $_SESSION['user'];
257}
258
259function fail(string $message, int $status = 400): never {
260 http_response_code($status);
261 header('Content-Type: application/json; charset=utf-8');
262 echo json_encode(['error' => $message], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
263 exit;
264}
265
266function jsonOut(mixed $data, int $status = 200): never {
267 http_response_code($status);
268 header('Content-Type: application/json; charset=utf-8');
269 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
270 exit;
271}
272
273function bearerToken(): ?string {
274 $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
275 if ($header === '' && function_exists('getallheaders')) {
276 $headers = getallheaders();
277 if (is_array($headers)) {
278 foreach ($headers as $name => $value) {
279 if (strcasecmp((string)$name, 'Authorization') === 0) { $header = (string)$value; break; }
280 }
281 }
282 }
283 if ($header === '') return null;
284 if (preg_match('/^Bearer\s+(\S+)\s*$/i', $header, $match)) return $match[1];
285 throw new AppException('De Authorization-header moet een Bearer-sleutel zijn.', 401);
286}
287
288function authenticate(): array {
289 $token = bearerToken();
290 if ($token !== null) return actorFromToken($token);
291 $id = user();
292 if (!localDev() && time() - ($_SESSION['validated'] ?? 0) > 60) {
293 try {
294 authRequest('/api/me', null, (string)($_SESSION['token'] ?? ''));
295 if (($_SESSION['expires'] ?? 0) - time() < 900) {
296 $extended = authRequest('/api/session/extend', [], (string)$_SESSION['token']);
297 $_SESSION['expires'] = time() + (int)$extended['expires_in'];
298 }
299 $_SESSION['validated'] = time();
300 } catch (Throwable $e) {
301 unset($_SESSION['user']);
302 fail('Log opnieuw in.', 401);
303 }
304 }
305 $row = query('SELECT id, role FROM users WHERE id=?', [$id])->fetch();
306 if (!$row) fail('Log opnieuw in.', 401);
307 return ['kind' => 'user', 'userId' => $row['id'], 'role' => $row['role']];
308}
309
310function requireCsrf(array $actor): void {
311 if ($actor['kind'] === 'token') return;
312 $sent = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
313 $expected = $_SESSION['csrf'] ?? '';
314 if (!is_string($sent) || !is_string($expected) || $expected === '' || !hash_equals($expected, $sent)) {
315 fail('Ongeldige sessie. Laad de pagina opnieuw.', 403);
316 }
317}
318
319function requireWriter(array $actor): void {
320 if ($actor['kind'] === 'token') return;
321 if (($actor['role'] ?? '') !== 'admin') fail('Alleen een beheerder mag dit wijzigen.', 403);
322}
323
324function requireAdminSession(array $actor): void {
325 if ($actor['kind'] !== 'user' || ($actor['role'] ?? '') !== 'admin') fail('Alleen een beheerder mag sleutels beheren.', 403);
326}
327
328function requireReader(array $actor): void {
329 if ($actor['kind'] !== 'user') fail('Leesstatus hoort bij een ingelogde lezer.', 403);
330}
331
332function readJson(): array {
333 $raw = file_get_contents('php://input');
334 if ($raw === false || trim($raw) === '') throw new AppException('De aanvraag heeft een JSON-object nodig.');
335 try {
336 $data = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
337 } catch (JsonException) {
338 throw new AppException('De JSON is ongeldig.');
339 }
340 if (!is_array($data) || array_is_list($data)) throw new AppException('De JSON moet een object zijn.');
341 return $data;
342}
343
344function apiRoute(): string {
345 $candidates = [];
346 $info = $_SERVER['PATH_INFO'] ?? '';
347 if (is_string($info) && $info !== '') $candidates[] = $info;
348 $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
349 if (preg_match('#/api\.php(/.*)$#', $uri, $match)) $candidates[] = $match[1];
350 foreach ($candidates as $candidate) {
351 $candidate = '/'.trim((string)$candidate, '/');
352 if ($candidate !== '/') return $candidate;
353 }
354 return '/';
355}