diff --git a/.github/workflows/local-profile.yml b/.github/workflows/local-profile.yml index bb3f8dfd..3255dd13 100644 --- a/.github/workflows/local-profile.yml +++ b/.github/workflows/local-profile.yml @@ -119,6 +119,7 @@ jobs: - run: php -d memory_limit=128M tests/local/game-ready-http.php vendor/autoload.php timeout-minutes: 2 - run: php tests/local/ingame-verification.php vendor/autoload.php + - run: php tests/local/voice-lobbies.php vendor/autoload.php - name: Ckeyinfo loopback identity contracts (offline) timeout-minutes: 2 run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/ckeyinfo-loopback.php vendor/autoload.php @@ -170,6 +171,7 @@ jobs: - run: php -d memory_limit=128M -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,stream_socket_server,stream_socket_accept,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/game-ready-http.php vendor/autoload.php timeout-minutes: 2 - run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/ingame-verification.php vendor/autoload.php + - run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/voice-lobbies.php vendor/autoload.php windows-exe-smoke: if: github.event_name == 'workflow_dispatch' && inputs.native_smoke runs-on: windows-latest diff --git a/docs/launcher-voice.md b/docs/launcher-voice.md new file mode 100644 index 00000000..b5c70db6 --- /dev/null +++ b/docs/launcher-voice.md @@ -0,0 +1,26 @@ +# Launcher voice lobbies + +Bot side of Civ13 launcher voice (Civ13 issue #5122, Phase 3). The game side +is Civ13 `code/modules/voice/voice_chat.dm`, and the design is in Civ13 +`docs/launcher-voice-plan.md`. The code is `src/Civ13/VoiceLobbies.php`. + +- `POST /webhook//voice_roster` (whitelisted; `X-Webhook-Key`): the + game's `{v: 1, members: [{ckey, key, team}]}`. The answer is + `{ids: {ckey: Discord user ID}}` for every ckey that has an account so far. +- Each ckey gets a Discord provisional account through + `partner-sdk/token/bot`, with external user ID `byond:`. Players need + no Discord login. Tokens live only in memory. +- One lobby per world (`civ13_kind: region`) and one per team + (`civ13_kind: team`, `civ13_team`), created with the bot token. Members + follow the roster. A player who drops out of it is removed after 30 + seconds; their launcher key stops working at once. +- `POST /voice/token` (public, 30 per minute per address): + `{id: sha256("civ13-voice-token:" + key)}`. The answer is 202 until the + token exists, then `{v: 1, sealed}`. `sealed` is base64(nonce | ciphertext | + tag) under AES-256-GCM, with key `HKDF-SHA256(key, info "civ13-voice-seal")` + and the token ID as AAD. It opens to `{application_id, server, user_id, + access_token, expires_in}`. + +Needs the Social SDK enabled on the bot's own application in the Discord +Developer Portal (the launcher uses the `application_id` it is given). +Offline contracts: `php tests/local/voice-lobbies.php vendor/autoload.php`. diff --git a/src/Civ13/HttpServiceManager.php b/src/Civ13/HttpServiceManager.php index 4ee09fb4..9f14d401 100644 --- a/src/Civ13/HttpServiceManager.php +++ b/src/Civ13/HttpServiceManager.php @@ -48,6 +48,7 @@ class HttpServiceManager protected array $dwa_discord_ids = []; private ?Directory $launcherDirectory = null; private ?GameReady $gameReady = null; + private ?VoiceLobbies $voiceLobbies = null; private ?TimerInterface $launcherDirectoryTimer = null; /** @param Civ13 $civ13 The bot instance; builds the {@see HttpHandler} and binds `discord`/`logger` by reference. */ @@ -350,6 +351,90 @@ public function handleShutdownNoticeWebhook(ServerRequestInterface $request, Gam return new HttpResponse(HttpResponse::STATUS_ACCEPTED); } + /** + * Launcher voice (Civ13 code/modules/voice/voice_chat.dm): the game POSTs its voice roster as + * JSON with the webhook key in X-Webhook-Key, and gets back {ids: {ckey: Discord user ID}}. + * See {@see VoiceLobbies}. + */ + public function handleVoiceRosterWebhook(ServerRequestInterface $request, GameServer $gameserver): HttpResponse + { + $secret = $this->civ13->options['http_key'] ?? ''; + $key = $request->getHeaderLine('X-Webhook-Key'); + if (!is_string($secret) || $secret === '' || $key === '' || !hash_equals($secret, $key) || $gameserver->legacy_relay) { + return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); + } + if ($request->getMethod() !== 'POST') { + return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED); + } + $body = (string) $request->getBody(); + $data = strlen($body) <= 131072 ? json_decode($body, true, 5) : null; + if (($members = VoiceLobbies::parseRoster($data)) === null) { + return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); + } + if (!$voice = $this->voiceLobbies()) { + return new HttpResponse(HttpResponse::STATUS_SERVICE_UNAVAILABLE); + } + + return HttpResponse::json(['ids' => (object) $voice->roster($gameserver->key, $members)]); + } + + /** + * Launcher voice: the launcher POSTs {id: sha256("civ13-voice-token:" + key)} and gets its + * Discord access token sealed with a key only it and the game know (202 while it is minted). + */ + public function handleVoiceToken(ServerRequestInterface $request): HttpResponse + { + if ($request->getMethod() !== 'POST') { + return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED); + } + $body = (string) $request->getBody(); + $data = strlen($body) <= 256 ? json_decode($body, true, 2) : null; + $id = is_array($data) ? ($data['id'] ?? null) : null; + if (!is_string($id) || preg_match('/^[0-9a-f]{64}$/D', $id) !== 1) { + return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); + } + $sealed = $this->voiceLobbies()?->token($id); + + return $sealed === null + ? HttpResponse::json(['v' => 1, 'ready' => false])->withStatus(HttpResponse::STATUS_ACCEPTED) + : HttpResponse::plaintext($sealed)->withHeader('Content-Type', 'application/json'); + } + + /** The voice service, made on first use once the bot knows its application. */ + private function voiceLobbies(): ?VoiceLobbies + { + if ($this->voiceLobbies !== null) { + return $this->voiceLobbies; + } + $application = $this->discord->application->id ?? null; + if (!is_string($application) || $application === '') { + return null; + } + $discord = $this->discord; + + return $this->voiceLobbies = new VoiceLobbies( + mint: static fn (string $ckey): PromiseInterface => $discord->getHttpClient()->post(\Discord\Http\Endpoint::PARTNER_SDK_TOKEN_BOT, [ + 'external_user_id' => 'byond:'.$ckey, + 'preferred_global_name' => $ckey, + ]), + createLobby: static fn (array $metadata): PromiseInterface => $discord->lobbies->createLobby([ + 'metadata' => $metadata, + 'idle_timeout_seconds' => VoiceLobbies::IDLE_TIMEOUT, + ])->then(static fn ($lobby) => (string) $lobby->id), + // Resolves to the user IDs Discord confirmed as added or updated. + updateMembers: static fn (string $lobby, array $members): PromiseInterface => $discord->lobbies->bulkUpdateMembers($lobby, $members) + ->then(static function ($confirmed): array { + $ids = []; + foreach ($confirmed as $member) { + $ids[] = (string) ($member->id ?? ''); + } + + return $ids; + }), + applicationId: $application, + ); + } + /** * In-game verification (Civ13 code/modules/client/discord_verify.dm): the game POSTs the * player's ckey and the code they typed as JSON, with the webhook key in the X-Webhook-Key @@ -1377,6 +1462,12 @@ function sendGetRequest(endpoint) { fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleInGameVerifyRelay($request), false ) + ->offsetSet( + '/voice/token', // Launcher voice: sealed Discord token for a voice key (VoiceLobbies) + fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleVoiceToken($request), + false + ) + ->setRateLimit('/voice/token', 30, 60) ->offsetSet( '/ss14verified', fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => ($this->civ13->ss14verifier === null ? HttpResponse::json(['error' => 'SS14 verification unavailable'])->withStatus(503) : HttpResponse::json($this->civ13->ss14verifier->toArray())), @@ -1740,6 +1831,11 @@ function (ServerRequestInterface $request, string $endpoint, bool $whitelisted) fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleDiscordVerifyWebhook($request, $gameserver), true ) + ->offsetSet( + $server_endpoint.'/voice_roster', + fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleVoiceRosterWebhook($request, $gameserver), + true + ) ->offsetSet( $server_endpoint.'/respawn_notice', function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { // NYI diff --git a/src/Civ13/Verifier.php b/src/Civ13/Verifier.php index 3ea10a56..c5e0afe3 100644 --- a/src/Civ13/Verifier.php +++ b/src/Civ13/Verifier.php @@ -498,7 +498,7 @@ protected function discordName(string $discord_id): string public static function plainMessage(string $message): string { $message = preg_replace('/<@[&!]?[0-9]+>/', 'staff', $message) ?? ''; - $message = str_replace(['`', '**', PHP_EOL], ['', '', ' '], $message); + $message = str_replace(['`', '**', "\r\n", "\r", "\n"], ['', '', ' ', ' ', ' '], $message); return mb_substr(trim($message), 0, 400); } diff --git a/src/Civ13/VoiceLobbies.php b/src/Civ13/VoiceLobbies.php new file mode 100644 index 00000000..2f4062e2 --- /dev/null +++ b/src/Civ13/VoiceLobbies.php @@ -0,0 +1,387 @@ + + * + * This file is subject to the MIT license that is bundled + * with this source code in the LICENSE.md file. + */ + +namespace Civ13; + +use React\Promise\PromiseInterface; + +/** + * Launcher voice chat, bot side (Civ13 issue #5122 Phase 3; game side is + * code/modules/voice/voice_chat.dm, design in Civ13 docs/launcher-voice-plan.md). + * + * Each game world POSTs a roster of its voice players ({ckey, key, team}) to + * `/webhook//voice_roster`. For every ckey this service: + * - mints a Discord provisional account keyed on the ckey with the bot token + * (DiscordPHP SessionManager::createProvisionalAccount), so players need no + * Discord login, and answers the game with each ckey's Discord user ID; + * - keeps one Discord lobby per world (the region call) and one per team, with + * members set from the roster. A member who leaves the roster is removed + * after REMOVE_GRACE seconds, so a reconnect or a missed POST does not + * churn the lobby. + * + * The launcher fetches its access token from the public `/voice/token` + * endpoint by showing `sha256("civ13-voice-token:" + key)`. The answer is + * sealed with AES-256-GCM under HKDF-SHA256(key, "civ13-voice-seal"), so the + * plain-HTTP web API only ever carries sealed bytes. The raw key reaches the + * bot only in the roster, over https or loopback. + * + * Every Discord effect is an injected closure, so the class runs offline in + * tests. Nothing is stored on disk: a bot restart mints fresh tokens. + */ +final class VoiceLobbies +{ + public const REMOVE_GRACE = 30; + public const MAX_MEMBERS = 500; // per world roster + public const TOKEN_MARGIN = 86400; // re-mint a token with less than a day left + public const IDLE_TIMEOUT = 600; + public const SEAL_INFO = 'civ13-voice-seal'; + public const TOKEN_LABEL = 'civ13-voice-token:'; + + /** @var array ckey => token */ + private array $tokens = []; + /** @var array ckeys being minted */ + private array $minting = []; + /** @var array token id => owner */ + private array $keys = []; + /** @var array> server => ckey => presence */ + private array $rosters = []; + /** @var array lobby name => Discord lobby ID (false while creating) */ + private array $lobbies = []; + /** @var array> lobby name => user IDs Discord has as members */ + private array $members = []; + /** @var array lobby names with a membership request in flight */ + private array $syncing = []; + /** @var \Closure():int */ + private \Closure $clock; + + /** + * @param \Closure(string $ckey): PromiseInterface $mint resolves {access_token, expires_in, id_token} + * @param \Closure(array $metadata): PromiseInterface $createLobby resolves the new lobby's ID + * @param \Closure(string $lobby, list $members): PromiseInterface $updateMembers bulk add/remove, at most 25 + */ + public function __construct( + private \Closure $mint, + private \Closure $createLobby, + private \Closure $updateMembers, + private string $applicationId, + ?\Closure $clock = null, + ) { + $this->clock = $clock ?? static fn (): int => time(); + } + + /** The roster body the game sends, normalised; null when it is not one. */ + public static function parseRoster(mixed $data): ?array + { + if (!is_array($data) || ($data['v'] ?? null) !== 1 || !is_array($data['members'] ?? null) || !array_is_list($data['members'])) { + return null; + } + if (count($data['members']) > self::MAX_MEMBERS) { + return null; + } + $members = []; + foreach ($data['members'] as $member) { + if (!is_array($member)) { + return null; + } + $ckey = $member['ckey'] ?? null; + $key = $member['key'] ?? null; + $team = $member['team'] ?? ''; + if (!is_string($ckey) || preg_match('/^[a-z0-9]{1,30}$/D', $ckey) !== 1) { + return null; + } + if (!is_string($key) || preg_match('/^[A-Za-z0-9_-]{32,64}$/D', $key) !== 1) { + return null; + } + if (!is_string($team) || strlen($team) > 64 || preg_match('/[\x00-\x1F\x7F]/', $team) === 1) { + return null; + } + $members[$ckey] = ['key' => $key, 'team' => $team]; + } + + return $members; + } + + /** What the launcher shows instead of its key. */ + public static function tokenId(string $key): string + { + return hash('sha256', self::TOKEN_LABEL.$key); + } + + /** + * Takes one world's roster, starts any minting and lobby work it needs, and + * returns the Discord user IDs known so far for its ckeys. + * + * @param array $members from {@see parseRoster()} + * @return array ckey => Discord user ID + */ + public function roster(string $server, array $members): array + { + $now = ($this->clock)(); + // PHP turns numeric array keys ("123") into integers; ckeys stay strings. + $members = array_combine(array_map('strval', array_keys($members)), array_values($members)) ?: []; + foreach ($this->keys as $id => $owner) { + if ($owner['server'] === $server && (!isset($members[$owner['ckey']]) || $members[$owner['ckey']]['key'] !== $owner['key'])) { + unset($this->keys[$id]); + } + } + $presence = $this->rosters[$server] ?? []; + foreach ($members as $ckey => $member) { + $ckey = (string) $ckey; + $this->keys[self::tokenId($member['key'])] = ['server' => $server, 'ckey' => $ckey, 'key' => $member['key']]; + $presence[$ckey] = ['team' => $member['team'], 'seen' => $now]; + $this->ensureToken($ckey); + } + // The grace period runs from the first roster without the player. + foreach ($presence as $ckey => $seen) { + if (isset($members[(string) $ckey])) { + continue; + } + $gone = $seen['gone'] ?? $now; + if ($gone <= $now - self::REMOVE_GRACE) { + unset($presence[$ckey]); + } else { + $presence[$ckey]['gone'] = $gone; + } + } + $this->rosters[$server] = $presence; + $this->syncServer($server); + + $ids = []; + foreach ($members as $ckey => $member) { + $ckey = (string) $ckey; + if (isset($this->tokens[$ckey])) { + $ids[$ckey] = $this->tokens[$ckey]['user_id']; + } + } + + return $ids; + } + + /** + * The launcher's sealed token answer for a token ID, or null when the ID + * is unknown or its token is not ready yet. + */ + public function token(string $id): ?string + { + if (preg_match('/^[0-9a-f]{64}$/D', $id) !== 1 || !isset($this->keys[$id])) { + return null; + } + $owner = $this->keys[$id]; + $token = $this->tokens[$owner['ckey']] ?? null; + if ($token === null || $token['expires_at'] <= ($this->clock)()) { + $this->ensureToken($owner['ckey']); + + return null; + } + $payload = json_encode([ + 'v' => 1, + 'application_id' => $this->applicationId, + 'server' => $owner['server'], + 'user_id' => $token['user_id'], + 'access_token' => $token['access_token'], + 'expires_in' => $token['expires_at'] - ($this->clock)(), + ], JSON_THROW_ON_ERROR); + + return json_encode(['v' => 1, 'sealed' => self::seal($owner['key'], $id, $payload)], JSON_THROW_ON_ERROR); + } + + /** AES-256-GCM under HKDF-SHA256(key, SEAL_INFO); AAD is the token ID. base64(nonce|ciphertext|tag). */ + public static function seal(string $key, string $id, string $plaintext): string + { + $nonce = random_bytes(12); + $tag = ''; + $ciphertext = openssl_encrypt($plaintext, 'aes-256-gcm', self::sealKey($key), OPENSSL_RAW_DATA, $nonce, $tag, $id, 16); + if ($ciphertext === false) { + throw new \RuntimeException('Voice token sealing failed'); + } + + return base64_encode($nonce.$ciphertext.$tag); + } + + /** The inverse of {@see seal()}, for tests and tooling. Null when it does not open. */ + public static function open(string $key, string $id, string $sealed): ?string + { + $raw = base64_decode($sealed, true); + if ($raw === false || strlen($raw) < 28) { + return null; + } + $plain = openssl_decrypt(substr($raw, 12, -16), 'aes-256-gcm', self::sealKey($key), OPENSSL_RAW_DATA, substr($raw, 0, 12), substr($raw, -16), $id); + + return $plain === false ? null : $plain; + } + + private static function sealKey(string $key): string + { + return hash_hkdf('sha256', $key, 32, self::SEAL_INFO); + } + + /** The Discord user ID inside a token response's id_token (its `sub`), or null. */ + public static function userIdFromIdToken(mixed $idToken): ?string + { + if (!is_string($idToken) || substr_count($idToken, '.') !== 2) { + return null; + } + $part = explode('.', $idToken)[1]; + $json = base64_decode(strtr($part, '-_', '+/').str_repeat('=', (4 - strlen($part) % 4) % 4), true); + $claims = $json === false ? null : json_decode($json, true); + $sub = is_array($claims) ? ($claims['sub'] ?? null) : null; + + return is_string($sub) && preg_match('/^[0-9]{17,20}$/D', $sub) === 1 ? $sub : null; + } + + /** Lobby names for one world, for tests and status. */ + public function lobbyIds(): array + { + return array_filter($this->lobbies, 'is_string'); + } + + public function memberIds(string $lobby): array + { + return array_map('strval', array_keys($this->members[$lobby] ?? [])); + } + + private function ensureToken(string $ckey): void + { + $token = $this->tokens[$ckey] ?? null; + if (isset($this->minting[$ckey]) || ($token !== null && $token['expires_at'] > ($this->clock)() + self::TOKEN_MARGIN)) { + return; + } + $this->minting[$ckey] = true; + ($this->mint)($ckey)->then(function ($response) use ($ckey): void { + unset($this->minting[$ckey]); + $response = (array) $response; + $user = self::userIdFromIdToken($response['id_token'] ?? null); + $access = $response['access_token'] ?? null; + $expires = (int) ($response['expires_in'] ?? 0); + if ($user === null || !is_string($access) || $access === '' || $expires <= 0) { + return; + } + $this->tokens[$ckey] = ['user_id' => $user, 'access_token' => $access, 'expires_at' => ($this->clock)() + $expires]; + foreach (array_keys($this->rosters) as $server) { + if (isset($this->rosters[$server][$ckey])) { + $this->syncServer($server); + } + } + }, function () use ($ckey): void { + unset($this->minting[$ckey]); + }); + } + + /** Desired members of every lobby belonging to one world. */ + private function desired(string $server): array + { + $want = ['region:'.$server => []]; + foreach ($this->rosters[$server] ?? [] as $ckey => $presence) { + $user = $this->tokens[$ckey]['user_id'] ?? null; + if ($user === null) { + continue; + } + $want['region:'.$server][$user] = true; + if ($presence['team'] !== '') { + $want['team:'.$server.':'.$presence['team']][$user] = true; + } + } + foreach (array_keys($this->lobbies) as $name) { + if (str_starts_with($name, 'team:'.$server.':') && !isset($want[$name])) { + $want[$name] = []; // empty a team nobody is on any more + } + } + + return $want; + } + + private function syncServer(string $server): void + { + foreach ($this->desired($server) as $name => $users) { + $this->syncLobby($server, $name, $users); + } + } + + private function syncLobby(string $server, string $name, array $users): void + { + if (isset($this->syncing[$name])) { + return; + } + if (!isset($this->lobbies[$name])) { + if (!$users) { + return; + } + $this->lobbies[$name] = false; + $kind = str_starts_with($name, 'team:') ? 'team' : 'region'; + $metadata = ['civ13_server' => $server, 'civ13_kind' => $kind]; + if ($kind === 'team') { + $metadata['civ13_team'] = substr($name, strlen('team:'.$server.':')); + } + ($this->createLobby)($metadata)->then(function ($id) use ($server, $name): void { + if (!is_string($id) || $id === '') { + unset($this->lobbies[$name]); + + return; + } + $this->lobbies[$name] = $id; + $this->members[$name] = []; + $this->syncServer($server); + }, function () use ($name): void { + unset($this->lobbies[$name]); + }); + + return; + } + $lobby = $this->lobbies[$name]; + if ($lobby === false) { + return; + } + $have = $this->members[$name] ?? []; + $changes = []; + foreach ($users as $user => $_) { + if (!isset($have[$user])) { + $changes[] = ['id' => (string) $user]; + } + } + foreach ($have as $user => $_) { + if (!isset($users[$user])) { + $changes[] = ['id' => (string) $user, 'remove_member' => true]; + } + } + if (!$changes) { + return; + } + $batch = array_slice($changes, 0, 25); + $this->syncing[$name] = true; + ($this->updateMembers)($lobby, $batch)->then(function ($confirmed = null) use ($server, $name, $batch): void { + unset($this->syncing[$name]); + // Discord can leave out an addition it refused; only confirmed + // additions count, so the rest are tried again on the next roster. + $added = is_array($confirmed) ? array_flip(array_map('strval', $confirmed)) : null; + $progress = false; + foreach ($batch as $change) { + if ($change['remove_member'] ?? false) { + unset($this->members[$name][$change['id']]); + $progress = true; + } elseif ($added === null || isset($added[$change['id']])) { + $this->members[$name][$change['id']] = true; + $progress = true; + } + } + if ($progress) { + $this->syncServer($server); // the next batch, if any + } + }, function ($error = null) use ($name): void { + unset($this->syncing[$name]); // the next roster tries again + if ($error instanceof \Discord\Http\Exceptions\NotFoundException) { + // Discord deleted the lobby (idle timeout); make a new one next time. + unset($this->lobbies[$name], $this->members[$name]); + } + }); + } +} diff --git a/tests/local/voice-lobbies.php b/tests/local/voice-lobbies.php new file mode 100644 index 00000000..69491fdf --- /dev/null +++ b/tests/local/voice-lobbies.php @@ -0,0 +1,135 @@ +addPsr4('Civ13\\', __DIR__.'/../../src/Civ13', true); + +use Civ13\VoiceLobbies; +use React\Promise\Deferred; + +set_error_handler(static function (int $severity, string $message, string $file, int $line): bool { if (! (error_reporting() & $severity)) { return true; } throw new ErrorException($message, 0, $severity, $file, $line); }, E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED); +$checks = 0; +function check(bool $ok, string $why): void { global $checks; ++$checks; if (!$ok) { throw new RuntimeException($why); } } +function idToken(string $sub): string { $b = static fn (string $s): string => rtrim(strtr(base64_encode($s), '+/', '-_'), '='); return $b('{"alg":"none"}').'.'.$b(json_encode(['sub' => $sub])).'.sig'; } + +$now = 1000; +$mints = []; $creates = []; $updates = []; +$voice = new VoiceLobbies( + mint: static function (string $ckey) use (&$mints) { $d = new Deferred(); $mints[] = [$ckey, $d]; return $d->promise(); }, + createLobby: static function (array $metadata) use (&$creates) { $d = new Deferred(); $creates[] = [$metadata, $d]; return $d->promise(); }, + updateMembers: static function (string $lobby, array $members) use (&$updates) { $d = new Deferred(); $updates[] = [$lobby, $members, $d]; return $d->promise(); }, + applicationId: '1562126764849897544', + clock: static function () use (&$now): int { return $now; }, +); +$keyA = str_repeat('a', 40); $keyB = str_repeat('b', 40); + +// Parsing the game's roster. +$parsed = VoiceLobbies::parseRoster(['v' => 1, 'members' => [['ckey' => 'alice', 'key' => $keyA, 'team' => 'GERMAN'], ['ckey' => 'bob', 'key' => $keyB, 'team' => '']]]); +check($parsed === ['alice' => ['key' => $keyA, 'team' => 'GERMAN'], 'bob' => ['key' => $keyB, 'team' => '']], 'roster parsed'); +check(VoiceLobbies::parseRoster(['v' => 1, 'members' => []]) === [], 'an empty roster is a roster'); +foreach ([null, [], ['v' => 2, 'members' => []], ['v' => 1, 'members' => ['x' => []]], + ['v' => 1, 'members' => [['ckey' => 'Alice', 'key' => $keyA]]], + ['v' => 1, 'members' => [['ckey' => 'alice', 'key' => 'short']]], + ['v' => 1, 'members' => [['ckey' => 'alice', 'key' => $keyA, 'team' => "a\nb"]]], + ['v' => 1, 'members' => array_fill(0, VoiceLobbies::MAX_MEMBERS + 1, ['ckey' => 'a', 'key' => $keyA])]] as $bad) { + check(VoiceLobbies::parseRoster($bad) === null, 'bad roster rejected: '.json_encode($bad === null ? null : array_slice((array) $bad, 0, 2))); +} + +// First roster: mints both, knows no IDs yet, makes no lobby before an ID exists. +check($voice->roster('tdm', $parsed) === [], 'no IDs before minting'); +check(array_column($mints, 0) === ['alice', 'bob'], 'each ckey minted once'); +check(count($creates) === 0, 'no empty lobby is created'); +check($voice->token(VoiceLobbies::tokenId($keyA)) === null, 'no token before minting'); +$voice->roster('tdm', $parsed); +check(count($mints) === 2, 'a second roster does not mint again while minting'); + +$mints[0][1]->resolve(['access_token' => 'tok-alice', 'expires_in' => 604800, 'id_token' => idToken('100000000000000001')]); +check(count($creates) === 2, 'region and team lobbies are created once alice has an ID'); +check($creates[0][0] === ['civ13_server' => 'tdm', 'civ13_kind' => 'region'], 'region lobby metadata'); +check($creates[1][0] === ['civ13_server' => 'tdm', 'civ13_kind' => 'team', 'civ13_team' => 'GERMAN'], 'team lobby metadata'); +$creates[0][1]->resolve('900000000000000001'); +check(count($updates) === 1 && $updates[0][0] === '900000000000000001' && $updates[0][1] === [['id' => '100000000000000001']], 'alice added to the region lobby'); +$creates[1][1]->resolve('900000000000000002'); +check(count($updates) === 2 && $updates[1][0] === '900000000000000002', 'alice added to her team lobby'); +$updates[0][2]->resolve(null); $updates[1][2]->resolve(null); +check($voice->memberIds('region:tdm') === ['100000000000000001'], 'region membership recorded'); + +$mints[1][1]->resolve(['access_token' => 'tok-bob', 'expires_in' => 604800, 'id_token' => idToken('100000000000000002')]); +check(count($updates) === 3 && $updates[2][1] === [['id' => '100000000000000002']], 'bob joins the region only (no team)'); +$updates[2][2]->resolve(null); +check($voice->roster('tdm', $parsed) === ['alice' => '100000000000000001', 'bob' => '100000000000000002'], 'the game gets both IDs'); +check(count($updates) === 3, 'an unchanged roster sends nothing'); + +// The launcher's sealed token. +$sealed = json_decode($voice->token(VoiceLobbies::tokenId($keyA)), true); +check(is_array($sealed) && $sealed['v'] === 1 && is_string($sealed['sealed']) && !str_contains($sealed['sealed'], 'tok-alice'), 'the token is sealed'); +$opened = json_decode(VoiceLobbies::open($keyA, VoiceLobbies::tokenId($keyA), $sealed['sealed']), true); +check($opened['access_token'] === 'tok-alice' && $opened['user_id'] === '100000000000000001' && $opened['application_id'] === '1562126764849897544' && $opened['server'] === 'tdm' && $opened['expires_in'] === 604800, 'it opens with the key'); +check(VoiceLobbies::open($keyB, VoiceLobbies::tokenId($keyA), $sealed['sealed']) === null, 'another key cannot open it'); +check(VoiceLobbies::open($keyA, VoiceLobbies::tokenId($keyB), $sealed['sealed']) === null, 'it is bound to its token ID'); +check($voice->token(str_repeat('0', 64)) === null && $voice->token('not hex') === null, 'unknown IDs get nothing'); + +// Leaving: kept for the grace period, then removed. +$onlyAlice = ['alice' => $parsed['alice']]; +$voice->roster('tdm', $onlyAlice); +check(count($updates) === 3, 'bob is kept while within the grace period'); +check($voice->token(VoiceLobbies::tokenId($keyB)) === null, 'but his launcher key stops working at once'); +$now += VoiceLobbies::REMOVE_GRACE; +$voice->roster('tdm', $onlyAlice); +check(count($updates) === 4 && $updates[3][1] === [['id' => '100000000000000002', 'remove_member' => true]], 'bob is removed after the grace period'); +$updates[3][2]->resolve(null); + +// A team change moves alice; an emptied team lobby is emptied, not left stale. +$voice->roster('tdm', ['alice' => ['key' => $keyA, 'team' => 'SOVIET']]); +$teamCreates = array_values(array_filter($creates, static fn ($c) => ($c[0]['civ13_team'] ?? '') === 'SOVIET')); +check(count($teamCreates) === 1, 'the new team gets its lobby'); +$last = end($updates); +check($last[0] === '900000000000000002' && $last[1] === [['id' => '100000000000000001', 'remove_member' => true]], 'she leaves the old team lobby'); + +// A failed mint leaves room to try again; a response without a user ID is ignored. +$voice->roster('tdm', ['carol' => ['key' => str_repeat('c', 40), 'team' => '']]); +$carol = end($mints); $carol[1]->reject(new RuntimeException('rate limited')); +$voice->roster('tdm', ['carol' => ['key' => str_repeat('c', 40), 'team' => '']]); +$again = end($mints); check($again !== $carol && $again[0] === 'carol', 'minting is retried after a failure'); +$again[1]->resolve(['access_token' => 'x', 'expires_in' => 10]); +check($voice->token(VoiceLobbies::tokenId(str_repeat('c', 40))) === null, 'no user ID, no token'); + +check(VoiceLobbies::userIdFromIdToken(idToken('123456789012345678')) === '123456789012345678', 'id_token sub read'); +check(VoiceLobbies::userIdFromIdToken('a.b') === null && VoiceLobbies::userIdFromIdToken(idToken('nope')) === null && VoiceLobbies::userIdFromIdToken(null) === null, 'bad id_tokens rejected'); + +// Review fixes: numeric ckeys, grace from the first absence, refused +// additions and lobbies Discord deleted. +$now = 5000; $mints = []; $creates = []; $updates = []; +$fresh = new VoiceLobbies( + mint: static function (string $ckey) use (&$mints) { $d = new Deferred(); $mints[] = [$ckey, $d]; return $d->promise(); }, + createLobby: static function (array $metadata) use (&$creates) { $d = new Deferred(); $creates[] = [$metadata, $d]; return $d->promise(); }, + updateMembers: static function (string $lobby, array $members) use (&$updates) { $d = new Deferred(); $updates[] = [$lobby, $members, $d]; return $d->promise(); }, + applicationId: '1562126764849897544', + clock: static function () use (&$now): int { return $now; }, +); +$numeric = VoiceLobbies::parseRoster(['v' => 1, 'members' => [['ckey' => '123', 'key' => $keyA, 'team' => '']]]); +check(is_array($numeric) && $fresh->roster('tdm', $numeric) === [], 'a numeric ckey is a roster, not a TypeError'); +check($mints[0][0] === '123', 'numeric ckeys are minted as strings'); +$mints[0][1]->resolve(['access_token' => 'tok-n', 'expires_in' => 604800, 'id_token' => idToken('100000000000000009')]); +$creates[0][1]->resolve('900000000000000009'); +$updates[0][2]->resolve([]); // Discord left the addition out +check($fresh->memberIds('region:tdm') === [], 'an addition Discord did not confirm is not recorded'); +$fresh->roster('tdm', $numeric); +check(count($updates) === 2 && $updates[1][1] === [['id' => '100000000000000009']], 'and is tried again on the next roster'); +$updates[1][2]->resolve(['100000000000000009']); +check($fresh->memberIds('region:tdm') === ['100000000000000009'], 'a confirmed addition is recorded'); +$now += 1000; // a long quiet spell, then the player leaves +$fresh->roster('tdm', []); +check(count($updates) === 2, 'the grace period starts at the first roster without the player'); +$now += VoiceLobbies::REMOVE_GRACE; +$fresh->roster('tdm', []); +check(count($updates) === 3 && ($updates[2][1][0]['remove_member'] ?? false), 'and ends after it'); +$updates[2][2]->resolve(null); +$fresh->roster('tdm', $numeric); +$last = end($updates); +$last[2]->reject(new \Discord\Http\Exceptions\NotFoundException('Unknown Lobby')); +$fresh->roster('tdm', $numeric); +check(count($creates) === 2 && $creates[1][0]['civ13_kind'] === 'region', 'a lobby Discord deleted is made again'); + +echo "voice lobby contracts: {$checks} checks passed\n";