feat: PHP lobby and game API with OAuth and a 30% miss parameter
SQLite under data/ (never deployed). Auth follows verhalenboek: auth.timfalken.com authorization code, tokens stay on the server. Lobbies, ready, host start, snapshots, delayed garbage delivery, elimination, podium, and a 5s return to the lobby. Local loopback exposes test_user_1 and test_user_2. Until a client secret is set, the API reports configured=false so single-player can keep working.
@@ -0,0 +1,18 @@
1
Options -Indexes
2
DirectoryIndex index.html index.php
3
4
<FilesMatch "^(router\.php|README\.md)$">
5
Require all denied
6
</FilesMatch>
7
8
<IfModule mod_headers.c>
9
Header always set X-Content-Type-Options "nosniff"
10
Header always set Referrer-Policy "same-origin"
11
</IfModule>
12
13
# PHP endpoints should not be cached.
14
<IfModule mod_headers.c>
15
<FilesMatch "\.(php)$">
16
Header set Cache-Control "no-store"
17
</FilesMatch>
18
</IfModule>
@@ -0,0 +1,18 @@1
Options -Indexes2
DirectoryIndex index.html index.php3
4
<FilesMatch "^(router\.php|README\.md)$">5
Require all denied6
</FilesMatch>7
8
<IfModule mod_headers.c>9
Header always set X-Content-Type-Options "nosniff"10
Header always set Referrer-Policy "same-origin"11
</IfModule>12
13
# PHP endpoints should not be cached.14
<IfModule mod_headers.c>15
<FilesMatch "\.(php)$">16
Header set Cache-Control "no-store"17
</FilesMatch>18
</IfModule>@@ -0,0 +1,108 @@
1
<?php
2
declare(strict_types=1);
3
require __DIR__ . '/lib/bootstrap.php';
4
require __DIR__ . '/lib/Store.php';
5
6
$action = $_GET['action'] ?? $_POST['action'] ?? '';
7
if ($action === '') {
8
$body = readJsonBody();
9
$action = (string) ($body['action'] ?? '');
10
} else {
11
$body = readJsonBody();
12
}
13
14
try {
15
$configured = authConfigured();
16
$local = localDev();
17
$user = currentUser();
18
19
if ($action === 'me' || $action === '') {
20
$view = ['lobby' => null, 'incoming' => [], 'shot_results' => []];
21
if ($user) {
22
$view = Store::open()->viewFor($user['id']);
23
}
24
jsonOut([
25
'ok' => true,
26
'configured' => $configured,
27
'local' => $local,
28
'csrf' => csrfToken(),
29
'me' => $user,
30
'lobby' => $view['lobby'],
31
'incoming' => $view['incoming'],
32
'shot_results' => $view['shot_results'],
33
'miss_chance_default' => METEORS_DEFAULT_MISS,
34
'flight_duration' => METEORS_FLIGHT_DURATION,
35
'login_url' => 'auth.php',
36
'logout_url' => 'logout.php',
37
]);
38
}
39
40
if ($action === 'test_login') {
41
if (!localDev()) {
42
jsonFail('Niet beschikbaar.', 403);
43
}
44
requireCsrf();
45
$who = (string) ($body['user'] ?? $_GET['user'] ?? '');
46
if (!in_array($who, ['test_user_1', 'test_user_2'], true)) {
47
jsonFail('Onbekende testgebruiker.');
48
}
49
loginUser('local:' . $who, $who);
50
jsonOut(['ok' => true, 'me' => currentUser(), 'csrf' => csrfToken()]);
51
}
52
53
if (!$user && $action !== 'me') {
54
jsonFail('Log in om verder te gaan.', 401);
55
}
56
57
requireCsrf();
58
$store = Store::open();
59
$userId = $user['id'];
60
$name = $user['name'];
61
62
switch ($action) {
63
case 'lobby_create':
64
$miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;
65
$lobby = $store->createLobby($userId, $name, $miss);
66
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
67
68
case 'lobby_join':
69
$code = (string) ($body['code'] ?? '');
70
$lobby = $store->joinLobby($userId, $name, $code);
71
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
72
73
case 'lobby_leave':
74
$store->leaveLobby($userId);
75
jsonOut(['ok' => true, 'lobby' => null, 'csrf' => csrfToken()]);
76
77
case 'lobby_ready':
78
$ready = (bool) ($body['ready'] ?? true);
79
$lobby = $store->setReady($userId, $ready);
80
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
81
82
case 'lobby_start':
83
$lobby = $store->startGame($userId);
84
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);
85
86
case 'poll':
87
$snapshot = isset($body['snapshot']) && is_array($body['snapshot']) ? $body['snapshot'] : null;
88
$score = isset($body['score']) ? (int) $body['score'] : null;
89
$eliminated = !empty($body['eliminated']);
90
$outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];
91
$view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);
92
jsonOut([
93
'ok' => true,
94
'csrf' => csrfToken(),
95
'me' => $user,
96
'lobby' => $view['lobby'],
97
'incoming' => $view['incoming'],
98
'shot_results' => $view['shot_results'],
99
]);
100
101
default:
102
jsonFail('Onbekende actie.', 404);
103
}
104
} catch (RuntimeException $e) {
105
jsonFail($e->getMessage(), 400);
106
} catch (Throwable $e) {
107
jsonFail('Interne fout.', 500);
108
}
@@ -0,0 +1,108 @@1
<?php2
declare(strict_types=1);3
require __DIR__ . '/lib/bootstrap.php';4
require __DIR__ . '/lib/Store.php';5
6
$action = $_GET['action'] ?? $_POST['action'] ?? '';7
if ($action === '') {8
$body = readJsonBody();9
$action = (string) ($body['action'] ?? '');10
} else {11
$body = readJsonBody();12
}13
14
try {15
$configured = authConfigured();16
$local = localDev();17
$user = currentUser();18
19
if ($action === 'me' || $action === '') {20
$view = ['lobby' => null, 'incoming' => [], 'shot_results' => []];21
if ($user) {22
$view = Store::open()->viewFor($user['id']);23
}24
jsonOut([25
'ok' => true,26
'configured' => $configured,27
'local' => $local,28
'csrf' => csrfToken(),29
'me' => $user,30
'lobby' => $view['lobby'],31
'incoming' => $view['incoming'],32
'shot_results' => $view['shot_results'],33
'miss_chance_default' => METEORS_DEFAULT_MISS,34
'flight_duration' => METEORS_FLIGHT_DURATION,35
'login_url' => 'auth.php',36
'logout_url' => 'logout.php',37
]);38
}39
40
if ($action === 'test_login') {41
if (!localDev()) {42
jsonFail('Niet beschikbaar.', 403);43
}44
requireCsrf();45
$who = (string) ($body['user'] ?? $_GET['user'] ?? '');46
if (!in_array($who, ['test_user_1', 'test_user_2'], true)) {47
jsonFail('Onbekende testgebruiker.');48
}49
loginUser('local:' . $who, $who);50
jsonOut(['ok' => true, 'me' => currentUser(), 'csrf' => csrfToken()]);51
}52
53
if (!$user && $action !== 'me') {54
jsonFail('Log in om verder te gaan.', 401);55
}56
57
requireCsrf();58
$store = Store::open();59
$userId = $user['id'];60
$name = $user['name'];61
62
switch ($action) {63
case 'lobby_create':64
$miss = isset($body['miss_chance']) ? (float) $body['miss_chance'] : METEORS_DEFAULT_MISS;65
$lobby = $store->createLobby($userId, $name, $miss);66
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);67
68
case 'lobby_join':69
$code = (string) ($body['code'] ?? '');70
$lobby = $store->joinLobby($userId, $name, $code);71
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);72
73
case 'lobby_leave':74
$store->leaveLobby($userId);75
jsonOut(['ok' => true, 'lobby' => null, 'csrf' => csrfToken()]);76
77
case 'lobby_ready':78
$ready = (bool) ($body['ready'] ?? true);79
$lobby = $store->setReady($userId, $ready);80
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);81
82
case 'lobby_start':83
$lobby = $store->startGame($userId);84
jsonOut(['ok' => true, 'lobby' => $store->presentLobby($lobby, $userId), 'csrf' => csrfToken()]);85
86
case 'poll':87
$snapshot = isset($body['snapshot']) && is_array($body['snapshot']) ? $body['snapshot'] : null;88
$score = isset($body['score']) ? (int) $body['score'] : null;89
$eliminated = !empty($body['eliminated']);90
$outgoing = isset($body['outgoing_shots']) && is_array($body['outgoing_shots']) ? $body['outgoing_shots'] : [];91
$view = $store->viewFor($userId, $snapshot, $score, $eliminated, $outgoing);92
jsonOut([93
'ok' => true,94
'csrf' => csrfToken(),95
'me' => $user,96
'lobby' => $view['lobby'],97
'incoming' => $view['incoming'],98
'shot_results' => $view['shot_results'],99
]);100
101
default:102
jsonFail('Onbekende actie.', 404);103
}104
} catch (RuntimeException $e) {105
jsonFail($e->getMessage(), 400);106
} catch (Throwable $e) {107
jsonFail('Interne fout.', 500);108
}@@ -0,0 +1,32 @@
1
<?php
2
declare(strict_types=1);
3
require __DIR__ . '/lib/bootstrap.php';
4
5
try {
6
if (localDev() && isset($_GET['test'])) {
7
$who = $_GET['test'] === '2' ? 'test_user_2' : 'test_user_1';
8
loginUser('local:' . $who, $who);
9
$next = isset($_GET['next']) && is_string($_GET['next']) ? $_GET['next'] : 'index.html';
10
header('Location: ' . $next);
11
exit;
12
}
13
if (!authConfigured()) {
14
header('Location: index.html?auth=unconfigured');
15
exit;
16
}
17
$cfg = config();
18
$_SESSION['oauth_state'] = bin2hex(random_bytes(32));
19
$_SESSION['oauth_started'] = time();
20
header('Location: ' . authUrl() . '/oauth/authorize?' . http_build_query([
21
'client_id' => $cfg['client_id'],
22
'redirect_uri' => baseUrl() . '/callback.php',
23
'response_type' => 'code',
24
'state' => $_SESSION['oauth_state'],
25
]));
26
} catch (Throwable $e) {
27
http_response_code(503);
28
header('Content-Type: text/html; charset=utf-8');
29
echo '<!DOCTYPE html><meta charset="utf-8"><title>Meteors</title>';
30
echo '<p>Inloggen is nu niet mogelijk. ' . htmlspecialchars($e->getMessage()) . '</p>';
31
echo '<p><a href="index.html">Terug naar het spel</a></p>';
32
}
@@ -0,0 +1,32 @@1
<?php2
declare(strict_types=1);3
require __DIR__ . '/lib/bootstrap.php';4
5
try {6
if (localDev() && isset($_GET['test'])) {7
$who = $_GET['test'] === '2' ? 'test_user_2' : 'test_user_1';8
loginUser('local:' . $who, $who);9
$next = isset($_GET['next']) && is_string($_GET['next']) ? $_GET['next'] : 'index.html';10
header('Location: ' . $next);11
exit;12
}13
if (!authConfigured()) {14
header('Location: index.html?auth=unconfigured');15
exit;16
}17
$cfg = config();18
$_SESSION['oauth_state'] = bin2hex(random_bytes(32));19
$_SESSION['oauth_started'] = time();20
header('Location: ' . authUrl() . '/oauth/authorize?' . http_build_query([21
'client_id' => $cfg['client_id'],22
'redirect_uri' => baseUrl() . '/callback.php',23
'response_type' => 'code',24
'state' => $_SESSION['oauth_state'],25
]));26
} catch (Throwable $e) {27
http_response_code(503);28
header('Content-Type: text/html; charset=utf-8');29
echo '<!DOCTYPE html><meta charset="utf-8"><title>Meteors</title>';30
echo '<p>Inloggen is nu niet mogelijk. ' . htmlspecialchars($e->getMessage()) . '</p>';31
echo '<p><a href="index.html">Terug naar het spel</a></p>';32
}@@ -0,0 +1,43 @@
1
<?php
2
declare(strict_types=1);
3
require __DIR__ . '/lib/bootstrap.php';
4
5
try {
6
$state = $_GET['state'] ?? null;
7
if (!is_string($state) || !isset($_SESSION['oauth_state'])
8
|| !hash_equals((string) $_SESSION['oauth_state'], $state)
9
|| time() - (int) ($_SESSION['oauth_started'] ?? 0) > 600) {
10
throw new RuntimeException('Ongeldige of verlopen login.');
11
}
12
unset($_SESSION['oauth_state'], $_SESSION['oauth_started']);
13
$code = $_GET['code'] ?? null;
14
if (!is_string($code) || $code === '') {
15
throw new RuntimeException('De login is niet afgerond.');
16
}
17
$cfg = config();
18
$token = authRequest('/oauth/token', [
19
'grant_type' => 'authorization_code',
20
'code' => $code,
21
'client_id' => $cfg['client_id'],
22
'client_secret' => $cfg['client_secret'],
23
'redirect_uri' => baseUrl() . '/callback.php',
24
]);
25
if (!isset($token['access_token'], $token['expires_in']) || !is_string($token['access_token'])) {
26
throw new RuntimeException('Geen toegangstoken ontvangen.');
27
}
28
$me = authRequest('/api/me', null, $token['access_token']);
29
if (!isset($me['user']) || !is_array($me['user'])) {
30
throw new RuntimeException('Het profiel ontbreekt.');
31
}
32
[$id, $name] = authIdentity($me['user']);
33
loginUser($id, $name);
34
$_SESSION['token'] = $token['access_token'];
35
$_SESSION['expires'] = time() + (int) $token['expires_in'];
36
header('Location: ' . baseUrl() . '/index.html?online=1');
37
} catch (Throwable $e) {
38
http_response_code(401);
39
header('Content-Type: text/html; charset=utf-8');
40
echo '<!DOCTYPE html><meta charset="utf-8"><title>Meteors</title>';
41
echo 'Inloggen is mislukt. ' . htmlspecialchars($e->getMessage());
42
echo ' <a href="auth.php">Opnieuw proberen</a> · <a href="index.html">Terug</a>';
43
}
@@ -0,0 +1,43 @@1
<?php2
declare(strict_types=1);3
require __DIR__ . '/lib/bootstrap.php';4
5
try {6
$state = $_GET['state'] ?? null;7
if (!is_string($state) || !isset($_SESSION['oauth_state'])8
|| !hash_equals((string) $_SESSION['oauth_state'], $state)9
|| time() - (int) ($_SESSION['oauth_started'] ?? 0) > 600) {10
throw new RuntimeException('Ongeldige of verlopen login.');11
}12
unset($_SESSION['oauth_state'], $_SESSION['oauth_started']);13
$code = $_GET['code'] ?? null;14
if (!is_string($code) || $code === '') {15
throw new RuntimeException('De login is niet afgerond.');16
}17
$cfg = config();18
$token = authRequest('/oauth/token', [19
'grant_type' => 'authorization_code',20
'code' => $code,21
'client_id' => $cfg['client_id'],22
'client_secret' => $cfg['client_secret'],23
'redirect_uri' => baseUrl() . '/callback.php',24
]);25
if (!isset($token['access_token'], $token['expires_in']) || !is_string($token['access_token'])) {26
throw new RuntimeException('Geen toegangstoken ontvangen.');27
}28
$me = authRequest('/api/me', null, $token['access_token']);29
if (!isset($me['user']) || !is_array($me['user'])) {30
throw new RuntimeException('Het profiel ontbreekt.');31
}32
[$id, $name] = authIdentity($me['user']);33
loginUser($id, $name);34
$_SESSION['token'] = $token['access_token'];35
$_SESSION['expires'] = time() + (int) $token['expires_in'];36
header('Location: ' . baseUrl() . '/index.html?online=1');37
} catch (Throwable $e) {38
http_response_code(401);39
header('Content-Type: text/html; charset=utf-8');40
echo '<!DOCTYPE html><meta charset="utf-8"><title>Meteors</title>';41
echo 'Inloggen is mislukt. ' . htmlspecialchars($e->getMessage());42
echo ' <a href="auth.php">Opnieuw proberen</a> · <a href="index.html">Terug</a>';43
}@@ -0,0 +1,3 @@
1
*
2
!.htaccess
3
!.gitignore
@@ -0,0 +1,3 @@1
*2
!.htaccess3
!.gitignore@@ -0,0 +1,2 @@
1
# The data directory is never served. This file is also written on first run.
2
Require all denied
@@ -0,0 +1,2 @@1
# The data directory is never served. This file is also written on first run.2
Require all denied@@ -0,0 +1,616 @@
1
<?php
2
declare(strict_types=1);
3
4
final class Store
5
{
6
private PDO $pdo;
7
private int $txDepth = 0;
8
9
public function __construct(PDO $pdo)
10
{
11
$this->pdo = $pdo;
12
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
13
$this->migrate();
14
}
15
16
public static function open(?string $dir = null): self
17
{
18
$dir = $dir ?? dataDir();
19
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
20
throw new RuntimeException('De datamap moet schrijfbaar zijn.');
21
}
22
$path = $dir . '/meteors.sqlite';
23
$pdo = new PDO('sqlite:' . $path, null, null, [
24
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
25
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
26
]);
27
$pdo->exec('PRAGMA journal_mode = WAL');
28
$pdo->exec('PRAGMA foreign_keys = ON');
29
$pdo->exec('PRAGMA busy_timeout = 4000');
30
return new self($pdo);
31
}
32
33
private function migrate(): void
34
{
35
$this->pdo->exec(<<<'SQL'
36
CREATE TABLE IF NOT EXISTS lobbies (
37
id TEXT PRIMARY KEY,
38
code TEXT UNIQUE NOT NULL,
39
host_id TEXT NOT NULL,
40
status TEXT NOT NULL DEFAULT 'waiting',
41
miss_chance REAL NOT NULL DEFAULT 0.30,
42
flight_duration REAL NOT NULL DEFAULT 1.2,
43
created INTEGER NOT NULL,
44
started INTEGER,
45
finished INTEGER
46
);
47
CREATE TABLE IF NOT EXISTS members (
48
lobby_id TEXT NOT NULL,
49
user_id TEXT NOT NULL,
50
name TEXT NOT NULL,
51
ready INTEGER NOT NULL DEFAULT 0,
52
eliminated INTEGER NOT NULL DEFAULT 0,
53
place INTEGER,
54
left_at INTEGER,
55
joined INTEGER NOT NULL,
56
last_seen INTEGER NOT NULL,
57
score INTEGER NOT NULL DEFAULT 0,
58
snapshot TEXT,
59
PRIMARY KEY (lobby_id, user_id)
60
);
61
CREATE TABLE IF NOT EXISTS shots (
62
id INTEGER PRIMARY KEY AUTOINCREMENT,
63
lobby_id TEXT NOT NULL,
64
from_user TEXT NOT NULL,
65
to_user TEXT,
66
color INTEGER NOT NULL,
67
client_id TEXT,
68
created REAL NOT NULL,
69
deliver_at REAL NOT NULL,
70
delivered INTEGER NOT NULL DEFAULT 0
71
);
72
CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);
73
SQL);
74
}
75
76
public function transaction(callable $fn): mixed
77
{
78
if ($this->txDepth > 0) {
79
return $fn();
80
}
81
$this->pdo->beginTransaction();
82
$this->txDepth++;
83
try {
84
$result = $fn();
85
$this->pdo->commit();
86
$this->txDepth--;
87
return $result;
88
} catch (Throwable $e) {
89
$this->txDepth--;
90
if ($this->pdo->inTransaction()) {
91
$this->pdo->rollBack();
92
}
93
throw $e;
94
}
95
}
96
97
private function now(): int
98
{
99
return time();
100
}
101
102
private function nowf(): float
103
{
104
return microtime(true);
105
}
106
107
private function newId(): string
108
{
109
return bin2hex(random_bytes(12));
110
}
111
112
private function newCode(): string
113
{
114
$alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
115
$len = strlen($alphabet);
116
for ($attempt = 0; $attempt < 16; $attempt++) {
117
$code = '';
118
for ($i = 0; $i < 4; $i++) {
119
$code .= $alphabet[random_int(0, $len - 1)];
120
}
121
$exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?');
122
$exists->execute([$code]);
123
if (!$exists->fetch()) {
124
return $code;
125
}
126
}
127
throw new RuntimeException('Kon geen unieke lobbycode maken.');
128
}
129
130
public function lobbyForUser(string $userId): ?array
131
{
132
$stmt = $this->pdo->prepare(
133
'SELECT l.* FROM lobbies l
134
JOIN members m ON m.lobby_id = l.id
135
WHERE m.user_id = ? AND m.left_at IS NULL
136
ORDER BY l.created DESC LIMIT 1'
137
);
138
$stmt->execute([$userId]);
139
$row = $stmt->fetch();
140
return $row ?: null;
141
}
142
143
public function getLobby(string $id): ?array
144
{
145
$stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?');
146
$stmt->execute([$id]);
147
$row = $stmt->fetch();
148
return $row ?: null;
149
}
150
151
public function getLobbyByCode(string $code): ?array
152
{
153
$code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? '');
154
$stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?');
155
$stmt->execute([$code]);
156
$row = $stmt->fetch();
157
return $row ?: null;
158
}
159
160
/** @return list<array> */
161
public function members(string $lobbyId, bool $includeLeft = false): array
162
{
163
$sql = 'SELECT * FROM members WHERE lobby_id = ?';
164
if (!$includeLeft) {
165
$sql .= ' AND left_at IS NULL';
166
}
167
$sql .= ' ORDER BY joined ASC';
168
$stmt = $this->pdo->prepare($sql);
169
$stmt->execute([$lobbyId]);
170
return $stmt->fetchAll();
171
}
172
173
public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS): array
174
{
175
return $this->transaction(function () use ($userId, $name, $missChance) {
176
$existing = $this->lobbyForUser($userId);
177
if ($existing && $existing['status'] !== 'finished') {
178
throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');
179
}
180
if ($existing && $existing['status'] === 'finished') {
181
$this->leaveMember($existing['id'], $userId);
182
}
183
$id = $this->newId();
184
$code = $this->newCode();
185
$now = $this->now();
186
$miss = max(0.0, min(1.0, $missChance));
187
$this->pdo->prepare(
188
'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)
189
VALUES (?,?,?,?,?,?,?)'
190
)->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);
191
$this->pdo->prepare(
192
'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen)
193
VALUES (?,?,?,0,?,?)'
194
)->execute([$id, $userId, $name, $now, $now]);
195
return $this->getLobby($id);
196
});
197
}
198
199
public function joinLobby(string $userId, string $name, string $code): array
200
{
201
return $this->transaction(function () use ($userId, $name, $code) {
202
$existing = $this->lobbyForUser($userId);
203
if ($existing && $existing['status'] !== 'finished') {
204
if (strcasecmp($existing['code'], $code) === 0) {
205
return $existing;
206
}
207
throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.');
208
}
209
$lobby = $this->getLobbyByCode($code);
210
if (!$lobby) {
211
throw new RuntimeException('Onbekende lobbycode.');
212
}
213
if ($lobby['status'] !== 'waiting') {
214
throw new RuntimeException('Deze lobby is al begonnen.');
215
}
216
$members = $this->members($lobby['id']);
217
if (count($members) >= METEORS_MAX_PLAYERS) {
218
throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');
219
}
220
$now = $this->now();
221
$this->pdo->prepare(
222
'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot)
223
VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL)
224
ON CONFLICT(lobby_id, user_id) DO UPDATE SET
225
name = excluded.name,
226
ready = 0,
227
eliminated = 0,
228
place = NULL,
229
left_at = NULL,
230
joined = excluded.joined,
231
last_seen = excluded.last_seen,
232
score = 0,
233
snapshot = NULL'
234
)->execute([$lobby['id'], $userId, $name, $now, $now]);
235
return $this->getLobby($lobby['id']);
236
});
237
}
238
239
private function leaveMember(string $lobbyId, string $userId): void
240
{
241
$this->pdo->prepare(
242
'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
243
)->execute([$this->now(), $lobbyId, $userId]);
244
$lobby = $this->getLobby($lobbyId);
245
if (!$lobby) {
246
return;
247
}
248
$remaining = $this->members($lobbyId);
249
if ($lobby['host_id'] === $userId) {
250
if ($remaining) {
251
$this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?')
252
->execute([$remaining[0]['user_id'], $lobbyId]);
253
} elseif ($lobby['status'] === 'waiting') {
254
// Empty waiting lobby can stay; a later join by code still works until we want to close it.
255
}
256
}
257
if ($lobby['status'] === 'playing') {
258
$this->assignPlaceIfNeeded($lobbyId, $userId, true);
259
$this->maybeFinish($lobbyId);
260
}
261
}
262
263
public function leaveLobby(string $userId): void
264
{
265
$this->transaction(function () use ($userId) {
266
$lobby = $this->lobbyForUser($userId);
267
if (!$lobby) {
268
return;
269
}
270
$this->leaveMember($lobby['id'], $userId);
271
});
272
}
273
274
public function setReady(string $userId, bool $ready): array
275
{
276
return $this->transaction(function () use ($userId, $ready) {
277
$lobby = $this->lobbyForUser($userId);
278
if (!$lobby) {
279
throw new RuntimeException('Je zit niet in een lobby.');
280
}
281
if ($lobby['status'] !== 'waiting') {
282
throw new RuntimeException('Het spel is al begonnen.');
283
}
284
$this->pdo->prepare(
285
'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
286
)->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]);
287
return $this->getLobby($lobby['id']);
288
});
289
}
290
291
public function startGame(string $userId): array
292
{
293
return $this->transaction(function () use ($userId) {
294
$lobby = $this->lobbyForUser($userId);
295
if (!$lobby) {
296
throw new RuntimeException('Je zit niet in een lobby.');
297
}
298
if ($lobby['host_id'] !== $userId) {
299
throw new RuntimeException('Alleen de host kan het spel starten.');
300
}
301
if ($lobby['status'] !== 'waiting') {
302
throw new RuntimeException('Het spel is al begonnen.');
303
}
304
$members = $this->members($lobby['id']);
305
if (count($members) < 2) {
306
throw new RuntimeException('Er zijn minstens twee spelers nodig.');
307
}
308
foreach ($members as $m) {
309
if (!(int) $m['ready']) {
310
throw new RuntimeException('Niet iedereen is gereed.');
311
}
312
}
313
$this->pdo->prepare(
314
'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?'
315
)->execute(['playing', $this->now(), $lobby['id']]);
316
$this->pdo->prepare(
317
'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL
318
WHERE lobby_id = ? AND left_at IS NULL'
319
)->execute([$lobby['id']]);
320
$this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]);
321
return $this->getLobby($lobby['id']);
322
});
323
}
324
325
/** @param list<array{client_id?:string,color?:int}> $shots */
326
public function recordShots(string $userId, array $shots): array
327
{
328
return $this->transaction(function () use ($userId, $shots) {
329
$lobby = $this->lobbyForUser($userId);
330
if (!$lobby || $lobby['status'] !== 'playing') {
331
return [];
332
}
333
$me = $this->member($lobby['id'], $userId);
334
if (!$me || (int) $me['eliminated']) {
335
return [];
336
}
337
$targets = [];
338
foreach ($this->members($lobby['id']) as $m) {
339
if ($m['user_id'] !== $userId && !(int) $m['eliminated']) {
340
$targets[] = $m;
341
}
342
}
343
$results = [];
344
$missChance = (float) $lobby['miss_chance'];
345
$flight = (float) $lobby['flight_duration'];
346
$now = $this->nowf();
347
$ins = $this->pdo->prepare(
348
'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered)
349
VALUES (?,?,?,?,?,?,?,0)'
350
);
351
foreach ($shots as $shot) {
352
$color = isset($shot['color']) ? (int) $shot['color'] : -1;
353
$clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');
354
$miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;
355
$to = null;
356
$toName = null;
357
if (!$miss) {
358
$pick = $targets[random_int(0, count($targets) - 1)];
359
$to = $pick['user_id'];
360
$toName = $pick['name'];
361
}
362
$deliver = $now + $flight;
363
$ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver]);
364
$results[] = [
365
'id' => (int) $this->pdo->lastInsertId(),
366
'client_id' => $clientId,
367
'miss' => $miss,
368
'target_id' => $to,
369
'target_name' => $toName,
370
'deliver_at' => $deliver,
371
'color' => $color,
372
'flight_duration' => $flight,
373
];
374
}
375
return $results;
376
});
377
}
378
379
/** @return list<array> undelivered shots whose time has come, marked delivered. */
380
public function takeIncoming(string $lobbyId, string $userId): array
381
{
382
$now = $this->nowf();
383
$stmt = $this->pdo->prepare(
384
'SELECT * FROM shots
385
WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ?
386
ORDER BY deliver_at ASC, id ASC'
387
);
388
$stmt->execute([$lobbyId, $userId, $now]);
389
$rows = $stmt->fetchAll();
390
if (!$rows) {
391
return [];
392
}
393
$ids = array_column($rows, 'id');
394
$in = implode(',', array_fill(0, count($ids), '?'));
395
$this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids);
396
$incoming = [];
397
foreach ($rows as $r) {
398
$incoming[] = [
399
'id' => (int) $r['id'],
400
'color' => (int) $r['color'],
401
'from_user' => $r['from_user'],
402
'client_id' => $r['client_id'],
403
];
404
}
405
return $incoming;
406
}
407
408
public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void
409
{
410
$lobby = $this->lobbyForUser($userId);
411
if (!$lobby || $lobby['status'] !== 'playing') {
412
return;
413
}
414
$json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null;
415
$fields = 'last_seen = ?';
416
$args = [$this->now()];
417
if ($json !== null) {
418
$fields .= ', snapshot = ?';
419
$args[] = $json;
420
}
421
if ($score !== null) {
422
$fields .= ', score = ?';
423
$args[] = $score;
424
}
425
$args[] = $lobby['id'];
426
$args[] = $userId;
427
$this->pdo->prepare(
428
"UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL"
429
)->execute($args);
430
if ($eliminated) {
431
$this->assignPlaceIfNeeded($lobby['id'], $userId, false);
432
$this->maybeFinish($lobby['id']);
433
}
434
}
435
436
public function member(string $lobbyId, string $userId): ?array
437
{
438
$stmt = $this->pdo->prepare(
439
'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?'
440
);
441
$stmt->execute([$lobbyId, $userId]);
442
$row = $stmt->fetch();
443
return $row ?: null;
444
}
445
446
private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void
447
{
448
$m = $this->member($lobbyId, $userId);
449
if (!$m || $m['place'] !== null) {
450
return;
451
}
452
$active = 0;
453
foreach ($this->members($lobbyId) as $row) {
454
if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) {
455
$active++;
456
}
457
}
458
// First out gets last place = number of current (incl. this) non-left players.
459
$total = count($this->members($lobbyId));
460
$alreadyPlaced = 0;
461
foreach ($this->members($lobbyId, true) as $row) {
462
if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) {
463
if ($row['place'] !== null) {
464
$alreadyPlaced++;
465
}
466
}
467
}
468
$place = $active + 1; // remaining others + self → this player's place
469
$this->pdo->prepare(
470
'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?'
471
)->execute([$place, $lobbyId, $userId]);
472
}
473
474
public function maybeFinish(string $lobbyId): void
475
{
476
$lobby = $this->getLobby($lobbyId);
477
if (!$lobby || $lobby['status'] !== 'playing') {
478
return;
479
}
480
$alive = [];
481
foreach ($this->members($lobbyId) as $m) {
482
if (!(int) $m['eliminated']) {
483
$alive[] = $m;
484
}
485
}
486
if (count($alive) > 1) {
487
return;
488
}
489
if (count($alive) === 1) {
490
$winner = $alive[0];
491
if ($winner['place'] === null) {
492
$this->pdo->prepare(
493
'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?'
494
)->execute([$lobbyId, $winner['user_id']]);
495
}
496
}
497
$this->pdo->prepare(
498
'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?'
499
)->execute(['finished', $this->now(), $lobbyId]);
500
}
501
502
public function maybeResetLobby(string $lobbyId): void
503
{
504
$lobby = $this->getLobby($lobbyId);
505
if (!$lobby || $lobby['status'] !== 'finished') {
506
return;
507
}
508
$finished = (int) ($lobby['finished'] ?? 0);
509
if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {
510
return;
511
}
512
$this->pdo->prepare(
513
'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?'
514
)->execute(['waiting', $lobbyId]);
515
$this->pdo->prepare(
516
'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0
517
WHERE lobby_id = ? AND left_at IS NULL'
518
)->execute([$lobbyId]);
519
$this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]);
520
}
521
522
/** Public view of a lobby for the given user, including incoming shots. */
523
public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array
524
{
525
return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) {
526
$touch = $this->lobbyForUser($userId);
527
if ($touch && $touch['status'] === 'finished') {
528
$this->maybeResetLobby($touch['id']);
529
}
530
if ($touch && $touch['status'] === 'playing') {
531
if ($snapshot !== null || $score !== null || $eliminated) {
532
$this->updateSnapshot($userId, $snapshot, $score, $eliminated);
533
} else {
534
$this->pdo->prepare(
535
'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'
536
)->execute([$this->now(), $touch['id'], $userId]);
537
}
538
}
539
$shotResults = [];
540
if ($outgoing && $touch && $touch['status'] === 'playing') {
541
$shotResults = $this->recordShots($userId, $outgoing);
542
}
543
$lobby = $this->lobbyForUser($userId);
544
if (!$lobby) {
545
return [
546
'lobby' => null,
547
'incoming' => [],
548
'shot_results' => $shotResults,
549
];
550
}
551
$incoming = [];
552
if ($lobby['status'] === 'playing') {
553
$incoming = $this->takeIncoming($lobby['id'], $userId);
554
}
555
return [
556
'lobby' => $this->presentLobby($lobby, $userId),
557
'incoming' => $incoming,
558
'shot_results' => $shotResults,
559
];
560
});
561
}
562
563
public function presentLobby(array $lobby, string $userId): array
564
{
565
$members = $this->members($lobby['id']);
566
$players = [];
567
foreach ($members as $m) {
568
$snap = null;
569
if (is_string($m['snapshot']) && $m['snapshot'] !== '') {
570
$decoded = json_decode($m['snapshot'], true);
571
$snap = is_array($decoded) ? $decoded : null;
572
}
573
$players[] = [
574
'id' => $m['user_id'],
575
'name' => $m['name'],
576
'ready' => (bool) (int) $m['ready'],
577
'eliminated' => (bool) (int) $m['eliminated'],
578
'place' => $m['place'] !== null ? (int) $m['place'] : null,
579
'is_host' => $m['user_id'] === $lobby['host_id'],
580
'is_me' => $m['user_id'] === $userId,
581
'score' => (int) $m['score'],
582
'snapshot' => $m['user_id'] === $userId ? null : $snap,
583
];
584
}
585
$rankings = [];
586
if ($lobby['status'] === 'finished' || $lobby['finished']) {
587
$all = $this->members($lobby['id'], true);
588
foreach ($all as $m) {
589
if ($m['place'] !== null) {
590
$rankings[] = [
591
'place' => (int) $m['place'],
592
'id' => $m['user_id'],
593
'name' => $m['name'],
594
'score' => (int) $m['score'],
595
];
596
}
597
}
598
usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']);
599
}
600
$allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true);
601
return [
602
'id' => $lobby['id'],
603
'code' => $lobby['code'],
604
'status' => $lobby['status'],
605
'host_id' => $lobby['host_id'],
606
'miss_chance' => (float) $lobby['miss_chance'],
607
'flight_duration' => (float) $lobby['flight_duration'],
608
'players' => $players,
609
'all_ready' => $allReady,
610
'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2,
611
'rankings' => $rankings,
612
'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null,
613
'podium_seconds' => METEORS_PODIUM_SECONDS,
614
];
615
}
616
}
@@ -0,0 +1,616 @@1
<?php2
declare(strict_types=1);3
4
final class Store5
{6
private PDO $pdo;7
private int $txDepth = 0;8
9
public function __construct(PDO $pdo)10
{11
$this->pdo = $pdo;12
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);13
$this->migrate();14
}15
16
public static function open(?string $dir = null): self17
{18
$dir = $dir ?? dataDir();19
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {20
throw new RuntimeException('De datamap moet schrijfbaar zijn.');21
}22
$path = $dir . '/meteors.sqlite';23
$pdo = new PDO('sqlite:' . $path, null, null, [24
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,25
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,26
]);27
$pdo->exec('PRAGMA journal_mode = WAL');28
$pdo->exec('PRAGMA foreign_keys = ON');29
$pdo->exec('PRAGMA busy_timeout = 4000');30
return new self($pdo);31
}32
33
private function migrate(): void34
{35
$this->pdo->exec(<<<'SQL'36
CREATE TABLE IF NOT EXISTS lobbies (37
id TEXT PRIMARY KEY,38
code TEXT UNIQUE NOT NULL,39
host_id TEXT NOT NULL,40
status TEXT NOT NULL DEFAULT 'waiting',41
miss_chance REAL NOT NULL DEFAULT 0.30,42
flight_duration REAL NOT NULL DEFAULT 1.2,43
created INTEGER NOT NULL,44
started INTEGER,45
finished INTEGER46
);47
CREATE TABLE IF NOT EXISTS members (48
lobby_id TEXT NOT NULL,49
user_id TEXT NOT NULL,50
name TEXT NOT NULL,51
ready INTEGER NOT NULL DEFAULT 0,52
eliminated INTEGER NOT NULL DEFAULT 0,53
place INTEGER,54
left_at INTEGER,55
joined INTEGER NOT NULL,56
last_seen INTEGER NOT NULL,57
score INTEGER NOT NULL DEFAULT 0,58
snapshot TEXT,59
PRIMARY KEY (lobby_id, user_id)60
);61
CREATE TABLE IF NOT EXISTS shots (62
id INTEGER PRIMARY KEY AUTOINCREMENT,63
lobby_id TEXT NOT NULL,64
from_user TEXT NOT NULL,65
to_user TEXT,66
color INTEGER NOT NULL,67
client_id TEXT,68
created REAL NOT NULL,69
deliver_at REAL NOT NULL,70
delivered INTEGER NOT NULL DEFAULT 071
);72
CREATE INDEX IF NOT EXISTS shots_deliver ON shots (lobby_id, to_user, delivered, deliver_at);73
SQL);74
}75
76
public function transaction(callable $fn): mixed77
{78
if ($this->txDepth > 0) {79
return $fn();80
}81
$this->pdo->beginTransaction();82
$this->txDepth++;83
try {84
$result = $fn();85
$this->pdo->commit();86
$this->txDepth--;87
return $result;88
} catch (Throwable $e) {89
$this->txDepth--;90
if ($this->pdo->inTransaction()) {91
$this->pdo->rollBack();92
}93
throw $e;94
}95
}96
97
private function now(): int98
{99
return time();100
}101
102
private function nowf(): float103
{104
return microtime(true);105
}106
107
private function newId(): string108
{109
return bin2hex(random_bytes(12));110
}111
112
private function newCode(): string113
{114
$alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';115
$len = strlen($alphabet);116
for ($attempt = 0; $attempt < 16; $attempt++) {117
$code = '';118
for ($i = 0; $i < 4; $i++) {119
$code .= $alphabet[random_int(0, $len - 1)];120
}121
$exists = $this->pdo->prepare('SELECT 1 FROM lobbies WHERE code = ?');122
$exists->execute([$code]);123
if (!$exists->fetch()) {124
return $code;125
}126
}127
throw new RuntimeException('Kon geen unieke lobbycode maken.');128
}129
130
public function lobbyForUser(string $userId): ?array131
{132
$stmt = $this->pdo->prepare(133
'SELECT l.* FROM lobbies l134
JOIN members m ON m.lobby_id = l.id135
WHERE m.user_id = ? AND m.left_at IS NULL136
ORDER BY l.created DESC LIMIT 1'137
);138
$stmt->execute([$userId]);139
$row = $stmt->fetch();140
return $row ?: null;141
}142
143
public function getLobby(string $id): ?array144
{145
$stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE id = ?');146
$stmt->execute([$id]);147
$row = $stmt->fetch();148
return $row ?: null;149
}150
151
public function getLobbyByCode(string $code): ?array152
{153
$code = strtoupper(preg_replace('/[^A-Za-z0-9]/', '', $code) ?? '');154
$stmt = $this->pdo->prepare('SELECT * FROM lobbies WHERE code = ?');155
$stmt->execute([$code]);156
$row = $stmt->fetch();157
return $row ?: null;158
}159
160
/** @return list<array> */161
public function members(string $lobbyId, bool $includeLeft = false): array162
{163
$sql = 'SELECT * FROM members WHERE lobby_id = ?';164
if (!$includeLeft) {165
$sql .= ' AND left_at IS NULL';166
}167
$sql .= ' ORDER BY joined ASC';168
$stmt = $this->pdo->prepare($sql);169
$stmt->execute([$lobbyId]);170
return $stmt->fetchAll();171
}172
173
public function createLobby(string $userId, string $name, float $missChance = METEORS_DEFAULT_MISS): array174
{175
return $this->transaction(function () use ($userId, $name, $missChance) {176
$existing = $this->lobbyForUser($userId);177
if ($existing && $existing['status'] !== 'finished') {178
throw new RuntimeException('Je zit al in een lobby. Verlaat die eerst.');179
}180
if ($existing && $existing['status'] === 'finished') {181
$this->leaveMember($existing['id'], $userId);182
}183
$id = $this->newId();184
$code = $this->newCode();185
$now = $this->now();186
$miss = max(0.0, min(1.0, $missChance));187
$this->pdo->prepare(188
'INSERT INTO lobbies (id, code, host_id, status, miss_chance, flight_duration, created)189
VALUES (?,?,?,?,?,?,?)'190
)->execute([$id, $code, $userId, 'waiting', $miss, METEORS_FLIGHT_DURATION, $now]);191
$this->pdo->prepare(192
'INSERT INTO members (lobby_id, user_id, name, ready, joined, last_seen)193
VALUES (?,?,?,0,?,?)'194
)->execute([$id, $userId, $name, $now, $now]);195
return $this->getLobby($id);196
});197
}198
199
public function joinLobby(string $userId, string $name, string $code): array200
{201
return $this->transaction(function () use ($userId, $name, $code) {202
$existing = $this->lobbyForUser($userId);203
if ($existing && $existing['status'] !== 'finished') {204
if (strcasecmp($existing['code'], $code) === 0) {205
return $existing;206
}207
throw new RuntimeException('Je zit al in een andere lobby. Verlaat die eerst.');208
}209
$lobby = $this->getLobbyByCode($code);210
if (!$lobby) {211
throw new RuntimeException('Onbekende lobbycode.');212
}213
if ($lobby['status'] !== 'waiting') {214
throw new RuntimeException('Deze lobby is al begonnen.');215
}216
$members = $this->members($lobby['id']);217
if (count($members) >= METEORS_MAX_PLAYERS) {218
throw new RuntimeException('Deze lobby is vol (maximaal ' . METEORS_MAX_PLAYERS . ' spelers).');219
}220
$now = $this->now();221
$this->pdo->prepare(222
'INSERT INTO members (lobby_id, user_id, name, ready, eliminated, place, left_at, joined, last_seen, score, snapshot)223
VALUES (?,?,?,0,0,NULL,NULL,?,?,0,NULL)224
ON CONFLICT(lobby_id, user_id) DO UPDATE SET225
name = excluded.name,226
ready = 0,227
eliminated = 0,228
place = NULL,229
left_at = NULL,230
joined = excluded.joined,231
last_seen = excluded.last_seen,232
score = 0,233
snapshot = NULL'234
)->execute([$lobby['id'], $userId, $name, $now, $now]);235
return $this->getLobby($lobby['id']);236
});237
}238
239
private function leaveMember(string $lobbyId, string $userId): void240
{241
$this->pdo->prepare(242
'UPDATE members SET left_at = ?, ready = 0 WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'243
)->execute([$this->now(), $lobbyId, $userId]);244
$lobby = $this->getLobby($lobbyId);245
if (!$lobby) {246
return;247
}248
$remaining = $this->members($lobbyId);249
if ($lobby['host_id'] === $userId) {250
if ($remaining) {251
$this->pdo->prepare('UPDATE lobbies SET host_id = ? WHERE id = ?')252
->execute([$remaining[0]['user_id'], $lobbyId]);253
} elseif ($lobby['status'] === 'waiting') {254
// Empty waiting lobby can stay; a later join by code still works until we want to close it.255
}256
}257
if ($lobby['status'] === 'playing') {258
$this->assignPlaceIfNeeded($lobbyId, $userId, true);259
$this->maybeFinish($lobbyId);260
}261
}262
263
public function leaveLobby(string $userId): void264
{265
$this->transaction(function () use ($userId) {266
$lobby = $this->lobbyForUser($userId);267
if (!$lobby) {268
return;269
}270
$this->leaveMember($lobby['id'], $userId);271
});272
}273
274
public function setReady(string $userId, bool $ready): array275
{276
return $this->transaction(function () use ($userId, $ready) {277
$lobby = $this->lobbyForUser($userId);278
if (!$lobby) {279
throw new RuntimeException('Je zit niet in een lobby.');280
}281
if ($lobby['status'] !== 'waiting') {282
throw new RuntimeException('Het spel is al begonnen.');283
}284
$this->pdo->prepare(285
'UPDATE members SET ready = ?, last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'286
)->execute([$ready ? 1 : 0, $this->now(), $lobby['id'], $userId]);287
return $this->getLobby($lobby['id']);288
});289
}290
291
public function startGame(string $userId): array292
{293
return $this->transaction(function () use ($userId) {294
$lobby = $this->lobbyForUser($userId);295
if (!$lobby) {296
throw new RuntimeException('Je zit niet in een lobby.');297
}298
if ($lobby['host_id'] !== $userId) {299
throw new RuntimeException('Alleen de host kan het spel starten.');300
}301
if ($lobby['status'] !== 'waiting') {302
throw new RuntimeException('Het spel is al begonnen.');303
}304
$members = $this->members($lobby['id']);305
if (count($members) < 2) {306
throw new RuntimeException('Er zijn minstens twee spelers nodig.');307
}308
foreach ($members as $m) {309
if (!(int) $m['ready']) {310
throw new RuntimeException('Niet iedereen is gereed.');311
}312
}313
$this->pdo->prepare(314
'UPDATE lobbies SET status = ?, started = ?, finished = NULL WHERE id = ?'315
)->execute(['playing', $this->now(), $lobby['id']]);316
$this->pdo->prepare(317
'UPDATE members SET eliminated = 0, place = NULL, score = 0, snapshot = NULL318
WHERE lobby_id = ? AND left_at IS NULL'319
)->execute([$lobby['id']]);320
$this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobby['id']]);321
return $this->getLobby($lobby['id']);322
});323
}324
325
/** @param list<array{client_id?:string,color?:int}> $shots */326
public function recordShots(string $userId, array $shots): array327
{328
return $this->transaction(function () use ($userId, $shots) {329
$lobby = $this->lobbyForUser($userId);330
if (!$lobby || $lobby['status'] !== 'playing') {331
return [];332
}333
$me = $this->member($lobby['id'], $userId);334
if (!$me || (int) $me['eliminated']) {335
return [];336
}337
$targets = [];338
foreach ($this->members($lobby['id']) as $m) {339
if ($m['user_id'] !== $userId && !(int) $m['eliminated']) {340
$targets[] = $m;341
}342
}343
$results = [];344
$missChance = (float) $lobby['miss_chance'];345
$flight = (float) $lobby['flight_duration'];346
$now = $this->nowf();347
$ins = $this->pdo->prepare(348
'INSERT INTO shots (lobby_id, from_user, to_user, color, client_id, created, deliver_at, delivered)349
VALUES (?,?,?,?,?,?,?,0)'350
);351
foreach ($shots as $shot) {352
$color = isset($shot['color']) ? (int) $shot['color'] : -1;353
$clientId = isset($shot['client_id']) ? (string) $shot['client_id'] : (string) ($shot['id'] ?? '');354
$miss = $targets === [] || (mt_rand() / mt_getrandmax()) < $missChance;355
$to = null;356
$toName = null;357
if (!$miss) {358
$pick = $targets[random_int(0, count($targets) - 1)];359
$to = $pick['user_id'];360
$toName = $pick['name'];361
}362
$deliver = $now + $flight;363
$ins->execute([$lobby['id'], $userId, $to, $color, $clientId, $now, $deliver]);364
$results[] = [365
'id' => (int) $this->pdo->lastInsertId(),366
'client_id' => $clientId,367
'miss' => $miss,368
'target_id' => $to,369
'target_name' => $toName,370
'deliver_at' => $deliver,371
'color' => $color,372
'flight_duration' => $flight,373
];374
}375
return $results;376
});377
}378
379
/** @return list<array> undelivered shots whose time has come, marked delivered. */380
public function takeIncoming(string $lobbyId, string $userId): array381
{382
$now = $this->nowf();383
$stmt = $this->pdo->prepare(384
'SELECT * FROM shots385
WHERE lobby_id = ? AND to_user = ? AND delivered = 0 AND deliver_at <= ?386
ORDER BY deliver_at ASC, id ASC'387
);388
$stmt->execute([$lobbyId, $userId, $now]);389
$rows = $stmt->fetchAll();390
if (!$rows) {391
return [];392
}393
$ids = array_column($rows, 'id');394
$in = implode(',', array_fill(0, count($ids), '?'));395
$this->pdo->prepare('UPDATE shots SET delivered = 1 WHERE id IN (' . $in . ')')->execute($ids);396
$incoming = [];397
foreach ($rows as $r) {398
$incoming[] = [399
'id' => (int) $r['id'],400
'color' => (int) $r['color'],401
'from_user' => $r['from_user'],402
'client_id' => $r['client_id'],403
];404
}405
return $incoming;406
}407
408
public function updateSnapshot(string $userId, ?array $snapshot, ?int $score, bool $eliminated): void409
{410
$lobby = $this->lobbyForUser($userId);411
if (!$lobby || $lobby['status'] !== 'playing') {412
return;413
}414
$json = $snapshot !== null ? json_encode($snapshot, JSON_UNESCAPED_UNICODE) : null;415
$fields = 'last_seen = ?';416
$args = [$this->now()];417
if ($json !== null) {418
$fields .= ', snapshot = ?';419
$args[] = $json;420
}421
if ($score !== null) {422
$fields .= ', score = ?';423
$args[] = $score;424
}425
$args[] = $lobby['id'];426
$args[] = $userId;427
$this->pdo->prepare(428
"UPDATE members SET $fields WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL"429
)->execute($args);430
if ($eliminated) {431
$this->assignPlaceIfNeeded($lobby['id'], $userId, false);432
$this->maybeFinish($lobby['id']);433
}434
}435
436
public function member(string $lobbyId, string $userId): ?array437
{438
$stmt = $this->pdo->prepare(439
'SELECT * FROM members WHERE lobby_id = ? AND user_id = ?'440
);441
$stmt->execute([$lobbyId, $userId]);442
$row = $stmt->fetch();443
return $row ?: null;444
}445
446
private function assignPlaceIfNeeded(string $lobbyId, string $userId, bool $leaving): void447
{448
$m = $this->member($lobbyId, $userId);449
if (!$m || $m['place'] !== null) {450
return;451
}452
$active = 0;453
foreach ($this->members($lobbyId) as $row) {454
if (!(int) $row['eliminated'] && $row['user_id'] !== $userId) {455
$active++;456
}457
}458
// First out gets last place = number of current (incl. this) non-left players.459
$total = count($this->members($lobbyId));460
$alreadyPlaced = 0;461
foreach ($this->members($lobbyId, true) as $row) {462
if ($row['place'] !== null && $row['left_at'] === null || ($row['place'] !== null && $row['user_id'] !== $userId)) {463
if ($row['place'] !== null) {464
$alreadyPlaced++;465
}466
}467
}468
$place = $active + 1; // remaining others + self → this player's place469
$this->pdo->prepare(470
'UPDATE members SET eliminated = 1, place = ? WHERE lobby_id = ? AND user_id = ?'471
)->execute([$place, $lobbyId, $userId]);472
}473
474
public function maybeFinish(string $lobbyId): void475
{476
$lobby = $this->getLobby($lobbyId);477
if (!$lobby || $lobby['status'] !== 'playing') {478
return;479
}480
$alive = [];481
foreach ($this->members($lobbyId) as $m) {482
if (!(int) $m['eliminated']) {483
$alive[] = $m;484
}485
}486
if (count($alive) > 1) {487
return;488
}489
if (count($alive) === 1) {490
$winner = $alive[0];491
if ($winner['place'] === null) {492
$this->pdo->prepare(493
'UPDATE members SET place = 1 WHERE lobby_id = ? AND user_id = ?'494
)->execute([$lobbyId, $winner['user_id']]);495
}496
}497
$this->pdo->prepare(498
'UPDATE lobbies SET status = ?, finished = ? WHERE id = ?'499
)->execute(['finished', $this->now(), $lobbyId]);500
}501
502
public function maybeResetLobby(string $lobbyId): void503
{504
$lobby = $this->getLobby($lobbyId);505
if (!$lobby || $lobby['status'] !== 'finished') {506
return;507
}508
$finished = (int) ($lobby['finished'] ?? 0);509
if ($finished === 0 || time() < $finished + METEORS_PODIUM_SECONDS) {510
return;511
}512
$this->pdo->prepare(513
'UPDATE lobbies SET status = ?, started = NULL, finished = NULL WHERE id = ?'514
)->execute(['waiting', $lobbyId]);515
$this->pdo->prepare(516
'UPDATE members SET ready = 0, eliminated = 0, place = NULL, snapshot = NULL, score = 0517
WHERE lobby_id = ? AND left_at IS NULL'518
)->execute([$lobbyId]);519
$this->pdo->prepare('DELETE FROM shots WHERE lobby_id = ?')->execute([$lobbyId]);520
}521
522
/** Public view of a lobby for the given user, including incoming shots. */523
public function viewFor(string $userId, ?array $snapshot = null, ?int $score = null, bool $eliminated = false, array $outgoing = []): array524
{525
return $this->transaction(function () use ($userId, $snapshot, $score, $eliminated, $outgoing) {526
$touch = $this->lobbyForUser($userId);527
if ($touch && $touch['status'] === 'finished') {528
$this->maybeResetLobby($touch['id']);529
}530
if ($touch && $touch['status'] === 'playing') {531
if ($snapshot !== null || $score !== null || $eliminated) {532
$this->updateSnapshot($userId, $snapshot, $score, $eliminated);533
} else {534
$this->pdo->prepare(535
'UPDATE members SET last_seen = ? WHERE lobby_id = ? AND user_id = ? AND left_at IS NULL'536
)->execute([$this->now(), $touch['id'], $userId]);537
}538
}539
$shotResults = [];540
if ($outgoing && $touch && $touch['status'] === 'playing') {541
$shotResults = $this->recordShots($userId, $outgoing);542
}543
$lobby = $this->lobbyForUser($userId);544
if (!$lobby) {545
return [546
'lobby' => null,547
'incoming' => [],548
'shot_results' => $shotResults,549
];550
}551
$incoming = [];552
if ($lobby['status'] === 'playing') {553
$incoming = $this->takeIncoming($lobby['id'], $userId);554
}555
return [556
'lobby' => $this->presentLobby($lobby, $userId),557
'incoming' => $incoming,558
'shot_results' => $shotResults,559
];560
});561
}562
563
public function presentLobby(array $lobby, string $userId): array564
{565
$members = $this->members($lobby['id']);566
$players = [];567
foreach ($members as $m) {568
$snap = null;569
if (is_string($m['snapshot']) && $m['snapshot'] !== '') {570
$decoded = json_decode($m['snapshot'], true);571
$snap = is_array($decoded) ? $decoded : null;572
}573
$players[] = [574
'id' => $m['user_id'],575
'name' => $m['name'],576
'ready' => (bool) (int) $m['ready'],577
'eliminated' => (bool) (int) $m['eliminated'],578
'place' => $m['place'] !== null ? (int) $m['place'] : null,579
'is_host' => $m['user_id'] === $lobby['host_id'],580
'is_me' => $m['user_id'] === $userId,581
'score' => (int) $m['score'],582
'snapshot' => $m['user_id'] === $userId ? null : $snap,583
];584
}585
$rankings = [];586
if ($lobby['status'] === 'finished' || $lobby['finished']) {587
$all = $this->members($lobby['id'], true);588
foreach ($all as $m) {589
if ($m['place'] !== null) {590
$rankings[] = [591
'place' => (int) $m['place'],592
'id' => $m['user_id'],593
'name' => $m['name'],594
'score' => (int) $m['score'],595
];596
}597
}598
usort($rankings, fn ($a, $b) => $a['place'] <=> $b['place']);599
}600
$allReady = $players !== [] && array_reduce($players, fn ($ok, $p) => $ok && $p['ready'], true);601
return [602
'id' => $lobby['id'],603
'code' => $lobby['code'],604
'status' => $lobby['status'],605
'host_id' => $lobby['host_id'],606
'miss_chance' => (float) $lobby['miss_chance'],607
'flight_duration' => (float) $lobby['flight_duration'],608
'players' => $players,609
'all_ready' => $allReady,610
'can_start' => $lobby['status'] === 'waiting' && $lobby['host_id'] === $userId && $allReady && count($players) >= 2,611
'rankings' => $rankings,612
'finished_at' => $lobby['finished'] !== null ? (int) $lobby['finished'] : null,613
'podium_seconds' => METEORS_PODIUM_SECONDS,614
];615
}616
}@@ -0,0 +1,321 @@
1
<?php
2
declare(strict_types=1);
3
4
const METEORS_SESSION_TTL = 86400;
5
const METEORS_DEFAULT_AUTH = 'https://auth.timfalken.com';
6
const METEORS_DEFAULT_CLIENT_ID = 'projects.timfalken.com';
7
const METEORS_DEFAULT_BASE = 'https://projects.timfalken.com/meteors';
8
const METEORS_DEFAULT_MISS = 0.30;
9
const METEORS_FLIGHT_DURATION = 1.2;
10
const METEORS_MAX_PLAYERS = 32;
11
const METEORS_PODIUM_SECONDS = 5;
12
13
function dataDir(): string
14
{
15
$override = getenv('METEORS_DATA_DIR');
16
if (is_string($override) && $override !== '') {
17
return rtrim($override, '/');
18
}
19
return dirname(__DIR__) . '/data';
20
}
21
22
function ensureDataDir(): string
23
{
24
$dir = dataDir();
25
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {
26
throw new RuntimeException('De datamap moet schrijfbaar zijn.');
27
}
28
$deny = $dir . '/.htaccess';
29
if (!is_file($deny)) {
30
@file_put_contents($deny, "Require all denied\n");
31
}
32
$sessions = $dir . '/sessions';
33
if (!is_dir($sessions)) {
34
@mkdir($sessions, 0775, true);
35
}
36
return $dir;
37
}
38
39
function localDev(): bool
40
{
41
$host = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);
42
return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)
43
&& in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);
44
}
45
46
function config(): array
47
{
48
$dir = ensureDataDir();
49
$path = $dir . '/config.php';
50
$lock = fopen($dir . '/config.lock', 'c');
51
if ($lock === false) {
52
throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');
53
}
54
try {
55
if (!flock($lock, LOCK_EX)) {
56
throw new RuntimeException('De configuratie kon niet worden vergrendeld.');
57
}
58
if (!is_file($path)) {
59
$template = <<<'PHP'
60
<?php
61
// Vul deze waarden op de server in. Lege velden gebruiken omgevingsvariabelen.
62
// Productie-URL: https://projects.timfalken.com/meteors
63
// client_id is het geregistreerde domein: projects.timfalken.com.
64
// Het geheim komt uit https://auth.timfalken.com/admin (het BESTAANDE geheim
65
// van dit domein; NIET opnieuw genereren, dat breekt de andere sites).
66
// Voeg daar ook het callback-pad /meteors/callback.php toe.
67
// Dit bestand wordt niet gedeployed en staat niet in git.
68
return [
69
'auth_url' => 'https://auth.timfalken.com',
70
'base_url' => 'https://projects.timfalken.com/meteors',
71
'client_id' => 'projects.timfalken.com',
72
'client_secret' => '',
73
];
74
PHP;
75
if (file_put_contents($path, $template) !== strlen($template)) {
76
throw new RuntimeException('data/config.php kon niet worden gemaakt.');
77
}
78
}
79
$values = require $path;
80
if (!is_array($values)) {
81
throw new RuntimeException('data/config.php moet een array teruggeven.');
82
}
83
} finally {
84
flock($lock, LOCK_UN);
85
fclose($lock);
86
}
87
foreach ([
88
'auth_url' => 'METEORS_AUTH_URL',
89
'base_url' => 'METEORS_BASE_URL',
90
'client_id' => 'METEORS_CLIENT_ID',
91
'client_secret' => 'METEORS_CLIENT_SECRET',
92
] as $key => $env) {
93
if (($values[$key] ?? '') === '') {
94
$values[$key] = getenv($env) ?: '';
95
}
96
}
97
if (($values['auth_url'] ?? '') === '') {
98
$values['auth_url'] = METEORS_DEFAULT_AUTH;
99
}
100
if (($values['client_id'] ?? '') === '') {
101
$values['client_id'] = METEORS_DEFAULT_CLIENT_ID;
102
}
103
return $values;
104
}
105
106
function authConfigured(): bool
107
{
108
$c = config();
109
return ($c['client_secret'] ?? '') !== ''
110
&& ($c['client_id'] ?? '') !== ''
111
&& ($c['base_url'] ?? '') !== '';
112
}
113
114
function baseUrl(): string
115
{
116
if (localDev()) {
117
$dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');
118
if ($dir === '/' || $dir === '.') {
119
$dir = '';
120
}
121
return 'http://' . $_SERVER['HTTP_HOST'] . $dir;
122
}
123
$base = rtrim((string) (config()['base_url'] ?? ''), '/');
124
if (!str_starts_with($base, 'https://')) {
125
throw new RuntimeException(
126
"Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie "
127
. '(https://projects.timfalken.com/meteors), of zet METEORS_BASE_URL.'
128
);
129
}
130
return $base;
131
}
132
133
function authUrl(): string
134
{
135
$url = rtrim((string) (config()['auth_url'] ?? METEORS_DEFAULT_AUTH), '/');
136
return $url !== '' ? $url : METEORS_DEFAULT_AUTH;
137
}
138
139
function authRequest(string $path, ?array $form = null, ?string $token = null): array
140
{
141
$ch = curl_init(authUrl() . $path);
142
$headers = ['Accept: application/json', 'User-Agent: Meteors/1.0'];
143
if ($token) {
144
$headers[] = 'Authorization: Bearer ' . $token;
145
}
146
curl_setopt_array($ch, [
147
CURLOPT_RETURNTRANSFER => true,
148
CURLOPT_TIMEOUT => 15,
149
CURLOPT_HTTPHEADER => $headers,
150
]);
151
if ($form !== null) {
152
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);
153
}
154
$body = curl_exec($ch);
155
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
156
$err = curl_error($ch);
157
curl_close($ch);
158
$data = is_string($body) ? json_decode($body, true) : null;
159
if ($status !== 200 || !is_array($data)) {
160
$hint = $err !== '' ? ' (' . $err . ')' : '';
161
throw new RuntimeException(
162
'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint
163
);
164
}
165
return $data;
166
}
167
168
/** @return array{0:string,1:string} */
169
function authIdentity(array $profile): array
170
{
171
if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {
172
throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');
173
}
174
$raw = $profile['id'];
175
$numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));
176
if (!$numeric || (int) $raw < 1) {
177
throw new RuntimeException('Ongeldig account-id.');
178
}
179
return ['auth:' . (int) $raw, $profile['username']];
180
}
181
182
function loginUser(string $id, string $name): void
183
{
184
if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) {
185
throw new RuntimeException('Ongeldig account.');
186
}
187
$name = trim($name);
188
if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {
189
throw new RuntimeException('Ongeldige gebruikersnaam.');
190
}
191
session_regenerate_id(true);
192
$_SESSION['user'] = $id;
193
$_SESSION['name'] = $name;
194
$_SESSION['csrf'] = bin2hex(random_bytes(24));
195
$_SESSION['expires'] = time() + METEORS_SESSION_TTL;
196
}
197
198
function logoutUser(): void
199
{
200
$_SESSION = [];
201
if (ini_get('session.use_cookies')) {
202
$p = session_get_cookie_params();
203
setcookie(session_name(), '', [
204
'expires' => time() - 3600,
205
'path' => $p['path'] ?? '/',
206
'secure' => (bool) ($p['secure'] ?? false),
207
'httponly' => true,
208
'samesite' => 'Lax',
209
]);
210
}
211
session_destroy();
212
}
213
214
function currentUser(): ?array
215
{
216
$id = $_SESSION['user'] ?? null;
217
$name = $_SESSION['name'] ?? null;
218
if (!is_string($id) || $id === '' || !is_string($name)) {
219
return null;
220
}
221
if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {
222
return null;
223
}
224
return ['id' => $id, 'name' => $name];
225
}
226
227
function requireUser(): array
228
{
229
$u = currentUser();
230
if (!$u) {
231
jsonFail('Log in om verder te gaan.', 401);
232
}
233
return $u;
234
}
235
236
function csrfToken(): string
237
{
238
if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {
239
$_SESSION['csrf'] = bin2hex(random_bytes(24));
240
}
241
return $_SESSION['csrf'];
242
}
243
244
function requireCsrf(): void
245
{
246
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {
247
return;
248
}
249
$got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';
250
if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {
251
jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);
252
}
253
}
254
255
function jsonOut(array $data, int $status = 200): never
256
{
257
http_response_code($status);
258
header('Content-Type: application/json; charset=utf-8');
259
header('Cache-Control: no-store');
260
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
261
exit;
262
}
263
264
function jsonFail(string $message, int $status = 400): never
265
{
266
jsonOut(['ok' => false, 'error' => $message], $status);
267
}
268
269
function readJsonBody(): array
270
{
271
$raw = file_get_contents('php://input');
272
if (!is_string($raw) || $raw === '') {
273
return $_POST;
274
}
275
$data = json_decode($raw, true);
276
return is_array($data) ? $data : [];
277
}
278
279
function startMeteorsSession(): void
280
{
281
if (session_status() === PHP_SESSION_ACTIVE) {
282
return;
283
}
284
$dir = ensureDataDir() . '/sessions';
285
if (!is_dir($dir)) {
286
@mkdir($dir, 0775, true);
287
}
288
session_name('meteors_session');
289
ini_set('session.use_strict_mode', '1');
290
ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);
291
session_save_path($dir);
292
$path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';
293
if ($path === '//') {
294
$path = '/';
295
}
296
$secure = !localDev();
297
session_set_cookie_params([
298
'lifetime' => METEORS_SESSION_TTL,
299
'path' => $path,
300
'secure' => $secure,
301
'httponly' => true,
302
'samesite' => 'Lax',
303
]);
304
session_start();
305
if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {
306
setcookie(session_name(), session_id(), [
307
'expires' => time() + METEORS_SESSION_TTL,
308
'path' => $path,
309
'secure' => $secure,
310
'httponly' => true,
311
'samesite' => 'Lax',
312
]);
313
}
314
if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {
315
$_SESSION['expires'] = time() + METEORS_SESSION_TTL;
316
}
317
}
318
319
if (!defined('METEORS_NO_SESSION')) {
320
startMeteorsSession();
321
}
@@ -0,0 +1,321 @@1
<?php2
declare(strict_types=1);3
4
const METEORS_SESSION_TTL = 86400;5
const METEORS_DEFAULT_AUTH = 'https://auth.timfalken.com';6
const METEORS_DEFAULT_CLIENT_ID = 'projects.timfalken.com';7
const METEORS_DEFAULT_BASE = 'https://projects.timfalken.com/meteors';8
const METEORS_DEFAULT_MISS = 0.30;9
const METEORS_FLIGHT_DURATION = 1.2;10
const METEORS_MAX_PLAYERS = 32;11
const METEORS_PODIUM_SECONDS = 5;12
13
function dataDir(): string14
{15
$override = getenv('METEORS_DATA_DIR');16
if (is_string($override) && $override !== '') {17
return rtrim($override, '/');18
}19
return dirname(__DIR__) . '/data';20
}21
22
function ensureDataDir(): string23
{24
$dir = dataDir();25
if (!is_dir($dir) && !mkdir($dir, 0775, true) && !is_dir($dir)) {26
throw new RuntimeException('De datamap moet schrijfbaar zijn.');27
}28
$deny = $dir . '/.htaccess';29
if (!is_file($deny)) {30
@file_put_contents($deny, "Require all denied\n");31
}32
$sessions = $dir . '/sessions';33
if (!is_dir($sessions)) {34
@mkdir($sessions, 0775, true);35
}36
return $dir;37
}38
39
function localDev(): bool40
{41
$host = parse_url('http://' . ($_SERVER['HTTP_HOST'] ?? ''), PHP_URL_HOST);42
return is_string($host) && in_array(strtolower($host), ['localhost', '127.0.0.1', '[::1]'], true)43
&& in_array($_SERVER['REMOTE_ADDR'] ?? '', ['127.0.0.1', '::1'], true);44
}45
46
function config(): array47
{48
$dir = ensureDataDir();49
$path = $dir . '/config.php';50
$lock = fopen($dir . '/config.lock', 'c');51
if ($lock === false) {52
throw new RuntimeException('De datamap moet schrijfbaar zijn om de configuratie te maken.');53
}54
try {55
if (!flock($lock, LOCK_EX)) {56
throw new RuntimeException('De configuratie kon niet worden vergrendeld.');57
}58
if (!is_file($path)) {59
$template = <<<'PHP'60
<?php61
// Vul deze waarden op de server in. Lege velden gebruiken omgevingsvariabelen.62
// Productie-URL: https://projects.timfalken.com/meteors63
// client_id is het geregistreerde domein: projects.timfalken.com.64
// Het geheim komt uit https://auth.timfalken.com/admin (het BESTAANDE geheim65
// van dit domein; NIET opnieuw genereren, dat breekt de andere sites).66
// Voeg daar ook het callback-pad /meteors/callback.php toe.67
// Dit bestand wordt niet gedeployed en staat niet in git.68
return [69
'auth_url' => 'https://auth.timfalken.com',70
'base_url' => 'https://projects.timfalken.com/meteors',71
'client_id' => 'projects.timfalken.com',72
'client_secret' => '',73
];74
PHP;75
if (file_put_contents($path, $template) !== strlen($template)) {76
throw new RuntimeException('data/config.php kon niet worden gemaakt.');77
}78
}79
$values = require $path;80
if (!is_array($values)) {81
throw new RuntimeException('data/config.php moet een array teruggeven.');82
}83
} finally {84
flock($lock, LOCK_UN);85
fclose($lock);86
}87
foreach ([88
'auth_url' => 'METEORS_AUTH_URL',89
'base_url' => 'METEORS_BASE_URL',90
'client_id' => 'METEORS_CLIENT_ID',91
'client_secret' => 'METEORS_CLIENT_SECRET',92
] as $key => $env) {93
if (($values[$key] ?? '') === '') {94
$values[$key] = getenv($env) ?: '';95
}96
}97
if (($values['auth_url'] ?? '') === '') {98
$values['auth_url'] = METEORS_DEFAULT_AUTH;99
}100
if (($values['client_id'] ?? '') === '') {101
$values['client_id'] = METEORS_DEFAULT_CLIENT_ID;102
}103
return $values;104
}105
106
function authConfigured(): bool107
{108
$c = config();109
return ($c['client_secret'] ?? '') !== ''110
&& ($c['client_id'] ?? '') !== ''111
&& ($c['base_url'] ?? '') !== '';112
}113
114
function baseUrl(): string115
{116
if (localDev()) {117
$dir = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/');118
if ($dir === '/' || $dir === '.') {119
$dir = '';120
}121
return 'http://' . $_SERVER['HTTP_HOST'] . $dir;122
}123
$base = rtrim((string) (config()['base_url'] ?? ''), '/');124
if (!str_starts_with($base, 'https://')) {125
throw new RuntimeException(126
"Zet 'base_url' in data/config.php op de HTTPS-URL van deze installatie "127
. '(https://projects.timfalken.com/meteors), of zet METEORS_BASE_URL.'128
);129
}130
return $base;131
}132
133
function authUrl(): string134
{135
$url = rtrim((string) (config()['auth_url'] ?? METEORS_DEFAULT_AUTH), '/');136
return $url !== '' ? $url : METEORS_DEFAULT_AUTH;137
}138
139
function authRequest(string $path, ?array $form = null, ?string $token = null): array140
{141
$ch = curl_init(authUrl() . $path);142
$headers = ['Accept: application/json', 'User-Agent: Meteors/1.0'];143
if ($token) {144
$headers[] = 'Authorization: Bearer ' . $token;145
}146
curl_setopt_array($ch, [147
CURLOPT_RETURNTRANSFER => true,148
CURLOPT_TIMEOUT => 15,149
CURLOPT_HTTPHEADER => $headers,150
]);151
if ($form !== null) {152
curl_setopt_array($ch, [CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($form)]);153
}154
$body = curl_exec($ch);155
$status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);156
$err = curl_error($ch);157
curl_close($ch);158
$data = is_string($body) ? json_decode($body, true) : null;159
if ($status !== 200 || !is_array($data)) {160
$hint = $err !== '' ? ' (' . $err . ')' : '';161
throw new RuntimeException(162
'De authenticatiedienst is niet bereikbaar of de sessie is verlopen.' . $hint163
);164
}165
return $data;166
}167
168
/** @return array{0:string,1:string} */169
function authIdentity(array $profile): array170
{171
if (!isset($profile['id'], $profile['username']) || !is_string($profile['username'])) {172
throw new RuntimeException('Het profiel mist een id of gebruikersnaam.');173
}174
$raw = $profile['id'];175
$numeric = is_int($raw) || (is_string($raw) && preg_match('/^[1-9][0-9]{0,17}$/', $raw));176
if (!$numeric || (int) $raw < 1) {177
throw new RuntimeException('Ongeldig account-id.');178
}179
return ['auth:' . (int) $raw, $profile['username']];180
}181
182
function loginUser(string $id, string $name): void183
{184
if (!preg_match('/^(?:local:test_user_[12]|auth:[1-9][0-9]{0,17})$/', $id)) {185
throw new RuntimeException('Ongeldig account.');186
}187
$name = trim($name);188
if ($name === '' || mb_strlen($name) > 64 || preg_match('/[\x00-\x1F]/', $name)) {189
throw new RuntimeException('Ongeldige gebruikersnaam.');190
}191
session_regenerate_id(true);192
$_SESSION['user'] = $id;193
$_SESSION['name'] = $name;194
$_SESSION['csrf'] = bin2hex(random_bytes(24));195
$_SESSION['expires'] = time() + METEORS_SESSION_TTL;196
}197
198
function logoutUser(): void199
{200
$_SESSION = [];201
if (ini_get('session.use_cookies')) {202
$p = session_get_cookie_params();203
setcookie(session_name(), '', [204
'expires' => time() - 3600,205
'path' => $p['path'] ?? '/',206
'secure' => (bool) ($p['secure'] ?? false),207
'httponly' => true,208
'samesite' => 'Lax',209
]);210
}211
session_destroy();212
}213
214
function currentUser(): ?array215
{216
$id = $_SESSION['user'] ?? null;217
$name = $_SESSION['name'] ?? null;218
if (!is_string($id) || $id === '' || !is_string($name)) {219
return null;220
}221
if (!localDev() && (($_SESSION['expires'] ?? 0) < time())) {222
return null;223
}224
return ['id' => $id, 'name' => $name];225
}226
227
function requireUser(): array228
{229
$u = currentUser();230
if (!$u) {231
jsonFail('Log in om verder te gaan.', 401);232
}233
return $u;234
}235
236
function csrfToken(): string237
{238
if (empty($_SESSION['csrf']) || !is_string($_SESSION['csrf'])) {239
$_SESSION['csrf'] = bin2hex(random_bytes(24));240
}241
return $_SESSION['csrf'];242
}243
244
function requireCsrf(): void245
{246
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'GET') {247
return;248
}249
$got = $_SERVER['HTTP_X_CSRF_TOKEN'] ?? '';250
if (!is_string($got) || $got === '' || !hash_equals(csrfToken(), $got)) {251
jsonFail('Ongeldige of ontbrekende CSRF-token.', 403);252
}253
}254
255
function jsonOut(array $data, int $status = 200): never256
{257
http_response_code($status);258
header('Content-Type: application/json; charset=utf-8');259
header('Cache-Control: no-store');260
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);261
exit;262
}263
264
function jsonFail(string $message, int $status = 400): never265
{266
jsonOut(['ok' => false, 'error' => $message], $status);267
}268
269
function readJsonBody(): array270
{271
$raw = file_get_contents('php://input');272
if (!is_string($raw) || $raw === '') {273
return $_POST;274
}275
$data = json_decode($raw, true);276
return is_array($data) ? $data : [];277
}278
279
function startMeteorsSession(): void280
{281
if (session_status() === PHP_SESSION_ACTIVE) {282
return;283
}284
$dir = ensureDataDir() . '/sessions';285
if (!is_dir($dir)) {286
@mkdir($dir, 0775, true);287
}288
session_name('meteors_session');289
ini_set('session.use_strict_mode', '1');290
ini_set('session.gc_maxlifetime', (string) METEORS_SESSION_TTL);291
session_save_path($dir);292
$path = rtrim(str_replace('\\', '/', dirname($_SERVER['SCRIPT_NAME'] ?? '')), '/') . '/';293
if ($path === '//') {294
$path = '/';295
}296
$secure = !localDev();297
session_set_cookie_params([298
'lifetime' => METEORS_SESSION_TTL,299
'path' => $path,300
'secure' => $secure,301
'httponly' => true,302
'samesite' => 'Lax',303
]);304
session_start();305
if (session_status() === PHP_SESSION_ACTIVE && session_id() !== '') {306
setcookie(session_name(), session_id(), [307
'expires' => time() + METEORS_SESSION_TTL,308
'path' => $path,309
'secure' => $secure,310
'httponly' => true,311
'samesite' => 'Lax',312
]);313
}314
if (isset($_SESSION['expires']) && is_int($_SESSION['expires']) && currentUser()) {315
$_SESSION['expires'] = time() + METEORS_SESSION_TTL;316
}317
}318
319
if (!defined('METEORS_NO_SESSION')) {320
startMeteorsSession();321
}@@ -0,0 +1,11 @@
1
<?php
2
declare(strict_types=1);
3
require __DIR__ . '/lib/bootstrap.php';
4
logoutUser();
5
if (isset($_GET['json'])) {
6
// Session is destroyed; a new empty one may start on next request.
7
header('Content-Type: application/json; charset=utf-8');
8
echo json_encode(['ok' => true]);
9
exit;
10
}
11
header('Location: index.html');
@@ -0,0 +1,11 @@1
<?php2
declare(strict_types=1);3
require __DIR__ . '/lib/bootstrap.php';4
logoutUser();5
if (isset($_GET['json'])) {6
// Session is destroyed; a new empty one may start on next request.7
header('Content-Type: application/json; charset=utf-8');8
echo json_encode(['ok' => true]);9
exit;10
}11
header('Location: index.html');@@ -0,0 +1,20 @@
1
<?php
2
declare(strict_types=1);
3
// Router for PHP's built-in server: php -S 127.0.0.1:8080 -t build server/router.php
4
// (copied to build/router.php; the -t directory is the docroot).
5
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/');
6
$file = __DIR__ . $uri;
7
if ($uri !== '/' && is_file($file)) {
8
return false;
9
}
10
if (str_ends_with($uri, '.php') && is_file($file)) {
11
require $file;
12
return true;
13
}
14
// Fall through to index.html for the game UI.
15
if (is_file(__DIR__ . '/index.html')) {
16
header('Content-Type: text/html; charset=utf-8');
17
readfile(__DIR__ . '/index.html');
18
return true;
19
}
20
return false;
@@ -0,0 +1,20 @@1
<?php2
declare(strict_types=1);3
// Router for PHP's built-in server: php -S 127.0.0.1:8080 -t build server/router.php4
// (copied to build/router.php; the -t directory is the docroot).5
$uri = urldecode(parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?? '/');6
$file = __DIR__ . $uri;7
if ($uri !== '/' && is_file($file)) {8
return false;9
}10
if (str_ends_with($uri, '.php') && is_file($file)) {11
require $file;12
return true;13
}14
// Fall through to index.html for the game UI.15
if (is_file(__DIR__ . '/index.html')) {16
header('Content-Type: text/html; charset=utf-8');17
readfile(__DIR__ . '/index.html');18
return true;19
}20
return false;@@ -0,0 +1,201 @@
1
<?php
2
declare(strict_types=1);
3
// php server/tests/run.php
4
define('METEORS_NO_SESSION', true);
5
require dirname(__DIR__) . '/lib/bootstrap.php';
6
require dirname(__DIR__) . '/lib/Store.php';
7
8
$failed = 0;
9
$passed = 0;
10
11
function expect(bool $cond, string $msg): void
12
{
13
global $failed, $passed;
14
if ($cond) {
15
$passed++;
16
echo " ok $msg\n";
17
} else {
18
$failed++;
19
echo " FAIL $msg\n";
20
}
21
}
22
23
function almostEqual(float $a, float $b, float $eps = 1e-6): bool
24
{
25
return abs($a - $b) <= $eps;
26
}
27
28
$tmp = sys_get_temp_dir() . '/meteors-test-' . bin2hex(random_bytes(6));
29
mkdir($tmp, 0775, true);
30
putenv('METEORS_DATA_DIR=' . $tmp);
31
32
echo "Store: lobby and game\n";
33
$store = Store::open($tmp);
34
35
$a = $store->createLobby('local:test_user_1', 'test_user_1', 0.30);
36
expect(isset($a['id'], $a['code']), 'create lobby returns id and code');
37
expect($a['status'] === 'waiting', 'new lobby is waiting');
38
expect(strlen($a['code']) === 4, 'code is 4 characters');
39
expect(almostEqual((float) $a['miss_chance'], 0.30), 'default miss chance 0.30');
40
41
$view = $store->viewFor('local:test_user_1');
42
expect($view['lobby']['players'][0]['is_host'] === true, 'creator is host');
43
expect($view['lobby']['can_start'] === false, 'cannot start alone');
44
45
try {
46
$store->startGame('local:test_user_1');
47
expect(false, 'start alone should throw');
48
} catch (RuntimeException $e) {
49
expect(str_contains($e->getMessage(), 'twee'), 'start alone is refused: ' . $e->getMessage());
50
}
51
52
$joined = $store->joinLobby('local:test_user_2', 'test_user_2', $a['code']);
53
expect($joined['id'] === $a['id'], 'second player joins by code');
54
$view = $store->viewFor('local:test_user_1');
55
expect(count($view['lobby']['players']) === 2, 'two players in lobby');
56
expect($view['lobby']['can_start'] === false, 'cannot start until both ready');
57
58
$store->setReady('local:test_user_1', true);
59
$store->setReady('local:test_user_2', true);
60
$view = $store->viewFor('local:test_user_1');
61
expect($view['lobby']['all_ready'] === true, 'all ready');
62
expect($view['lobby']['can_start'] === true, 'host can start when all ready and 2+');
63
64
$view2 = $store->viewFor('local:test_user_2');
65
expect($view2['lobby']['can_start'] === false, 'non-host cannot start');
66
67
try {
68
$store->startGame('local:test_user_2');
69
expect(false, 'non-host start should throw');
70
} catch (RuntimeException $e) {
71
expect(str_contains($e->getMessage(), 'host'), 'non-host start refused');
72
}
73
74
$started = $store->startGame('local:test_user_1');
75
expect($started['status'] === 'playing', 'game starts');
76
77
// Shots: force miss by using miss_chance 1.0 on a fresh lobby later.
78
// Here miss is 0.30 — fire many shots and check some hits and some misses, or set chance.
79
$results = $store->recordShots('local:test_user_1', [
80
['client_id' => 'c1', 'color' => 2],
81
['client_id' => 'c2', 'color' => -1],
82
]);
83
expect(count($results) === 2, 'two shot results');
84
expect(isset($results[0]['miss'], $results[0]['flight_duration']), 'result has miss and duration');
85
expect(almostEqual($results[0]['flight_duration'], METEORS_FLIGHT_DURATION), 'flight duration 1.2');
86
87
// Incoming is delayed until deliver_at.
88
$inc = $store->viewFor('local:test_user_2');
89
$hits = array_filter($results, fn ($r) => !$r['miss']);
90
if ($hits) {
91
expect(count($inc['incoming']) === 0, 'incoming not delivered before flight duration');
92
} else {
93
expect(true, 'all missed — no incoming expected');
94
}
95
96
// Fast-forward: rewrite deliver_at in the sqlite file.
97
$pdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
98
$pdo->exec('UPDATE shots SET deliver_at = 0 WHERE to_user = "local:test_user_2"');
99
$inc = $store->viewFor('local:test_user_2');
100
$expectedHits = count($hits);
101
expect(count($inc['incoming']) === $expectedHits, 'incoming delivered after deliver_at (' . count($inc['incoming']) . " vs $expectedHits)");
102
$inc2 = $store->viewFor('local:test_user_2');
103
expect(count($inc2['incoming']) === 0, 'incoming is delivered only once');
104
105
// Elimination and podium.
106
$store->updateSnapshot('local:test_user_2', ['score' => 3, 'blocks' => []], 3, true);
107
$view = $store->viewFor('local:test_user_1');
108
expect($view['lobby']['status'] === 'finished', 'game finishes when one remains');
109
$ranks = $view['lobby']['rankings'];
110
expect(count($ranks) >= 2, 'rankings present');
111
$first = $ranks[0];
112
expect($first['place'] === 1 && $first['id'] === 'local:test_user_1', 'survivor is 1st');
113
$second = $ranks[1];
114
expect($second['place'] === 2 && $second['id'] === 'local:test_user_2', 'eliminated is 2nd');
115
116
// Podium wait: not yet reset.
117
$view = $store->viewFor('local:test_user_1');
118
expect($view['lobby']['status'] === 'finished', 'still finished during podium');
119
120
$pdo->exec('UPDATE lobbies SET finished = ' . (time() - 6));
121
$view = $store->viewFor('local:test_user_1');
122
expect($view['lobby']['status'] === 'waiting', 'back to lobby after podium seconds');
123
expect($view['lobby']['players'][0]['ready'] === false, 'ready flags reset');
124
125
// Host leave transfers host.
126
$store->leaveLobby('local:test_user_1');
127
$view = $store->viewFor('local:test_user_2');
128
expect($view['lobby']['host_id'] === 'local:test_user_2', 'host transfers to remaining player');
129
130
// Mid-game leave counts as elimination.
131
$store->leaveLobby('local:test_user_2');
132
$b = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
133
$store->joinLobby('local:test_user_2', 'test_user_2', $b['code']);
134
$store->setReady('local:test_user_1', true);
135
$store->setReady('local:test_user_2', true);
136
$store->startGame('local:test_user_1');
137
$store->leaveLobby('local:test_user_2');
138
$view = $store->viewFor('local:test_user_1');
139
expect($view['lobby']['status'] === 'finished', 'leave mid-game finishes if one remains');
140
expect($view['lobby']['rankings'][0]['id'] === 'local:test_user_1', 'stayer wins');
141
142
// Miss chance 1.0: all miss. Need a fresh game with 2 players.
143
// Leave leftover memberships.
144
$store->leaveLobby('local:test_user_1');
145
$c = $store->createLobby('local:test_user_1', 'test_user_1', 1.0);
146
$store->joinLobby('local:test_user_2', 'test_user_2', $c['code']);
147
$store->setReady('local:test_user_1', true);
148
$store->setReady('local:test_user_2', true);
149
$store->startGame('local:test_user_1');
150
$allMiss = $store->recordShots('local:test_user_1', [
151
['client_id' => 'm1', 'color' => 0],
152
['client_id' => 'm2', 'color' => 1],
153
['client_id' => 'm3', 'color' => 2],
154
]);
155
expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'miss_chance 1.0 → all miss');
156
157
$d = null;
158
$store->leaveLobby('local:test_user_1');
159
$store->leaveLobby('local:test_user_2');
160
$d = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
161
$store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);
162
$store->setReady('local:test_user_1', true);
163
$store->setReady('local:test_user_2', true);
164
$store->startGame('local:test_user_1');
165
$allHit = $store->recordShots('local:test_user_1', [
166
['client_id' => 'h1', 'color' => 0],
167
['client_id' => 'h2', 'color' => 1],
168
]);
169
expect(count($allHit) === 2 && array_reduce($allHit, fn ($ok, $r) => $ok && !$r['miss'] && $r['target_id'] === 'local:test_user_2', true), 'miss_chance 0 → all hit the other player');
170
171
// Eliminated player is not a target.
172
$store->updateSnapshot('local:test_user_2', null, 0, true);
173
$none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' => 0]]);
174
// Game may already be finished; recordShots on finished returns [].
175
expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');
176
177
echo "\nConfig helpers\n";
178
$cfg = config();
179
expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
180
expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
181
expect($cfg['client_secret'] === '', 'secret starts empty (Tim must fill it in)');
182
expect(authConfigured() === false, 'auth is unconfigured without a secret');
183
putenv('METEORS_CLIENT_SECRET=test-secret-value');
184
// config file empty secret falls back to env
185
$cfg2 = config();
186
expect($cfg2['client_secret'] === 'test-secret-value', 'empty file field falls back to env');
187
putenv('METEORS_CLIENT_SECRET');
188
189
echo "\n$passed passed, $failed failed\n";
190
191
// cleanup
192
$files = new RecursiveIteratorIterator(
193
new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS),
194
RecursiveIteratorIterator::CHILD_FIRST
195
);
196
foreach ($files as $f) {
197
$f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());
198
}
199
@rmdir($tmp);
200
201
exit($failed === 0 ? 0 : 1);
@@ -0,0 +1,201 @@1
<?php2
declare(strict_types=1);3
// php server/tests/run.php4
define('METEORS_NO_SESSION', true);5
require dirname(__DIR__) . '/lib/bootstrap.php';6
require dirname(__DIR__) . '/lib/Store.php';7
8
$failed = 0;9
$passed = 0;10
11
function expect(bool $cond, string $msg): void12
{13
global $failed, $passed;14
if ($cond) {15
$passed++;16
echo " ok $msg\n";17
} else {18
$failed++;19
echo " FAIL $msg\n";20
}21
}22
23
function almostEqual(float $a, float $b, float $eps = 1e-6): bool24
{25
return abs($a - $b) <= $eps;26
}27
28
$tmp = sys_get_temp_dir() . '/meteors-test-' . bin2hex(random_bytes(6));29
mkdir($tmp, 0775, true);30
putenv('METEORS_DATA_DIR=' . $tmp);31
32
echo "Store: lobby and game\n";33
$store = Store::open($tmp);34
35
$a = $store->createLobby('local:test_user_1', 'test_user_1', 0.30);36
expect(isset($a['id'], $a['code']), 'create lobby returns id and code');37
expect($a['status'] === 'waiting', 'new lobby is waiting');38
expect(strlen($a['code']) === 4, 'code is 4 characters');39
expect(almostEqual((float) $a['miss_chance'], 0.30), 'default miss chance 0.30');40
41
$view = $store->viewFor('local:test_user_1');42
expect($view['lobby']['players'][0]['is_host'] === true, 'creator is host');43
expect($view['lobby']['can_start'] === false, 'cannot start alone');44
45
try {46
$store->startGame('local:test_user_1');47
expect(false, 'start alone should throw');48
} catch (RuntimeException $e) {49
expect(str_contains($e->getMessage(), 'twee'), 'start alone is refused: ' . $e->getMessage());50
}51
52
$joined = $store->joinLobby('local:test_user_2', 'test_user_2', $a['code']);53
expect($joined['id'] === $a['id'], 'second player joins by code');54
$view = $store->viewFor('local:test_user_1');55
expect(count($view['lobby']['players']) === 2, 'two players in lobby');56
expect($view['lobby']['can_start'] === false, 'cannot start until both ready');57
58
$store->setReady('local:test_user_1', true);59
$store->setReady('local:test_user_2', true);60
$view = $store->viewFor('local:test_user_1');61
expect($view['lobby']['all_ready'] === true, 'all ready');62
expect($view['lobby']['can_start'] === true, 'host can start when all ready and 2+');63
64
$view2 = $store->viewFor('local:test_user_2');65
expect($view2['lobby']['can_start'] === false, 'non-host cannot start');66
67
try {68
$store->startGame('local:test_user_2');69
expect(false, 'non-host start should throw');70
} catch (RuntimeException $e) {71
expect(str_contains($e->getMessage(), 'host'), 'non-host start refused');72
}73
74
$started = $store->startGame('local:test_user_1');75
expect($started['status'] === 'playing', 'game starts');76
77
// Shots: force miss by using miss_chance 1.0 on a fresh lobby later.78
// Here miss is 0.30 — fire many shots and check some hits and some misses, or set chance.79
$results = $store->recordShots('local:test_user_1', [80
['client_id' => 'c1', 'color' => 2],81
['client_id' => 'c2', 'color' => -1],82
]);83
expect(count($results) === 2, 'two shot results');84
expect(isset($results[0]['miss'], $results[0]['flight_duration']), 'result has miss and duration');85
expect(almostEqual($results[0]['flight_duration'], METEORS_FLIGHT_DURATION), 'flight duration 1.2');86
87
// Incoming is delayed until deliver_at.88
$inc = $store->viewFor('local:test_user_2');89
$hits = array_filter($results, fn ($r) => !$r['miss']);90
if ($hits) {91
expect(count($inc['incoming']) === 0, 'incoming not delivered before flight duration');92
} else {93
expect(true, 'all missed — no incoming expected');94
}95
96
// Fast-forward: rewrite deliver_at in the sqlite file.97
$pdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');98
$pdo->exec('UPDATE shots SET deliver_at = 0 WHERE to_user = "local:test_user_2"');99
$inc = $store->viewFor('local:test_user_2');100
$expectedHits = count($hits);101
expect(count($inc['incoming']) === $expectedHits, 'incoming delivered after deliver_at (' . count($inc['incoming']) . " vs $expectedHits)");102
$inc2 = $store->viewFor('local:test_user_2');103
expect(count($inc2['incoming']) === 0, 'incoming is delivered only once');104
105
// Elimination and podium.106
$store->updateSnapshot('local:test_user_2', ['score' => 3, 'blocks' => []], 3, true);107
$view = $store->viewFor('local:test_user_1');108
expect($view['lobby']['status'] === 'finished', 'game finishes when one remains');109
$ranks = $view['lobby']['rankings'];110
expect(count($ranks) >= 2, 'rankings present');111
$first = $ranks[0];112
expect($first['place'] === 1 && $first['id'] === 'local:test_user_1', 'survivor is 1st');113
$second = $ranks[1];114
expect($second['place'] === 2 && $second['id'] === 'local:test_user_2', 'eliminated is 2nd');115
116
// Podium wait: not yet reset.117
$view = $store->viewFor('local:test_user_1');118
expect($view['lobby']['status'] === 'finished', 'still finished during podium');119
120
$pdo->exec('UPDATE lobbies SET finished = ' . (time() - 6));121
$view = $store->viewFor('local:test_user_1');122
expect($view['lobby']['status'] === 'waiting', 'back to lobby after podium seconds');123
expect($view['lobby']['players'][0]['ready'] === false, 'ready flags reset');124
125
// Host leave transfers host.126
$store->leaveLobby('local:test_user_1');127
$view = $store->viewFor('local:test_user_2');128
expect($view['lobby']['host_id'] === 'local:test_user_2', 'host transfers to remaining player');129
130
// Mid-game leave counts as elimination.131
$store->leaveLobby('local:test_user_2');132
$b = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);133
$store->joinLobby('local:test_user_2', 'test_user_2', $b['code']);134
$store->setReady('local:test_user_1', true);135
$store->setReady('local:test_user_2', true);136
$store->startGame('local:test_user_1');137
$store->leaveLobby('local:test_user_2');138
$view = $store->viewFor('local:test_user_1');139
expect($view['lobby']['status'] === 'finished', 'leave mid-game finishes if one remains');140
expect($view['lobby']['rankings'][0]['id'] === 'local:test_user_1', 'stayer wins');141
142
// Miss chance 1.0: all miss. Need a fresh game with 2 players.143
// Leave leftover memberships.144
$store->leaveLobby('local:test_user_1');145
$c = $store->createLobby('local:test_user_1', 'test_user_1', 1.0);146
$store->joinLobby('local:test_user_2', 'test_user_2', $c['code']);147
$store->setReady('local:test_user_1', true);148
$store->setReady('local:test_user_2', true);149
$store->startGame('local:test_user_1');150
$allMiss = $store->recordShots('local:test_user_1', [151
['client_id' => 'm1', 'color' => 0],152
['client_id' => 'm2', 'color' => 1],153
['client_id' => 'm3', 'color' => 2],154
]);155
expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'miss_chance 1.0 → all miss');156
157
$d = null;158
$store->leaveLobby('local:test_user_1');159
$store->leaveLobby('local:test_user_2');160
$d = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);161
$store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);162
$store->setReady('local:test_user_1', true);163
$store->setReady('local:test_user_2', true);164
$store->startGame('local:test_user_1');165
$allHit = $store->recordShots('local:test_user_1', [166
['client_id' => 'h1', 'color' => 0],167
['client_id' => 'h2', 'color' => 1],168
]);169
expect(count($allHit) === 2 && array_reduce($allHit, fn ($ok, $r) => $ok && !$r['miss'] && $r['target_id'] === 'local:test_user_2', true), 'miss_chance 0 → all hit the other player');170
171
// Eliminated player is not a target.172
$store->updateSnapshot('local:test_user_2', null, 0, true);173
$none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' => 0]]);174
// Game may already be finished; recordShots on finished returns [].175
expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');176
177
echo "\nConfig helpers\n";178
$cfg = config();179
expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');180
expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');181
expect($cfg['client_secret'] === '', 'secret starts empty (Tim must fill it in)');182
expect(authConfigured() === false, 'auth is unconfigured without a secret');183
putenv('METEORS_CLIENT_SECRET=test-secret-value');184
// config file empty secret falls back to env185
$cfg2 = config();186
expect($cfg2['client_secret'] === 'test-secret-value', 'empty file field falls back to env');187
putenv('METEORS_CLIENT_SECRET');188
189
echo "\n$passed passed, $failed failed\n";190
191
// cleanup192
$files = new RecursiveIteratorIterator(193
new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS),194
RecursiveIteratorIterator::CHILD_FIRST195
);196
foreach ($files as $f) {197
$f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());198
}199
@rmdir($tmp);200
201
exit($failed === 0 ? 0 : 1);