BlueGit

projects-timfalken-com microchess

Files

microchess / web / tests / push.php

push.php

feat: scaffold Synhex hex tactics on the Microchess lobby shell
timfa project_86226080_bot_b6e0858ac0a12dc6d49a8d25b3b0be9b · pushed by timfa · 2 months ago
24f20754 History
push.php 5.3 KiB Download Raw
1<?php
2// Isolated database and real Web Push encryption, with an in-memory HTTP transport.
3declare(strict_types=1);
4$root=sys_get_temp_dir().'/synhex-push-'.bin2hex(random_bytes(6));
5mkdir($root.'/data',0700,true);mkdir($root.'/lib');mkdir($root.'/assets/avatars',0700,true);
6foreach (['bootstrap.php','HexGrid.php','SynhexSim.php','SynhexMatch.php','Push.php','PieceColors.php'] as $file) copy(__DIR__.'/../lib/'.$file,$root.'/lib/'.$file);
7copy(__DIR__.'/../lib/game-config.php',$root.'/lib/game-config.php');
8symlink(realpath(__DIR__.'/../lib/push'),$root.'/lib/push');
9copy(__DIR__.'/../assets/avatars/catalog.json',$root.'/assets/avatars/catalog.json');
10$_SERVER+=['HTTP_HOST'=>'localhost','REMOTE_ADDR'=>'127.0.0.1','SCRIPT_NAME'=>'/synhex/api.php'];
11require $root.'/lib/bootstrap.php';
12use Minishlink\WebPush\WebPush;
13use Minishlink\WebPush\VAPID;
14use GuzzleHttp\Handler\MockHandler;
15use GuzzleHttp\HandlerStack;
16use GuzzleHttp\Middleware;
17use GuzzleHttp\Psr7\Response;
18$checks=0;
19function check(bool $value,string $label): void {global $checks;$checks++;if (!$value) throw new RuntimeException($label);}
20try {
21 $keys=pushKeys();
22 check($keys===json_decode(file_get_contents($root.'/data/push-keys.json'),true),'Persistent VAPID keys');
23 check(strlen(base64_decode(strtr($keys['publicKey'],'-_','+/')))===65,'P-256 VAPID public key');
24 $u='local:test_user_1';$v='local:test_user_2';loginUser($v,'test_user_2');
25 $device=VAPID::createVapidKeys();
26 $sub=['endpoint'=>'https://fcm.googleapis.com/fcm/send/test-device','keys'=>['p256dh'=>$device['publicKey'],'auth'=>rtrim(strtr(base64_encode(random_bytes(16)),'+/','-_'),'=')]];
27 pushSubscribe($u,['subscription'=>$sub]);pushSubscribe($u,['subscription'=>$sub]);
28 check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===1,'Subscriptions are idempotent');
29 pushUnsubscribe($v,$sub['endpoint']);
30 check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===1,'Other account cannot unsubscribe device');
31 foreach (['http://fcm.googleapis.com/test','https://127.0.0.1/test','https://fcm.googleapis.com.evil.example/test','https://fcm.googleapis.com:443/test','https://user@fcm.googleapis.com/test'] as $bad) {
32 try {pushEndpoint($bad);check(false,'Reject unsafe endpoint');} catch (DomainException) {$checks++;}
33 }
34 $bad=$sub;$bad['keys']['p256dh']='BA'.str_repeat('A',85);
35 try {pushSubscribe($u,['subscription'=>$bad]);check(false,'Reject invalid curve point');} catch (DomainException) {$checks++;}
36 $id=startGame($u,$v);query('UPDATE games SET white=? WHERE id=?',[$v,$id]);
37 $GLOBALS['push_events']=[];pushGame($id);
38 $events=$GLOBALS['push_events'];
39 $users=array_column(array_values($events),'user');
40 check(count($events)===2 && in_array($u,$users,true) && in_array($v,$users,true),'Notify both players when planning starts');
41 pushSubscribe($v,['subscription'=>$sub]);
42 check(query('SELECT user_id FROM push_subscriptions')->fetchColumn()===$v,'Subscription follows account on same device');
43 $history=[];$mock=new MockHandler([new Response(201),new Response(410)]);
44 $handler=HandlerStack::create($mock);$handler->push(Middleware::history($history));
45 $sender=new WebPush(['VAPID'=>['subject'=>'https://example.com','publicKey'=>$keys['publicKey'],'privateKey'=>$keys['privateKey']]],[],5,['handler'=>$handler]);
46 $one=[array_values($events)[0]];
47 pushDeliver($one,$sender);
48 check(count($history)===1,'Sends through HTTP transport');
49 $request=$history[0]['request'];
50 check($request->getHeaderLine('Content-Encoding')==='aes128gcm','Encrypted notification payload');
51 check(str_starts_with($request->getHeaderLine('Authorization'),'vapid '),'VAPID authenticated notification');
52 check($request->getHeaderLine('Topic')==='game-'.$id,'Coalesce each game');
53 check(!str_contains((string)$request->getBody(),'Your turn'),'No plaintext payload');
54 query('UPDATE games SET version=version+1 WHERE id=?',[$id]);
55 pushDeliver($one,$sender);check(count($history)===1,'Skip superseded event');
56 $GLOBALS['push_events']=[];pushGame($id);pushDeliver([array_values($GLOBALS['push_events'])[0]],$sender);
57 check((int)query('SELECT COUNT(*) FROM push_subscriptions')->fetchColumn()===0,'Remove expired subscriptions');
58 $GLOBALS['push_events']=[];query("UPDATE games SET status='ended' WHERE id=?",[$id]);pushGame($id);
59 check(!$GLOBALS['push_events'],'No turn notification after game ends');
60 // Rendering a production login page preserves both invitation and notification targets.
61 $_GET=['game'=>'42','invite'=>str_repeat('a',48)];unset($_SESSION['user']);
62 $index=str_replace("require __DIR__.'/lib/bootstrap.php';",'',file_get_contents(__DIR__.'/../index.php'));
63 file_put_contents($root.'/index.php',$index);
64 ob_start();require $root.'/index.php';$html=ob_get_clean();
65 check(str_contains($html,'game=42'),'Sign-in link preserves notification game');
66 echo "Push: $checks checks passed.\n";
67} finally {
68 session_write_close();
69 // Only remove this test's randomly named fixture; do not traverse vendor symlink.
70 $files=new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root,FilesystemIterator::SKIP_DOTS),RecursiveIteratorIterator::CHILD_FIRST);
71 foreach ($files as $file) {if ($file->isDir()&&!$file->isLink()) rmdir($file->getPathname());else unlink($file->getPathname());}
72 rmdir($root);
73}