BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / lib / bootstrap.php

bootstrap.php

feat: laat een beheerder andere gebruikers promoveren
timfa project_87242033_bot_b167a9be22027ad5a4b431d0ad8426c6 · pushed by timfa · 6 weeks ago
1d95d234 History
bootstrap.php 18.3 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 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 authRequest(string $path, ?array $form = null, ?string $token = null): array {
234 $ch=curl_init('https://auth.timfalken.com'.$path);
235 $headers = ['Accept: application/json', 'User-Agent: Verhalenboek/1.0'];
236 if ($token) $headers[] = 'Authorization: Bearer '.$token;
237 curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_TIMEOUT => 15, CURLOPT_HTTPHEADER => $headers]);
238 if ($form !== null) curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
239 $body = curl_exec($ch);
240 $status = (int)curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
241 curl_close($ch);
242 $data = is_string($body) ? json_decode($body, true) : null;
243 if ($status !== 200 || !is_array($data)) throw new RuntimeException('De authenticatiedienst is niet bereikbaar of de sessie is verlopen. Log opnieuw in.');
244 return $data;
245}
246
247/** @return array{0:string,1:string} */
248function authIdentity(array $profile): array {
249 if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
250 throw new RuntimeException('Het accountantwoord mist een id of gebruikersnaam.');
251 }
252 $raw = $profile['id'];
253 $numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
254 if (!$numeric || (int)$raw < 1) throw new RuntimeException('Ongeldig account-id.');
255 return ['auth:'.(int)$raw, $profile['username']];
256}
257
258function loginUser(string $id, string $name): void {
259 if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) throw new RuntimeException('Ongeldig account.');
260 $name = trim($name);
261 if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) throw new RuntimeException('Ongeldige gebruikersnaam.');
262 transaction(function () use ($id, $name): void {
263 $existing = query('SELECT id FROM users WHERE id=?', [$id])->fetch();
264 if ($existing) {
265 query('UPDATE users SET name=? WHERE id=?', [$name, $id]);
266 return;
267 }
268 $count = (int)query('SELECT COUNT(*) FROM users')->fetchColumn();
269 query('INSERT INTO users (id, name, role, theme, font, created) VALUES (?,?,?,?,?,?)', [
270 $id, $name, $count === 0 ? 'admin' : 'user', 'system', 'serif', time(),
271 ]);
272 });
273 session_regenerate_id(true);
274 $_SESSION['user'] = $id;
275 $_SESSION['csrf'] = bin2hex(random_bytes(24));
276}
277
278config();
279session_name('verhalenboek_session');
280ini_set('session.use_strict_mode', '1');
281$sessionLifetime = 86400;
282$sessionPath = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/').'/';
283if ($sessionPath === '//') $sessionPath = '/';
284$sessionSecure = !localDev();
285session_set_cookie_params(['lifetime' => $sessionLifetime, 'path' => $sessionPath, 'secure' => $sessionSecure, 'httponly' => true, 'samesite' => 'Lax']);
286session_set_save_handler(new DatabaseSessions(), true);
287session_start();
288if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
289 setcookie(session_name(), session_id(), [
290 'expires' => time() + $sessionLifetime,
291 'path' => $sessionPath,
292 'secure' => $sessionSecure,
293 'httponly' => true,
294 'samesite' => 'Lax',
295 ]);
296}
297if (localDev() && !in_array($_SESSION['user'] ?? '', ['local:test_user_1', 'local:test_user_2'], true)) {
298 unset($_SESSION['token'], $_SESSION['expires'], $_SESSION['validated']);
299 loginUser('local:test_user_1', 'test_user_1');
300}
301
302function user(): string {
303 if (!isset($_SESSION['user'])) fail('Log in om verder te gaan.', 401, 'missing');
304 if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
305 unset($_SESSION['user']);
306 fail('Je sessie is verlopen. Log opnieuw in.', 401, 'missing');
307 }
308 return $_SESSION['user'];
309}
310
311function fail(string $message, int $status = 400, ?string $auth = null): never {
312 http_response_code($status);
313 header('Content-Type: application/json; charset=utf-8');
314 $body = ['error' => $message];
315 if ($auth !== null) {
316 $body['how_to_authenticate'] = authHint($auth);
317 $body['hint'] = $body['how_to_authenticate'];
318 if ($status === 401) header('WWW-Authenticate: Bearer');
319 }
320 echo json_encode($body, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
321 exit;
322}
323
324function jsonOut(mixed $data, int $status = 200): never {
325 http_response_code($status);
326 header('Content-Type: application/json; charset=utf-8');
327 echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR);
328 exit;
329}
330
331function bearerToken(): ?string {
332 $header = $_SERVER['HTTP_AUTHORIZATION'] ?? $_SERVER['REDIRECT_HTTP_AUTHORIZATION'] ?? '';
333 if ($header === '' && function_exists('getallheaders')) {
334 $headers = getallheaders();
335 if (is_array($headers)) {
336 foreach ($headers as $name => $value) {
337 if (strcasecmp((string)$name, 'Authorization') === 0) { $header = (string)$value; break; }
338 }
339 }
340 }
341 if ($header === '') return null;
342 if (preg_match('/^Bearer\s+(\S+)\s*$/i', $header, $match)) return $match[1];
343 throw new AppException('De Authorization-header heeft het verkeerde formaat.', 401, 'format');
344}
345
346function authenticate(): array {
347 $token = bearerToken();
348 if ($token !== null) return actorFromToken($token);
349 $id = user();
350 if (!localDev() && time() - ($_SESSION['validated'] ?? 0) > 60) {
351 try {
352 authRequest('/api/me', null, (string)($_SESSION['token'] ?? ''));
353 if (($_SESSION['expires'] ?? 0) - time() < 900) {
354 $extended = authRequest('/api/session/extend', [], (string)$_SESSION['token']);
355 $_SESSION['expires'] = time() + (int)$extended['expires_in'];
356 }
357 $_SESSION['validated'] = time();
358 } catch (Throwable $e) {
359 unset($_SESSION['user']);
360 fail('Log opnieuw in.', 401, 'missing');
361 }
362 }
363 $row = query('SELECT id, role FROM users WHERE id=?', [$id])->fetch();
364 if (!$row) fail('Log opnieuw in.', 401, 'missing');
365 return ['kind' => 'user', 'userId' => $row['id'], 'role' => $row['role']];
366}
367
368function requireCsrf(array $actor): void {
369 if ($actor['kind'] === 'token') return;
370 $sent = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
371 $expected = $_SESSION['csrf'] ?? '';
372 if (!is_string($sent) || !is_string($expected) || $expected === '' || !hash_equals($expected, $sent)) {
373 fail('Ongeldige sessie. Laad de pagina opnieuw.', 403);
374 }
375}
376
377function requireWriter(array $actor): void {
378 if ($actor['kind'] === 'token') return;
379 if (($actor['role'] ?? '') !== 'admin') fail('Alleen een beheerder mag dit wijzigen.', 403, 'writer');
380}
381
382function requireAdminSession(array $actor, string $message = 'Alleen een beheerder mag sleutels beheren.', string $auth = 'admin'): void {
383 if ($actor['kind'] !== 'user' || ($actor['role'] ?? '') !== 'admin') fail($message, 403, $auth);
384}
385
386function requireReader(array $actor): void {
387 if ($actor['kind'] !== 'user') fail('Leesstatus hoort bij een ingelogde lezer.', 403);
388}
389
390function readJson(): array {
391 $raw = file_get_contents('php://input');
392 if ($raw === false || trim($raw) === '') throw new AppException('De aanvraag heeft een JSON-object nodig.');
393 try {
394 $data = json_decode($raw, true, 64, JSON_THROW_ON_ERROR);
395 } catch (JsonException) {
396 throw new AppException('De JSON is ongeldig.');
397 }
398 if (!is_array($data) || array_is_list($data)) throw new AppException('De JSON moet een object zijn.');
399 return $data;
400}
401
402function apiRoute(): string {
403 $candidates = [];
404 $info = $_SERVER['PATH_INFO'] ?? '';
405 if (is_string($info) && $info !== '') $candidates[] = $info;
406 $uri = rawurldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/');
407 if (preg_match('#/api\.php(/.*)$#', $uri, $match)) $candidates[] = $match[1];
408 foreach ($candidates as $candidate) {
409 $candidate = '/'.trim((string)$candidate, '/');
410 if ($candidate !== '/') return $candidate;
411 }
412 return '/';
413}