BlueGit

projects-timfalken-com verhalenboek

Files

verhalenboek / web / lib / bootstrap.php

bootstrap.php

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