| 1 | <?php |
| 2 | declare(strict_types=1); |
| 3 | |
| 4 | // Dependencies are shipped with the app: production needs no Composer or worker. |
| 5 | function pushKeys(): array { |
| 6 | static $keys; |
| 7 | if ($keys!==null) return $keys; |
| 8 | require_once __DIR__.'/push/vendor/autoload.php'; |
| 9 | $path=dirname(__DIR__).'/data/push-keys.json'; |
| 10 | $lock=fopen(dirname(__DIR__).'/data/push-keys.lock','c'); |
| 11 | if (!$lock) throw new RuntimeException('Unable to initialize notifications.'); |
| 12 | try { |
| 13 | if (!flock($lock,LOCK_EX)) throw new RuntimeException('Unable to lock notification keys.'); |
| 14 | if (!file_exists($path)) { |
| 15 | $generated=Minishlink\WebPush\VAPID::createVapidKeys(); |
| 16 | $json=json_encode($generated,JSON_THROW_ON_ERROR); |
| 17 | if (file_put_contents($path,$json)!==strlen($json)) throw new RuntimeException('Unable to save notification keys.'); |
| 18 | chmod($path,0600); |
| 19 | } |
| 20 | return $keys=json_decode(file_get_contents($path),true,8,JSON_THROW_ON_ERROR); |
| 21 | } finally {flock($lock,LOCK_UN);fclose($lock);} |
| 22 | } |
| 23 | function pushEndpoint(mixed $endpoint): string { |
| 24 | if (!is_string($endpoint) || strlen($endpoint)>2048) throw new DomainException('Invalid push subscription.'); |
| 25 | $url=parse_url($endpoint); |
| 26 | $host=strtolower($url['host']??''); |
| 27 | // Only browser-operated push services. Never let a subscription turn this server into an HTTP proxy. |
| 28 | $allowed=in_array($host,['fcm.googleapis.com','updates.push.services.mozilla.com','web.push.apple.com'],true) |
| 29 | || str_ends_with($host,'.push.apple.com') || str_ends_with($host,'.notify.windows.com'); |
| 30 | if (!$allowed || ($url['scheme']??'')!=='https' || isset($url['user']) || isset($url['port']) || isset($url['fragment']) || empty($url['path'])) throw new DomainException('Unsupported push service.'); |
| 31 | return $endpoint; |
| 32 | } |
| 33 | function pushSubscribe(string $user,array $in): void { |
| 34 | $s=$in['subscription']??null; |
| 35 | if (!is_array($s)) throw new DomainException('Invalid push subscription.'); |
| 36 | $endpoint=pushEndpoint($s['endpoint']??null); |
| 37 | foreach (['p256dh'=>65,'auth'=>16] as $key=>$length) { |
| 38 | $value=$s['keys'][$key]??null; |
| 39 | if (!is_string($value) || strlen($value)>100 || !preg_match('/^[A-Za-z0-9_-]+={0,2}$/D',$value)) throw new DomainException('Invalid push keys.'); |
| 40 | $decoded=base64_decode(strtr($value,'-_','+/'),true); |
| 41 | if ($decoded===false || strlen($decoded)!==$length || ($key==='p256dh' && $decoded[0]!=="\x04")) throw new DomainException('Invalid push keys.'); |
| 42 | } |
| 43 | $point=base64_decode(strtr($s['keys']['p256dh'],'-_','+/'),true); |
| 44 | $pem="-----BEGIN PUBLIC KEY-----\n".chunk_split(base64_encode(hex2bin('3059301306072a8648ce3d020106082a8648ce3d030107034200').$point),64,"\n")."-----END PUBLIC KEY-----\n"; |
| 45 | if (!@openssl_pkey_get_public($pem)) throw new DomainException('Invalid push public key.'); |
| 46 | pushKeys(); |
| 47 | if (!query('SELECT 1 FROM push_subscriptions WHERE endpoint=? AND user_id=?',[$endpoint,$user])->fetchColumn() |
| 48 | && (int)query('SELECT COUNT(*) FROM push_subscriptions WHERE user_id=?',[$user])->fetchColumn()>=10) throw new DomainException('Notification device limit reached. Disable notifications on another device first.'); |
| 49 | query('INSERT INTO push_subscriptions(endpoint,user_id,p256dh,auth,updated) VALUES(?,?,?,?,?) ON CONFLICT(endpoint) DO UPDATE SET user_id=excluded.user_id,p256dh=excluded.p256dh,auth=excluded.auth,updated=excluded.updated',[$endpoint,$user,$s['keys']['p256dh'],$s['keys']['auth'],time()]); |
| 50 | } |
| 51 | function pushUnsubscribe(string $user,mixed $endpoint): void { |
| 52 | if (!is_string($endpoint)) throw new DomainException('Invalid push subscription.'); |
| 53 | query('DELETE FROM push_subscriptions WHERE endpoint=? AND user_id=?',[$endpoint,$user]); |
| 54 | } |
| 55 | function pushGame(int $id,string $kind='turn',?string $recipient=null): void { |
| 56 | $g=query('SELECT * FROM games WHERE id=?',[$id])->fetch(); |
| 57 | if (!$g) return; |
| 58 | if ($kind==='turn') { |
| 59 | if ($g['status']!=='active') return; |
| 60 | if ($recipient) { |
| 61 | $GLOBALS['push_events'][$id.':'.$recipient]=['game'=>$id,'user'=>$recipient,'version'=>(int)$g['version'],'kind'=>$kind]; |
| 62 | return; |
| 63 | } |
| 64 | $s=json_decode($g['state'],true); |
| 65 | foreach (SynhexMatch::playersToNotify($g,$s) as $user) { |
| 66 | $GLOBALS['push_events'][$id.':'.$user]=['game'=>$id,'user'=>$user,'version'=>(int)$g['version'],'kind'=>$kind]; |
| 67 | } |
| 68 | return; |
| 69 | } |
| 70 | if (!$recipient) return; |
| 71 | $GLOBALS['push_events'][$id.':'.$recipient]=['game'=>$id,'user'=>$recipient,'version'=>(int)$g['version'],'kind'=>$kind]; |
| 72 | } |
| 73 | function pushAfterCommit(): void { |
| 74 | $events=$GLOBALS['push_events']??[]; |
| 75 | $GLOBALS['push_events']=[]; |
| 76 | if (!$events) return; |
| 77 | // Only committed events reach shutdown. HTTP failures cannot change the API result. |
| 78 | register_shutdown_function(static function() use ($events): void { |
| 79 | session_write_close(); |
| 80 | ignore_user_abort(true); |
| 81 | if (function_exists('fastcgi_finish_request')) fastcgi_finish_request(); |
| 82 | try {pushDeliver($events);} catch (Throwable $e) {error_log('Push delivery failed ('.get_class($e).').');} |
| 83 | }); |
| 84 | } |
| 85 | function pushDeliver(array $events,?Minishlink\WebPush\WebPush $push=null): void { |
| 86 | $jobs=[]; |
| 87 | foreach ($events as $event) { |
| 88 | $g=query('SELECT * FROM games WHERE id=?',[$event['game']])->fetch(); |
| 89 | if (!$g || (int)$g['version']!==$event['version']) continue; |
| 90 | foreach (query('SELECT * FROM push_subscriptions WHERE user_id=?',[$event['user']])->fetchAll() as $s) $jobs[]=[$event,$g,$s]; |
| 91 | } |
| 92 | if (!$jobs) return; |
| 93 | $keys=pushKeys(); |
| 94 | $push??=new Minishlink\WebPush\WebPush(['VAPID'=>['subject'=>baseUrl(),'publicKey'=>$keys['publicKey'],'privateKey'=>$keys['privateKey']]],['TTL'=>3600,'urgency'=>'normal'],5,['connect_timeout'=>2,'allow_redirects'=>false]); |
| 95 | $push->setReuseVAPIDHeaders(true); |
| 96 | foreach ($jobs as [$event,$g,$s]) { |
| 97 | $opponent=profile($g['a']===$event['user']?$g['b']:$g['a'])['name']; |
| 98 | $body=match($event['kind']) {'challenge'=>$opponent.' invited you to play.','rematch'=>$opponent.' wants a rematch.',default=>'Your turn against '.$opponent.'.'}; |
| 99 | $push->queueNotification(Minishlink\WebPush\Subscription::create(['endpoint'=>$s['endpoint'],'contentEncoding'=>'aes128gcm','keys'=>['p256dh'=>$s['p256dh'],'auth'=>$s['auth']]]),json_encode(['title'=>'Synhex','body'=>$body,'game'=>$event['game']],JSON_THROW_ON_ERROR),['topic'=>'game-'.$event['game']]); |
| 100 | } |
| 101 | foreach ($push->flush() as $report) { |
| 102 | if ($report->isSubscriptionExpired()) query('DELETE FROM push_subscriptions WHERE endpoint=?',[(string)$report->getRequest()->getUri()]); |
| 103 | elseif (!$report->isSuccess()) error_log('Push service did not accept a notification.'); |
| 104 | } |
| 105 | } |
projects-timfalken-com microchess