BlueGit

projects-timfalken-com meteors

Files

meteors / server / tests / run.php

run.php

run.php 46.7 KiB Download Raw
1<?php
2declare(strict_types=1);
3// php server/tests/run.php
4define('METEORS_NO_SESSION', true);
5require dirname(__DIR__) . '/lib/bootstrap.php';
6require dirname(__DIR__) . '/lib/Store.php';
7
8$failed = 0;
9$passed = 0;
10
11function 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
23function 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));
29mkdir($tmp, 0775, true);
30putenv('METEORS_DATA_DIR=' . $tmp);
31
32echo "Login return target (t1193)\n";
33expect(loginReturnTarget(null) === 'menu', 'no return param → main menu');
34expect(loginReturnTarget('') === 'menu', 'empty return → main menu');
35expect(loginReturnTarget('online') === 'online', 'return=online → online play');
36expect(loginReturnTarget('https://evil.example/') === 'menu', 'unknown/URL value → main menu (no open redirect)');
37expect(loginReturnTarget(['online']) === 'menu', 'array value → main menu');
38expect(loginReturnPath('menu') === 'index.html', 'menu path has no online flag');
39expect(loginReturnPath(null) === 'index.html', 'missing session value → menu');
40expect(loginReturnPath('online') === 'index.html?online=1', 'online path opens the online panel');
41$cbSrc = (string) file_get_contents(dirname(__DIR__) . '/callback.php');
42expect(strpos($cbSrc, "index.html?online=1'") === false, 'callback no longer hard-codes ?online=1');
43expect(strpos($cbSrc, 'loginReturnPath(') !== false, 'callback uses loginReturnPath');
44$authSrc = (string) file_get_contents(dirname(__DIR__) . '/auth.php');
45expect(strpos($authSrc, "loginReturnTarget(\$_GET['return']") !== false, 'auth.php stores the return target');
46
47echo "Store: lobby and game\n";
48$store = Store::open($tmp);
49
50$a = $store->createLobby('local:test_user_1', 'test_user_1', 0.30);
51expect(isset($a['id'], $a['code']), 'create lobby returns id and code');
52expect($a['status'] === 'waiting', 'new lobby is waiting');
53expect(strlen($a['code']) === 4, 'code is 4 characters');
54expect(almostEqual((float) $a['miss_chance'], 0.30), 'default miss chance 0.30');
55
56$view = $store->viewFor('local:test_user_1');
57expect($view['lobby']['players'][0]['is_host'] === true, 'creator is host');
58expect($view['lobby']['can_start'] === false, 'cannot start alone');
59
60try {
61 $store->startGame('local:test_user_1');
62 expect(false, 'start alone should throw');
63} catch (RuntimeException $e) {
64 expect(str_contains($e->getMessage(), 'twee'), 'start alone is refused: ' . $e->getMessage());
65}
66
67$joined = $store->joinLobby('local:test_user_2', 'test_user_2', $a['code']);
68expect($joined['id'] === $a['id'], 'second player joins by code');
69$view = $store->viewFor('local:test_user_1');
70expect(count($view['lobby']['players']) === 2, 'two players in lobby');
71expect($view['lobby']['can_start'] === false, 'cannot start until both ready');
72
73$store->setReady('local:test_user_1', true);
74$store->setReady('local:test_user_2', true);
75$view = $store->viewFor('local:test_user_1');
76expect($view['lobby']['all_ready'] === true, 'all ready');
77expect($view['lobby']['can_start'] === true, 'host can start when all ready and 2+');
78
79$view2 = $store->viewFor('local:test_user_2');
80expect($view2['lobby']['can_start'] === false, 'non-host cannot start');
81
82try {
83 $store->startGame('local:test_user_2');
84 expect(false, 'non-host start should throw');
85} catch (RuntimeException $e) {
86 expect(str_contains($e->getMessage(), 'host'), 'non-host start refused');
87}
88
89$started = $store->startGame('local:test_user_1');
90expect($started['status'] === 'playing', 'game starts');
91
92// Shots: force miss by using miss_chance 1.0 on a fresh lobby later.
93// Here miss is 0.30 — fire many shots and check some hits and some misses, or set chance.
94$results = $store->recordShots('local:test_user_1', [
95 ['client_id' => 'c1', 'color' => 2],
96 ['client_id' => 'c2', 'color' => -1],
97]);
98expect(count($results) === 2, 'two shot results');
99expect(isset($results[0]['miss'], $results[0]['flight_duration']), 'result has miss and duration');
100expect(almostEqual($results[0]['flight_duration'], METEORS_FLIGHT_DURATION), 'flight duration 1.2');
101
102// Incoming is delayed until deliver_at.
103$inc = $store->viewFor('local:test_user_2');
104$hits = array_filter($results, fn ($r) => !$r['miss']);
105if ($hits) {
106 expect(count($inc['incoming']) === 0, 'incoming not delivered before flight duration');
107} else {
108 expect(true, 'all missed — no incoming expected');
109}
110
111// Fast-forward: rewrite deliver_at in the sqlite file.
112$pdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
113$pdo->exec('UPDATE shots SET deliver_at = 0 WHERE to_user = "local:test_user_2"');
114$inc = $store->viewFor('local:test_user_2');
115$expectedHits = count($hits);
116expect(count($inc['incoming']) === $expectedHits, 'incoming delivered after deliver_at (' . count($inc['incoming']) . " vs $expectedHits)");
117$inc2 = $store->viewFor('local:test_user_2');
118expect(count($inc2['incoming']) === 0, 'incoming is delivered only once');
119
120// Elimination and podium.
121$store->updateSnapshot('local:test_user_2', ['score' => 3, 'blocks' => []], 3, true);
122$view = $store->viewFor('local:test_user_1');
123expect($view['lobby']['status'] === 'finished', 'game finishes when one remains');
124$ranks = $view['lobby']['rankings'];
125expect(count($ranks) >= 2, 'rankings present');
126$first = $ranks[0];
127expect($first['place'] === 1 && $first['id'] === 'local:test_user_1', 'survivor is 1st');
128$second = $ranks[1];
129expect($second['place'] === 2 && $second['id'] === 'local:test_user_2', 'eliminated is 2nd');
130
131// Podium wait: not yet reset.
132$view = $store->viewFor('local:test_user_1');
133expect($view['lobby']['status'] === 'finished', 'still finished during podium');
134
135$pdo->exec('UPDATE lobbies SET finished = ' . (time() - 6));
136$view = $store->viewFor('local:test_user_1');
137expect($view['lobby']['status'] === 'waiting', 'back to lobby after podium seconds');
138expect($view['lobby']['players'][0]['ready'] === false, 'ready flags reset');
139
140// Host leave transfers host.
141$store->leaveLobby('local:test_user_1');
142$view = $store->viewFor('local:test_user_2');
143expect($view['lobby']['host_id'] === 'local:test_user_2', 'host transfers to remaining player');
144
145// Mid-game leave counts as elimination.
146$store->leaveLobby('local:test_user_2');
147$b = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
148$store->joinLobby('local:test_user_2', 'test_user_2', $b['code']);
149$store->setReady('local:test_user_1', true);
150$store->setReady('local:test_user_2', true);
151$store->startGame('local:test_user_1');
152$store->leaveLobby('local:test_user_2');
153$view = $store->viewFor('local:test_user_1');
154expect($view['lobby']['status'] === 'finished', 'leave mid-game finishes if one remains');
155expect($view['lobby']['rankings'][0]['id'] === 'local:test_user_1', 'stayer wins');
156
157// Miss chance 1.0: all miss. Need a fresh game with 2 players.
158// Leave leftover memberships.
159$store->leaveLobby('local:test_user_1');
160$c = $store->createLobby('local:test_user_1', 'test_user_1', 1.0);
161$store->joinLobby('local:test_user_2', 'test_user_2', $c['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$store->testMissOverride = 1.0;
166$allMiss = $store->recordShots('local:test_user_1', [
167 ['client_id' => 'm1', 'color' => 0],
168 ['client_id' => 'm2', 'color' => 1],
169 ['client_id' => 'm3', 'color' => 2],
170]);
171$store->testMissOverride = null;
172expect(count($allMiss) === 3 && array_reduce($allMiss, fn ($ok, $r) => $ok && $r['miss'], true), 'forced miss 1.0 → all miss');
173
174$d = null;
175$store->leaveLobby('local:test_user_1');
176$store->leaveLobby('local:test_user_2');
177$d = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
178$store->joinLobby('local:test_user_2', 'test_user_2', $d['code']);
179$store->setReady('local:test_user_1', true);
180$store->setReady('local:test_user_2', true);
181$store->startGame('local:test_user_1');
182$store->testMissOverride = 0.0;
183$allHit = $store->recordShots('local:test_user_1', [
184 ['client_id' => 'h1', 'color' => 0],
185 ['client_id' => 'h2', 'color' => 1],
186]);
187$store->testMissOverride = null;
188expect(count($allHit) === 2 && array_reduce($allHit, fn ($ok, $r) => $ok && !$r['miss'] && $r['target_id'] === 'local:test_user_2', true), 'forced miss 0 → all hit the other player');
189
190// Eliminated player is not a target.
191$store->updateSnapshot('local:test_user_2', null, 0, true);
192$none = $store->recordShots('local:test_user_1', [['client_id' => 'x', 'color' => 0]]);
193// Game may already be finished; recordShots on finished returns [].
194expect($none === [] || $none[0]['miss'] === true, 'no living target after opponent is out');
195
196
197echo "\nPlanets and per-sender Power miss\n";
198expect(count(Planets::all()) >= 8 && count(Planets::all()) <= 12, 'catalog has 8–12 planets');
199expect(Planets::known('terra') && Planets::known('cinder') && Planets::known('aurel'), 'terra, cinder, aurel exist');
200expect(almostEqual(Planets::power(Planets::byId('aurel')), 1 / 9), 'Aurel power 1/9 (gravity 2 since t1199)');
201expect(almostEqual(Planets::missChance(Planets::byId('aurel')), 0.60 - 0.55 / 9), 'Aurel miss ~53.9%');
202expect(almostEqual(Planets::power(Planets::byId('cinder')), 1.0), 'Cinder power 1');
203expect(almostEqual(Planets::missChance(Planets::byId('cinder')), 0.05), 'Cinder miss 5%');
204$td = Planets::displayValues(Planets::byId('terra'));
205expect(almostEqual($td['gravity'], 9.81) && almostEqual($td['density'], 1.05) && (int) round($td['newtons']) === 104 && $td['power'] === 44, 'Terra display g/d/F/Power');
206expect(Planets::displayPower(Planets::byId('aurel')) === 10, 'Aurel displayed Power 10');
207
208echo "\nGravity minimum 2 (t1199)\n";
209foreach (Planets::all() as $pl) {
210 expect((float) $pl['jumpsToClear'] >= 2.0, 'catalog gravity >= 2: ' . $pl['id']);
211}
212foreach (['aurel', 'lunara', 'zephyr'] as $pid) {
213 expect(almostEqual((float) Planets::byId($pid)['jumpsToClear'], 2.0), "$pid raised to 2.0");
214}
215expect(Planets::GRAVITY_MIN === 2.0 && Planets::GRAVITY_MAX === 4.0, 'gravity range constants');
216expect(almostEqual(Planets::clampGravity(1.0), 2.0) && almostEqual(Planets::clampGravity(3.3), 3.3) && almostEqual(Planets::clampGravity(9), 4.0), 'clampGravity');
217$tdG = Planets::displayValues(['jumpsToClear' => 4, 'fallTime' => 3, 'riseTime' => 1.5]);
218expect(almostEqual($tdG['gravity'], 29.43) && $tdG['gravityPct'] === 300, 'gravity 4 shows 300% / 29.43 g');
219expect(Planets::displayValues(Planets::byId('terra'))['gravityPct'] === 100, 'Terra 100%');
220expect(Planets::displayPower(Planets::byId('cinder')) === 92, 'Cinder displayed Power 92 (5% miss)');
221expect(Planets::displayValues(Planets::byId('cinder'))['power'] === 92, 'Cinder displayValues Power 92');
222
223$store->leaveLobby('local:test_user_1');
224$store->leaveLobby('local:test_user_2');
225$pl = $store->createLobby('local:test_user_1', 'test_user_1', 0.30, 'aurel');
226$store->joinLobby('local:test_user_2', 'test_user_2', $pl['code'], 'cinder');
227$presented = $store->presentLobby($pl, 'local:test_user_1');
228$byId = [];
229foreach ($presented['players'] as $plr) { $byId[$plr['id']] = $plr; }
230expect($byId['local:test_user_1']['planet']['id'] === 'aurel', 'host planet aurel');
231expect($byId['local:test_user_2']['planet']['id'] === 'cinder', 'guest planet cinder');
232expect(almostEqual($byId['local:test_user_1']['planet']['miss_chance'], 0.60 - 0.55 / 9), 'host miss from Aurel Power');
233expect(almostEqual($byId['local:test_user_2']['planet']['miss_chance'], 0.05), 'guest miss from Cinder Power');
234
235$store->setPlanet('local:test_user_1', 'wisp');
236$presented = $store->presentLobby($store->getLobby($pl['id']), 'local:test_user_1');
237foreach ($presented['players'] as $plr) {
238 if ($plr['is_me']) {
239 expect($plr['planet']['id'] === 'wisp', 'setPlanet updates host to Wisp');
240 }
241}
242
243try {
244 $store->setPlanet('local:test_user_1', 'no-such-world');
245 expect(false, 'unknown planet must throw');
246} catch (RuntimeException $e) {
247 expect(true, 'unknown planet rejected');
248}
249
250$store->setReady('local:test_user_1', true);
251$store->setReady('local:test_user_2', true);
252$store->startGame('local:test_user_1');
253$me = $store->member($pl['id'], 'local:test_user_1');
254expect(almostEqual($store->missChanceForMember($me), Planets::missChanceForId('wisp')), 'in-game miss uses the sender planet');
255$guest = $store->member($pl['id'], 'local:test_user_2');
256expect(almostEqual($store->missChanceForMember($guest), 0.05), 'guest still uses Cinder Power');
257try {
258 $store->setPlanet('local:test_user_1', 'terra');
259 expect(false, 'setPlanet during play must throw');
260} catch (RuntimeException $e) {
261 expect(true, 'planet locked once the match starts');
262}
263$store->leaveLobby('local:test_user_1');
264$store->leaveLobby('local:test_user_2');
265
266echo "\nshot_flights (t1125)\n";
267$e = $store->createLobby('local:test_user_1', 'test_user_1', 0.0);
268$store->joinLobby('local:test_user_2', 'test_user_2', $e['code']);
269$store->joinLobby('local:test_user_3', 'test_user_3', $e['code']);
270$store->setReady('local:test_user_1', true);
271$store->setReady('local:test_user_2', true);
272$store->setReady('local:test_user_3', true);
273$store->startGame('local:test_user_1');
274$store->testMissOverride = 0.0;
275$shots = $store->recordShots('local:test_user_1', [
276 ['client_id' => 'f1', 'color' => 2, 'col' => 6, 'y' => 12.4],
277]);
278$store->testMissOverride = null;
279expect(count($shots) === 1, 'one recorded shot');
280expect(($shots[0]['from_id'] ?? null) === 'local:test_user_1', 'shot_results includes from_id');
281expect(isset($shots[0]['age']) && almostEqual((float) $shots[0]['age'], 0.0), 'own result age is 0');
282
283$view3 = $store->viewFor('local:test_user_3');
284expect(isset($view3['shot_flights']) && is_array($view3['shot_flights']), 'viewFor exposes shot_flights');
285$found = null;
286foreach ($view3['shot_flights'] as $f) {
287 if (($f['client_id'] ?? '') === 'f1') {
288 $found = $f;
289 break;
290 }
291}
292expect($found !== null, 'third player sees the shot in shot_flights');
293if ($found) {
294 expect($found['from_id'] === 'local:test_user_1', 'shot_flights.from_id is the shooter');
295 expect($found['target_id'] === 'local:test_user_2' || $found['target_id'] === 'local:test_user_3', 'hit lands on a living opponent');
296 expect($found['miss'] === false, 'forced hit is not a miss');
297 expect($found['age'] >= 0 && $found['age'] < 2.0, 'age is seconds since created');
298 expect(almostEqual((float) $found['flight_duration'], METEORS_FLIGHT_DURATION), 'flight_duration on shot_flights');
299 expect(isset($found['land_col']) && $found['land_col'] >= 0 && $found['land_col'] <= 9, 'shot_flights has land_col 0–9');
300 expect(($shots[0]['land_col'] ?? null) === $found['land_col'], 'recordShots and shot_flights share land_col');
301 expect(($shots[0]['col'] ?? null) === 6, 'shot_results echoes launch col');
302 expect(isset($shots[0]['y']) && abs((float) $shots[0]['y'] - 12.4) < 0.01, 'shot_results echoes launch y');
303 expect(($found['col'] ?? null) === 6, 'shot_flights has launch col (t1136)');
304 expect(isset($found['y']) && abs((float) $found['y'] - 12.4) < 0.01, 'shot_flights has launch y (t1136)');
305}
306// Incoming carries the same land_col (t1126).
307$targetId = $found['target_id'] ?? $shots[0]['target_id'];
308$pdoLand = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
309$pdoLand->exec('UPDATE shots SET deliver_at = 0 WHERE client_id = "f1"');
310$incLand = $store->viewFor($targetId);
311$incHit = null;
312foreach ($incLand['incoming'] as $row) {
313 if (($row['client_id'] ?? '') === 'f1') {
314 $incHit = $row;
315 break;
316 }
317}
318expect($incHit !== null, 'target receives incoming for the shot');
319if ($incHit) {
320 expect(($incHit['land_col'] ?? null) === $found['land_col'], 'incoming.land_col matches the flight');
321}
322$view1 = $store->viewFor('local:test_user_1');
323expect(count($view1['shot_flights']) >= 1, 'shooter also sees shot_flights (client de-dupes)');
324$store->leaveLobby('local:test_user_1');
325$store->leaveLobby('local:test_user_2');
326$store->leaveLobby('local:test_user_3');
327
328
329echo "\nBlocks registry and unlock thresholds\n";
330require_once dirname(__DIR__) . '/lib/Blocks.php';
331$allBlocks = Blocks::all();
332expect(count($allBlocks) >= 48, 'registry has Terra + new icons (got ' . count($allBlocks) . ')');
333for ($i = 0; $i < 5; $i++) {
334 expect(Blocks::threshold($i) === 0, "terra index $i is free");
335}
336expect(Blocks::threshold(5) === 500, 'first unlock is 500 points');
337$prev = 500;
338for ($i = 6; $i < count($allBlocks); $i++) {
339 $t = Blocks::threshold($i);
340 if ($t <= $prev) {
341 expect(false, "threshold at $i should be > $prev, got $t");
342 break;
343 }
344 $prev = $t;
345}
346expect($prev > 500, 'later thresholds grow');
347expect(Blocks::unlocked(0, 0) === true, 'terra unlocked at 0 points');
348expect(Blocks::unlocked(5, 499) === false, 'fehu locked at 499');
349expect(Blocks::unlocked(5, 500) === true, 'fehu unlocked at 500');
350$terraIds = [];
351foreach ($allBlocks as $i => $b) {
352 if ($i >= 5) break;
353 $terraIds[] = $b['id'];
354}
355
356echo "\nLifetime points, anti-cheat, custom planets\n";
357$ptsStore = Store::open($tmp);
358$u = 'local:designer_a';
359$v = 'local:designer_b';
360expect($ptsStore->lifetimePoints($u) === 0, 'new profile starts at 0');
361$t1 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
362expect($t1 === 200, 'first award adds 200');
363$t2 = $ptsStore->awardPoints($u, 200, 'k-one', 'solo');
364expect($t2 === 200, 'same award_key is idempotent');
365$t3 = $ptsStore->awardPoints($u, 50, 'k-two', 'offline');
366expect($t3 === 250, 'second key adds 50');
367
368$ptsStore->testNow = 1_000_000;
369$ses = $ptsStore->playBegin($u, 'solo');
370expect(isset($ses['token']) && strlen($ses['token']) === 32, 'playBegin returns a token');
371$ptsStore->testNow = 1_000_001;
372$fin = $ptsStore->playFinish($u, $ses['token'], 9000);
373expect($fin['awarded'] === 0, 'score with duration under 3s awards 0');
374expect($fin['lifetime_points'] === 250, 'lifetime unchanged after clamped zero');
375$again = $ptsStore->playFinish($u, $ses['token'], 9000);
376expect(!empty($again['already']), 'second finish of same token is a no-op');
377
378$ptsStore->testNow = 2_000_000;
379$ses2 = $ptsStore->playBegin($u, 'offline');
380$ptsStore->testNow = 2_000_010;
381$fin2 = $ptsStore->playFinish($u, $ses2['token'], 9000);
382expect($fin2['awarded'] === 40, 'cap is 4 points/s over 10s (got ' . $fin2['awarded'] . ')');
383expect($fin2['lifetime_points'] === 290, 'capped award is added');
384
385$ptsStore->testNow = 3_000_000;
386$ses3 = $ptsStore->playBegin($u, 'solo');
387$ptsStore->testNow = 3_000_020;
388$fin3 = $ptsStore->playFinish($u, $ses3['token'], 17);
389expect($fin3['awarded'] === 17, 'honest score under the cap is kept');
390
391try {
392 $ptsStore->saveCustomPlanet($u, [
393 'name' => 'Lockworld', 'people' => 'Lockers',
394 'jumpsToClear' => 2, 'fallTime' => 3, 'riseTime' => 1.5,
395 'colors' => array_merge($terraIds, ['rune-fehu']),
396 ]);
397 // 6 items? no that's 6. Use 4 terra + fehu
398 expect(false, 'should not reach (wrong colors count would throw first)');
399} catch (RuntimeException $e) {
400 expect(str_contains($e->getMessage(), 'vijf') || str_contains($e->getMessage(), 'ontgrendeld') || str_contains($e->getMessage(), 'Onbekend'),
401 'invalid colors refused: ' . $e->getMessage());
402}
403
404try {
405 $ptsStore->saveCustomPlanet($u, [
406 'name' => 'Lockworld', 'people' => 'Lockers',
407 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'rune-fehu'],
408 ]);
409 expect(false, 'locked block should throw');
410} catch (RuntimeException $e) {
411 expect(str_contains($e->getMessage(), 'ontgrendeld'), 'locked block refused: ' . $e->getMessage());
412}
413
414try {
415 $ptsStore->saveCustomPlanet($u, [
416 'name' => 'Ghost', 'people' => 'Ghosts',
417 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], 'no-such-block'],
418 ]);
419 expect(false, 'unknown block should throw');
420} catch (RuntimeException $e) {
421 expect(str_contains($e->getMessage(), 'Onbekend'), 'unknown block refused: ' . $e->getMessage());
422}
423
424try {
425 $ptsStore->saveCustomPlanet($u, [
426 'name' => 'Twins', 'people' => 'Twins',
427 'colors' => [$terraIds[0], $terraIds[1], $terraIds[2], $terraIds[3], $terraIds[0]],
428 ]);
429 expect(false, 'duplicate block should throw');
430} catch (RuntimeException $e) {
431 expect(str_contains($e->getMessage(), 'één vak') || str_contains($e->getMessage(), 'vak'),
432 'duplicate block refused: ' . $e->getMessage());
433}
434
435$snap = $ptsStore->saveCustomPlanet($u, [
436 'name' => 'My World', 'people' => 'My People',
437 'jumpsToClear' => 2.5, 'fallTime' => 2, 'riseTime' => 1,
438 'colors' => $terraIds,
439]);
440expect(!empty($snap['id']) && str_starts_with($snap['id'], 'c_'), 'custom id is c_ + hex');
441expect($snap['custom'] === true, 'snapshot is marked custom');
442expect($snap['name'] === 'My World', 'name stored');
443expect(count($snap['colors']) === 5, 'five colors in snapshot');
444expect($snap['colors'][0]['block'] === $terraIds[0], 'color has registry block id');
445expect($snap['owner_id'] === $u, 'owner_id set');
446
447$listed = $ptsStore->listCustomPlanets($u);
448expect(count($listed) === 1, 'owner lists the planet');
449
450echo "Custom planet gravity clamp (t1199)\n";
451$low = $ptsStore->saveCustomPlanet($u, [
452 'name' => 'Lowgrav', 'people' => 'Floaters',
453 'jumpsToClear' => 1, 'fallTime' => 3, 'riseTime' => 1.5,
454 'colors' => $terraIds,
455]);
456expect(almostEqual((float) $low['jumpsToClear'], 2.0), 'saving gravity 1 stores 2');
457$rawPdo = new PDO('sqlite:' . $tmp . '/meteors.sqlite');
458$rawPdo->exec("UPDATE custom_planets SET jumps_to_clear = 1.2 WHERE id = '" . $low['id'] . "'");
459$lowList = array_values(array_filter($ptsStore->listCustomPlanets($u), fn($pl) => $pl['id'] === $low['id']));
460expect(count($lowList) === 1 && almostEqual((float) $lowList[0]['jumpsToClear'], 2.0), 'an old row with 1.2 loads as 2');
461$ptsStore->deleteCustomPlanet($u, $low['id']);
462
463
464echo "Last chosen planet (t1196)\n";
465expect($ptsStore->lastPlanet($u) === null, 'no last planet stored yet');
466expect($ptsStore->profilePayload($u)['last_planet'] === null, 'payload last_planet null');
467expect($ptsStore->setLastPlanet($u, 'terra') === 'terra', 'standard planet saved');
468expect($ptsStore->lastPlanet($u) === 'terra', 'standard planet read back');
469$ptsStore->setLastPlanet($u, $snap['id']);
470expect($ptsStore->profilePayload($u)['last_planet'] === $snap['id'], 'own custom planet saved and in payload');
471foreach (['', 'nope', str_repeat('x', 80)] as $bad) {
472 try { $ptsStore->setLastPlanet($u, $bad); expect(false, 'bad planet accepted: ' . $bad); }
473 catch (RuntimeException $e) { expect(true, 'bad planet refused: ' . substr($bad, 0, 8)); }
474}
475try { $ptsStore->setLastPlanet($v, $snap['id']); expect(false, 'other user may not pick my custom planet'); }
476catch (RuntimeException $e) { expect(true, "someone else's custom planet refused"); }
477expect($ptsStore->lastPlanet($u) === $snap['id'], 'refused writes keep the old value');
478
479expect($ptsStore->listCustomPlanets($v) === [], 'other user has no planets');
480
481try {
482 $ptsStore->setPlanet($u, $snap['id']);
483 expect(false, 'setPlanet without a lobby should throw');
484} catch (RuntimeException $e) {
485 expect(true, 'setPlanet requires a lobby: ' . $e->getMessage());
486}
487
488$lobby = $ptsStore->createLobby($u, 'A', 0.3, $snap['id']);
489$view = $ptsStore->viewFor($u);
490$meP = $view['lobby']['players'][0]['planet'] ?? null;
491expect($meP && $meP['id'] === $snap['id'], 'createLobby stores custom planet');
492expect(!empty($meP['custom']), 'presented planet is custom');
493expect(count($meP['colors']) === 5 && $meP['colors'][0]['image'] !== '', 'presented colors include images');
494expect(isset($meP['miss_chance']) && is_float($meP['miss_chance']), 'server sends miss_chance for custom');
495
496$ptsStore->joinLobby($v, 'B', $lobby['code']);
497$viewB = $ptsStore->viewFor($v);
498$seen = null;
499foreach ($viewB['lobby']['players'] as $plr) {
500 if ($plr['planet']['id'] === $snap['id']) { $seen = $plr['planet']; }
501}
502expect($seen !== null, 'other player sees the custom planet snapshot');
503expect(($seen['colors'][2]['block'] ?? '') === $terraIds[2], 'opponent sees block ids');
504
505try {
506 $ptsStore->setPlanet($v, $snap['id']);
507 expect(false, 'cannot pick someone else\'s custom planet');
508} catch (RuntimeException $e) {
509 expect(str_contains($e->getMessage(), 'Onbekende'), 'foreign custom refused: ' . $e->getMessage());
510}
511
512$ptsStore->leaveLobby($u);
513$ptsStore->leaveLobby($v);
514$ptsStore->deleteCustomPlanet($u, $snap['id']);
515expect($ptsStore->lastPlanet($u) === null, "deleted custom planet → last_planet falls back to null (t1196)");
516expect($ptsStore->listCustomPlanets($u) === [], 'deleted planet is gone');
517
518// Snapshot survives mid-match edits: create, join, start, then edit/delete, opponent still sees original.
519$snap2 = $ptsStore->saveCustomPlanet($u, [
520 'name' => 'Frozen', 'people' => 'Ice',
521 'jumpsToClear' => 3, 'fallTime' => 2, 'riseTime' => 1,
522 'colors' => $terraIds,
523]);
524$lobby2 = $ptsStore->createLobby($u, 'A', 0.3, $snap2['id']);
525$ptsStore->joinLobby($v, 'B', $lobby2['code']);
526$ptsStore->setReady($u, true);
527$ptsStore->setReady($v, true);
528$ptsStore->startGame($u);
529$ptsStore->saveCustomPlanet($u, [
530 'id' => $snap2['id'],
531 'name' => 'Changed', 'people' => 'Ice',
532 'jumpsToClear' => 1, 'fallTime' => 5, 'riseTime' => 3,
533 'colors' => $terraIds,
534]);
535$viewMid = $ptsStore->viewFor($v);
536$midP = null;
537foreach ($viewMid['lobby']['players'] as $plr) {
538 if (($plr['planet']['id'] ?? '') === $snap2['id']) { $midP = $plr['planet']; }
539}
540expect($midP && $midP['name'] === 'Frozen', 'in-match snapshot keeps the original name (got ' . ($midP['name'] ?? '?') . ')');
541expect($midP && almostEqual((float) $midP['jumpsToClear'], 3.0), 'in-match snapshot keeps original gravity');
542$ptsStore->leaveLobby($u);
543$ptsStore->leaveLobby($v);
544
545// Online award is idempotent and server-side.
546$u3 = 'local:online_award_a';
547$v3 = 'local:online_award_b';
548$lob = $ptsStore->createLobby($u3, 'A', 0.0, 'terra');
549$ptsStore->joinLobby($v3, 'B', $lob['code']);
550$ptsStore->setReady($u3, true);
551$ptsStore->setReady($v3, true);
552$ptsStore->startGame($u3);
553$ptsStore->viewFor($u3, null, 80, false, []);
554$ptsStore->viewFor($u3, null, 80, true, []);
555expect($ptsStore->lifetimePoints($u3) === 80, 'online elimination awards the score');
556$ptsStore->viewFor($u3, null, 999, true, []);
557expect($ptsStore->lifetimePoints($u3) === 80, 'online award_key is idempotent');
558
559// t1278: a rematch in the same (reset) lobby must award again, otherwise
560// the client's reward tally sees before === after and skips the count.
561echo "Online rematch awards (t1278)\n";
562$uR = 'local:rematch_a';
563$vR = 'local:rematch_b';
564$ptsStore->touchProfile($uR, 'Ra', null);
565$ptsStore->touchProfile($vR, 'Rb', null);
566$lobR = $ptsStore->createLobby($uR, 'Ra', 0.0, 'terra');
567$ptsStore->joinLobby($vR, 'Rb', $lobR['code']);
568$ptsStore->setReady($uR, true);
569$ptsStore->setReady($vR, true);
570$start1 = $ptsStore->startGame($uR);
571expect(!empty($start1['started']), 'first match has a started timestamp');
572$ptsStore->viewFor($uR, null, 90, false, []);
573$ptsStore->viewFor($vR, null, 40, true, []);
574expect($ptsStore->lifetimePoints($uR) === 90, 'match 1 winner awarded 90 (got ' . $ptsStore->lifetimePoints($uR) . ')');
575expect($ptsStore->lifetimePoints($vR) === 40, 'match 1 loser awarded 40');
576$lobAfter1 = $ptsStore->lobbyForUser($uR);
577expect(($lobAfter1['status'] ?? '') === 'finished', 'lobby finished after last player is out');
578expect($ptsStore->onlineAwardedFor($uR, $lobAfter1) === 90, 'winner online_awarded is 90');
579expect($ptsStore->onlineAwardedFor($vR, $lobAfter1) === 40, 'loser online_awarded is 40');
580$key1 = $ptsStore->onlineAwardKey($lobAfter1, $uR);
581expect(strpos($key1, ':' . (int) $start1['started'] . ':') !== false, 'award key includes match start');
582
583// Same match is idempotent under the new key too.
584$ptsStore->viewFor($uR, null, 90, false, []);
585expect($ptsStore->lifetimePoints($uR) === 90, 'same match stays idempotent');
586
587$ptsStore->testNow = ((int) ($lobAfter1['finished'] ?? time())) + METEORS_PODIUM_SECONDS + 1;
588$ptsStore->viewFor($uR);
589$lobWait = $ptsStore->lobbyForUser($uR);
590expect(($lobWait['status'] ?? '') === 'waiting', 'lobby resets after the podium');
591expect($ptsStore->onlineAwardedFor($uR, $lobWait) === null, 'waiting lobby has no current award');
592
593$ptsStore->setReady($uR, true);
594$ptsStore->setReady($vR, true);
595$start2 = $ptsStore->startGame($uR);
596expect((int) $start2['started'] !== (int) $start1['started'], 'rematch gets a new started time');
597$beforeRematchU = $ptsStore->lifetimePoints($uR);
598$beforeRematchV = $ptsStore->lifetimePoints($vR);
599$ptsStore->viewFor($uR, null, 70, false, []);
600$ptsStore->viewFor($vR, null, 25, true, []);
601expect($ptsStore->lifetimePoints($uR) === $beforeRematchU + 70, 'rematch winner is awarded again (got ' . $ptsStore->lifetimePoints($uR) . ')');
602expect($ptsStore->lifetimePoints($vR) === $beforeRematchV + 25, 'rematch loser is awarded again');
603$lobAfter2 = $ptsStore->lobbyForUser($uR);
604expect($ptsStore->onlineAwardedFor($uR, $lobAfter2) === 70, 'rematch online_awarded is the new score, not the first');
605
606// Mid-podium old-key compatibility: a first-match award stored under the
607// pre-t1278 key must not be granted a second time after deploy.
608$uOld = 'local:oldkey_a';
609$vOld = 'local:oldkey_b';
610$ptsStore->touchProfile($uOld, 'Oa', null);
611$ptsStore->touchProfile($vOld, 'Ob', null);
612$lobOld = $ptsStore->createLobby($uOld, 'Oa', 0.0, 'terra');
613$ptsStore->joinLobby($vOld, 'Ob', $lobOld['code']);
614$ptsStore->setReady($uOld, true);
615$ptsStore->setReady($vOld, true);
616$stOld = $ptsStore->startGame($uOld);
617$ptsStore->viewFor($uOld, null, 15, false, []);
618// Pretend the current match was already awarded with the old lobby-only key
619// (as a live lobby would be, mid-podium, right after deploy).
620$ptsStore->awardPoints($uOld, 15, 'online:' . $stOld['id'] . ':' . $uOld, 'online');
621expect($ptsStore->lifetimePoints($uOld) === 15, 'seeded old-key award');
622$ptsStore->viewFor($vOld, null, 5, true, []);
623expect($ptsStore->lifetimePoints($uOld) === 15, 'old key for this same match is not awarded twice (got ' . $ptsStore->lifetimePoints($uOld) . ')');
624expect($ptsStore->lifetimePoints($vOld) === 5, 'opponent still gets the new-key award');
625$ptsStore->testNow = null;
626
627$ptsStore->setLocale($u, 'nl');
628expect($ptsStore->locale($u) === 'nl', 'setLocale stores nl');
629try {
630 $ptsStore->setLocale($u, 'xx');
631 expect(false, 'unknown locale should throw');
632} catch (RuntimeException $e) {
633 expect(true, 'unknown locale refused');
634}
635
636
637echo "Leaderboard (t1247)\n";
638expect(safeAvatarUrl(null) === null, 'null avatar rejected');
639expect(safeAvatarUrl('javascript:alert(1)') === null, 'javascript avatar rejected');
640expect(safeAvatarUrl('https://auth.timfalken.com/avatar/1?v=2') === 'https://auth.timfalken.com/avatar/1?v=2', 'https avatar kept');
641expect(safeAvatarUrl('/avatar/1') === '/avatar/1', 'same-origin path kept');
642$parsed = parseAuthFriends([
643 'friends' => [
644 ['id' => 2, 'username' => 'ada', 'avatar_url' => 'https://auth.timfalken.com/avatar/2?v=3'],
645 ['id' => 'nope', 'username' => 'bad'],
646 ['id' => 0, 'username' => 'zero'],
647 'not-an-array',
648 ['id' => 3, 'username' => 'bob'],
649 ],
650]);
651expect(count($parsed) === 2, 'parseAuthFriends keeps two valid friends');
652expect($parsed[0]['id'] === 'auth:2' && $parsed[0]['name'] === 'ada', 'first friend id+name');
653expect($parsed[0]['avatar'] === 'https://auth.timfalken.com/avatar/2?v=3', 'first friend avatar');
654expect($parsed[1]['id'] === 'auth:3' && $parsed[1]['name'] === 'bob' && $parsed[1]['avatar'] === null, 'second friend no avatar');
655expect(parseAuthFriends(['friends' => []]) === [], 'empty friends list');
656expect(parseAuthFriends(null) === [], 'invalid friends payload');
657[$aid, $aname, $aav] = authIdentity(['id' => 7, 'username' => 'tim', 'avatar_url' => 'https://auth.timfalken.com/avatar/7?v=1']);
658expect($aid === 'auth:7' && $aname === 'tim' && $aav === 'https://auth.timfalken.com/avatar/7?v=1', 'authIdentity includes avatar_url');
659expect(localTestFriends('local:test_user_1')[0]['id'] === 'local:test_user_2', 'local test_user_1 is friends with test_user_2');
660expect(localTestFriends('local:test_user_2')[0]['id'] === 'local:test_user_1', 'and the other way around');
661expect(localTestFriends('auth:7') === [], 'real accounts have no local test friends');
662
663$lbDir = $tmp . '/leaderboard';
664mkdir($lbDir, 0775, true);
665$lb = Store::open($lbDir);
666for ($i = 1; $i <= 12; $i++) {
667 $uid = 'auth:' . (1000 + $i);
668 $lb->touchProfile($uid, 'Player ' . sprintf('%02d', $i), 'https://auth.timfalken.com/avatar/' . (1000 + $i));
669 $lb->awardPoints($uid, $i * 10, 'lb-' . $i, 'solo');
670}
671// nameless profile still appears, fallback name from the id
672$lb->awardPoints('auth:1099', 5, 'lb-nameless', 'solo');
673$top = $lb->topPlayers(10, 'auth:1012');
674expect(count($top) === 10, 'global list is capped at 10 (got ' . count($top) . ')');
675expect($top[0]['id'] === 'auth:1012' && $top[0]['points'] === 120 && $top[0]['rank'] === 1, 'highest score is first');
676expect($top[0]['you'] === true, 'current player is flagged when in the top 10');
677expect($top[0]['name'] === 'Player 12', 'name is stored on the profile');
678expect($top[0]['avatar'] === 'https://auth.timfalken.com/avatar/1012', 'avatar is stored on the profile');
679expect($top[9]['id'] === 'auth:1003' && $top[9]['points'] === 30 && $top[9]['you'] === false, '10th is Player 03 with 30 points');
680$ids = array_column($top, 'id');
681expect(!in_array('auth:1002', $ids, true) && !in_array('auth:1099', $ids, true), '11th and nameless (5 pts) stay off the top 10');
682$below = $lb->topPlayers(10, 'auth:1001');
683expect($below[0]['you'] === false && !in_array(true, array_column($below, 'you'), true), 'viewer outside the top 10 is not flagged');
684
685$lb->touchProfile('auth:4000', 'Zero Points', null);
686$withZero = $lb->topPlayers(50);
687expect(!in_array('auth:4000', array_column($withZero, 'id'), true), 'global tab hides players with 0 points');
688expect(array_reduce($withZero, fn($ok, $r) => $ok && $r['points'] > 0, true), 'every global row has points');
689
690// ties: same points, then name, then id
691$lb->touchProfile('auth:2001', 'Cara', null);
692$lb->touchProfile('auth:2002', 'Ada', null);
693$lb->awardPoints('auth:2001', 7, 'tie-c', 'solo');
694$lb->awardPoints('auth:2002', 7, 'tie-a', 'solo');
695$tie = $lb->topPlayers(50);
696$cara = null; $ada = null;
697foreach ($tie as $row) {
698 if ($row['id'] === 'auth:2001') { $cara = $row; }
699 if ($row['id'] === 'auth:2002') { $ada = $row; }
700}
701expect($ada && $cara && $ada['points'] === 7 && $cara['points'] === 7, 'tied players both listed');
702expect($ada['rank'] < $cara['rank'], 'tie broken by name (Ada before Cara)');
703
704$friends = [
705 ['id' => 'auth:1012', 'name' => 'From API', 'avatar' => 'https://auth.timfalken.com/avatar/from-api'],
706 ['id' => 'auth:1005', 'name' => 'Player 05', 'avatar' => null],
707 ['id' => 'auth:3001', 'name' => 'Never Played', 'avatar' => 'https://auth.timfalken.com/avatar/3001'],
708];
709$fl = $lb->friendsLeaderboard($friends, 10, 'auth:1099');
710$flIds = array_column($fl, 'id');
711expect(!in_array('auth:3001', $flIds, true), 'friends tab hides a friend with 0 points (never played)');
712expect(array_reduce($fl, fn($ok, $r) => $ok && $r['points'] > 0, true), 'every friends row has points');
713expect($fl[0]['id'] === 'auth:1012' && $fl[0]['points'] === 120 && $fl[0]['name'] === 'Player 12', 'friend with a profile uses stored name and points');
714expect($fl[1]['id'] === 'auth:1005' && $fl[1]['points'] === 50, 'second friend by points');
715expect($fl[2]['id'] === 'auth:1099' && $fl[2]['points'] === 5 && $fl[2]['you'] === true, 'viewer is ranked among friends when they have points');
716expect(count($fl) === 3, 'friends tab is friends-with-points plus you (got ' . count($fl) . ')');
717
718$onlyYou = $lb->friendsLeaderboard([], 10, 'auth:1012');
719expect(count($onlyYou) === 1 && $onlyYou[0]['id'] === 'auth:1012' && $onlyYou[0]['you'] === true, 'empty friend list still shows you if you have points');
720$zeroYou = $lb->friendsLeaderboard($friends, 10, 'auth:4000');
721expect(!in_array('auth:4000', array_column($zeroYou, 'id'), true), 'viewer with 0 points is omitted like anyone else');
722expect($lb->friendsLeaderboard([], 10, 'auth:4000') === [], 'no friends and 0 points → empty friends tab');
723
724echo "Leaderboard names from auth (t1249)\n";
725expect(isPlaceholderName('auth:3', '3') === true, 'name equal to the auth id is a placeholder');
726expect(isPlaceholderName('auth:3', 'auth:3') === true, 'raw user id is a placeholder');
727expect(isPlaceholderName('auth:3', '') === true, 'empty name is a placeholder');
728expect(isPlaceholderName('auth:3', 'Ada') === false, 'a real username is not a placeholder');
729expect(isPlaceholderName('local:test_user_1', 'test_user_1') === false, 'local test names are real');
730
731// Existing profile with no stored name, like the live fallback "1" / "3".
732$lb->awardPoints('auth:3', 40, 'lb-t1249-ada', 'solo');
733$before = $lb->topPlayers(10, null);
734$adaRow = null;
735foreach ($before as $row) {
736 if ($row['id'] === 'auth:3') { $adaRow = $row; }
737}
738expect($adaRow && $adaRow['name'] === '3', 'without auth data the display name falls back to the id (' . ($adaRow['name'] ?? '?') . ')');
739
740$known = [
741 'auth:3' => ['id' => 'auth:3', 'name' => 'Ada', 'avatar' => 'https://auth.timfalken.com/avatar/3?v=2'],
742 'auth:1012' => ['id' => 'auth:1012', 'name' => 'From Friends', 'avatar' => null],
743];
744$filled = $lb->applyIdentities($before, $known);
745$adaFilled = null;
746foreach ($filled as $row) {
747 if ($row['id'] === 'auth:3') { $adaFilled = $row; }
748}
749expect($adaFilled && $adaFilled['name'] === 'Ada', 'applyIdentities replaces the placeholder with the friends-list name');
750expect($adaFilled && $adaFilled['avatar'] === 'https://auth.timfalken.com/avatar/3?v=2', 'applyIdentities fills the avatar from auth');
751
752$n = $lb->rememberIdentities(array_values($known));
753expect($n >= 1, 'rememberIdentities backfills existing profiles (changed ' . $n . ')');
754$after = $lb->topPlayers(50, null);
755$adaStored = null;
756foreach ($after as $row) {
757 if ($row['id'] === 'auth:3') { $adaStored = $row; }
758}
759expect($adaStored && $adaStored['name'] === 'Ada', 'later reads (including guests) use the backfilled name');
760expect($adaStored && $adaStored['avatar'] === 'https://auth.timfalken.com/avatar/3?v=2', 'backfilled avatar is stored');
761
762// Does not create a profile for a friend who never played.
763$beforeCount = $lb->topPlayers(50);
764$lb->rememberIdentities([['id' => 'auth:9999', 'name' => 'Ghost', 'avatar' => null]]);
765$afterCount = $lb->topPlayers(50);
766expect(count($afterCount) === count($beforeCount), 'rememberIdentities does not invent profiles for friends who never played');
767$ghost = false;
768foreach ($afterCount as $row) {
769 if ($row['id'] === 'auth:9999') { $ghost = true; }
770}
771expect($ghost === false, 'the never-played friend is not on the global board');
772
773// A leftover placeholder in the store loses to the friends-list name.
774$pdoLb = new PDO('sqlite:' . $lbDir . '/meteors.sqlite');
775$pdoLb->exec("UPDATE profiles SET name = '3' WHERE user_id = 'auth:3'");
776$fl = $lb->friendsLeaderboard([
777 ['id' => 'auth:3', 'name' => 'Ada', 'avatar' => 'https://auth.timfalken.com/avatar/3?v=9'],
778], 10, 'auth:1012');
779$adaRow = null;
780foreach ($fl as $row) {
781 if ($row['id'] === 'auth:3') { $adaRow = $row; }
782}
783expect($adaRow && $adaRow['name'] === 'Ada', 'friends tab prefers the auth name over a stored placeholder');
784expect($fl[0]['id'] === 'auth:1012' && $fl[0]['you'] === true, 'viewer with more points ranks above that friend');
785
786// Friends cache: fresh hit, stale miss, stale allowed on failure path.
787$lb->writeFriendsCache('auth:7', [
788 ['id' => 'auth:3', 'name' => 'Ada', 'avatar' => null],
789], 1000);
790$hit = $lb->readFriendsCache('auth:7', 1000 + 30);
791expect($hit && $hit[0]['name'] === 'Ada', 'fresh friends cache is reused');
792$miss = $lb->readFriendsCache('auth:7', 1000 + Store::FRIENDS_CACHE_TTL + 1);
793expect($miss === null, 'stale friends cache is not reused by default');
794$stale = $lb->readFriendsCache('auth:7', 1000 + Store::FRIENDS_CACHE_TTL + 1, true);
795expect($stale && $stale[0]['id'] === 'auth:3', 'stale cache can be used when auth is unavailable');
796
797$apiSrc = (string) file_get_contents(dirname(__DIR__) . '/api.php');
798expect(strpos($apiSrc, "action === 'leaderboard'") !== false, 'api.php has a leaderboard action');
799expect(strpos($apiSrc, 'leaderboardKnownIdentities(') !== false, 'leaderboard resolves names via cached auth friends');
800$bootSrc = (string) file_get_contents(dirname(__DIR__) . '/lib/bootstrap.php');
801expect(strpos($bootSrc, "authRequest('/api/friends'") !== false, 'friends are fetched from GET /api/friends on auth.timfalken.com');
802expect(strpos($bootSrc, "/api/profiles") !== false, 'leaderboard names also come from public GET /api/profiles');
803
804echo "Auth locale claim (t1250)\n";
805expect(normalizeAuthLocale('zh-Hans') === 'zh', 'zh-Hans maps to zh');
806expect(normalizeAuthLocale('zh-hans') === 'zh', 'zh-hans maps to zh');
807expect(normalizeAuthLocale('zh_CN') === 'zh', 'zh_CN maps to zh');
808expect(normalizeAuthLocale('nl') === 'nl', 'nl stays nl');
809expect(normalizeAuthLocale('en-US') === 'en', 'en-US falls back to en');
810expect(normalizeAuthLocale('xx') === null, 'unknown claim is null');
811expect(normalizeAuthLocale('') === null, 'empty claim is null');
812expect(authLocaleFromPayload(['user' => ['locale' => 'zh-Hans']]) === 'zh', '/api/me user.locale is read');
813expect(authLocaleFromPayload(['locale' => 'de']) === 'de', 'top-level locale is read');
814expect(authNumericId('auth:15') === 15, 'auth:15 → 15');
815expect(authNumericId('local:test_user_1') === null, 'local testers are not auth ids');
816
817$locUser = 'local:test_user_1';
818$locStore = Store::open($tmp . '/locale-t1250');
819expect($locStore->locale($locUser) === null, 'new profile has no stored locale');
820expect($locStore->localeExplicit($locUser) === false, 'new profile is not an explicit in-game choice');
821expect($locStore->setLocale($locUser, 'zh-Hans') === 'zh', 'setLocale accepts zh-Hans');
822expect($locStore->locale($locUser) === 'zh' && $locStore->localeExplicit($locUser) === true, 'in-game set_locale marks the choice explicit');
823$payload = $locStore->profilePayload($locUser);
824expect(!empty($payload['locale_explicit']) && $payload['locale'] === 'zh', 'profilePayload exposes locale_explicit');
825
826echo "Public auth profiles (t1253)\n";
827$parsed = parseAuthProfiles([
828 'profiles' => [
829 ['id' => 2, 'username' => 'daniqueaben', 'avatar_url' => null],
830 ['id' => 3, 'username' => 'lucia'],
831 ['id' => 15, 'username' => 'emma', 'avatar_url' => 'https://auth.timfalken.com/avatar/15?v=1'],
832 ['id' => 'nope', 'username' => 'bad'],
833 ['id' => 1, 'username' => ''],
834 'x',
835 ],
836]);
837expect(count($parsed) === 3, 'parseAuthProfiles keeps valid rows (got ' . count($parsed) . ')');
838expect($parsed[0]['id'] === 'auth:2' && $parsed[0]['name'] === 'daniqueaben', 'id 2 → auth:2 / daniqueaben');
839expect($parsed[2]['avatar'] === 'https://auth.timfalken.com/avatar/15?v=1', 'avatar_url is kept');
840
841$pr = Store::open($tmp . '/profiles-t1253');
842$pr->testNow = 5000;
843$pr->awardPoints('auth:2', 10, 't1253-a', 'solo');
844$pr->awardPoints('auth:3', 20, 't1253-b', 'solo');
845$pr->awardPoints('auth:15', 1, 't1253-c', 'solo');
846$calls = [];
847$GLOBALS['METEORS_AUTH_GET'] = function (string $path, $token = null) use (&$calls) {
848 $calls[] = $path;
849 if (!str_starts_with($path, '/api/profiles?ids=')) {
850 throw new RuntimeException('unexpected path ' . $path);
851 }
852 $q = substr($path, strlen('/api/profiles?ids='));
853 $ids = array_map('intval', explode(',', $q));
854 $names = [2 => 'daniqueaben', 3 => 'lucia', 15 => 'emma'];
855 $rows = [];
856 foreach ($ids as $id) {
857 if (isset($names[$id])) {
858 $rows[] = ['id' => $id, 'username' => $names[$id], 'avatar_url' => null];
859 }
860 }
861 return ['profiles' => $rows];
862};
863$got = fetchAuthProfiles($pr, ['auth:2', 'auth:3', 'auth:15', 'local:test_user_1']);
864expect(isset($got['auth:2'], $got['auth:3'], $got['auth:15']), 'fetchAuthProfiles returns all auth ids');
865expect($got['auth:3']['name'] === 'lucia' && $got['auth:2']['name'] === 'daniqueaben' && $got['auth:15']['name'] === 'emma', 'usernames from /api/profiles');
866expect(count($calls) === 1, 'one batched /api/profiles request (got ' . count($calls) . ')');
867expect(!str_contains($calls[0], 'local:'), 'local testers are not sent to auth');
868$calls = [];
869$again = fetchAuthProfiles($pr, ['auth:3']);
870expect($again['auth:3']['name'] === 'lucia' && $calls === [], 'fresh profiles cache is reused');
871$pr->testNow = 5000 + Store::PROFILES_CACHE_TTL + 1;
872$calls = [];
873fetchAuthProfiles($pr, ['auth:3']);
874expect(count($calls) === 1, 'stale profiles cache is refetched');
875
876// Auth down: stale cache still fills names; no cache keeps fallbacks.
877$pr->testNow = 5000 + Store::PROFILES_CACHE_TTL * 3;
878$GLOBALS['METEORS_AUTH_GET'] = function () {
879 throw new RuntimeException('auth down');
880};
881$stale = fetchAuthProfiles($pr, ['auth:3']);
882expect($stale['auth:3']['name'] === 'lucia', 'stale profiles cache is used when auth is unreachable');
883
884$emptyStore = Store::open($tmp . '/profiles-t1253-empty');
885$emptyStore->testNow = 1;
886$down = fetchAuthProfiles($emptyStore, ['auth:9']);
887expect($down === [], 'no cache and auth down → empty (caller keeps fallbacks)');
888
889$board = $pr->topPlayers(10, null);
890$filled = $pr->applyIdentities($board, $got);
891$names = [];
892foreach ($filled as $row) {
893 $names[$row['id']] = $row['name'];
894}
895expect(($names['auth:3'] ?? '') === 'lucia', 'applyIdentities shows lucia instead of 3');
896$pr->rememberIdentities(array_values($got));
897$later = $pr->topPlayers(10, null);
898$storedNames = [];
899foreach ($later as $row) {
900 $storedNames[$row['id']] = $row['name'];
901}
902expect(($storedNames['auth:2'] ?? '') === 'daniqueaben', 'backfill stores daniqueaben for later guests');
903expect(($storedNames['auth:15'] ?? '') === 'emma', 'backfill stores emma');
904
905$many = [];
906for ($i = 1; $i <= 51; $i++) {
907 $many[] = 'auth:' . $i;
908}
909$chunks = [];
910$GLOBALS['METEORS_AUTH_GET'] = function (string $path) use (&$chunks) {
911 $chunks[] = $path;
912 return ['profiles' => []];
913};
914$fresh = Store::open($tmp . '/profiles-t1253-chunk');
915fetchAuthProfiles($fresh, $many);
916expect(count($chunks) === 2, 'more than 50 ids are split into two /api/profiles calls (got ' . count($chunks) . ')');
917unset($GLOBALS['METEORS_AUTH_GET']);
918
919$srcApi = (string) file_get_contents(dirname(__DIR__) . '/api.php');
920expect(strpos($srcApi, 'auth_locale') !== false, 'me/poll expose auth_locale');
921expect(strpos($srcApi, 'locale_explicit') !== false, 'me/poll expose locale_explicit');
922$cbSrc = (string) file_get_contents(dirname(__DIR__) . '/callback.php');
923expect(strpos($cbSrc, 'storeAuthLocale') !== false, 'callback stores the OIDC locale claim');
924
925echo "\nConfig helpers\n";
926
927
928$cfg = config();
929expect(isset($cfg['client_id'], $cfg['client_secret']), 'config() creates a file');
930expect(is_file($tmp . '/config.php'), 'config.php written to the data dir');
931expect($cfg['client_secret'] === '', 'secret starts empty (Tim must fill it in)');
932expect(authConfigured() === false, 'auth is unconfigured without a secret');
933putenv('METEORS_CLIENT_SECRET=test-secret-value');
934// config file empty secret falls back to env
935$cfg2 = config();
936expect($cfg2['client_secret'] === 'test-secret-value', 'empty file field falls back to env');
937putenv('METEORS_CLIENT_SECRET');
938
939echo "\n$passed passed, $failed failed\n";
940
941// cleanup
942$files = new RecursiveIteratorIterator(
943 new RecursiveDirectoryIterator($tmp, FilesystemIterator::SKIP_DOTS),
944 RecursiveIteratorIterator::CHILD_FIRST
945);
946foreach ($files as $f) {
947 $f->isDir() ? @rmdir($f->getPathname()) : @unlink($f->getPathname());
948}
949@rmdir($tmp);
950
951exit($failed === 0 ? 0 : 1);