From 29491397705b6f9c2dcbc6e58f05bbebd4d2c3dd Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 13:03:15 +0000 Subject: [PATCH 1/4] Verify Discord from inside the game /approveme without a ckey gives a private single-use code. The game's Verify Discord verb sends ckey + code as the discord_verify webhook; the primary bot redeems it (bans, age and alt review still apply), and a desktop bot with the read-only verifier relays it to the primary bot's HMAC-signed /verified/ingame endpoint (INGAME_VERIFY_TOKEN). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016WTP2R6s5HsPDzf2CSzzGM --- .github/workflows/local-profile.yml | 2 + bot.php | 4 +- docs/ingame-verification.md | 34 ++++ docs/windows-test1714.md | 2 +- src/Civ13/Civ13.php | 3 + src/Civ13/HttpServiceManager.php | 117 +++++++++++ src/Civ13/InGameVerification.php | 177 +++++++++++++++++ .../MessageCommand/Commands/ApproveMe.php | 2 +- src/Civ13/Slash.php | 46 +++-- src/Civ13/Verifier.php | 182 ++++++++++++++---- tests/local/ingame-verification.php | 126 ++++++++++++ tests/windows/bootstrap.php | 2 +- 12 files changed, 641 insertions(+), 56 deletions(-) create mode 100644 docs/ingame-verification.md create mode 100644 src/Civ13/InGameVerification.php create mode 100644 tests/local/ingame-verification.php diff --git a/.github/workflows/local-profile.yml b/.github/workflows/local-profile.yml index 638b4882..bb3f8dfd 100644 --- a/.github/workflows/local-profile.yml +++ b/.github/workflows/local-profile.yml @@ -118,6 +118,7 @@ jobs: timeout-minutes: 2 - 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 - 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 @@ -168,6 +169,7 @@ jobs: timeout-minutes: 2 - 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 windows-exe-smoke: if: github.event_name == 'workflow_dispatch' && inputs.native_smoke runs-on: windows-latest diff --git a/bot.php b/bot.php index 81cd2d9e..dc94a53d 100644 --- a/bot.php +++ b/bot.php @@ -315,7 +315,7 @@ function loadEnv(string $filePath, bool $explicit = false): array //'pers' => '753768492834095235', ], ]; -$options['welcome_message'] = 'Welcome to the Civ13 Discord Server! Please read the rules and verify your account using the `/approveme` slash command (Civ13) or the `/verifyme` slash command (Civ14).'; // . ' Failure to verify in a timely manner will result in an automatic removal from the server.'; +$options['welcome_message'] = 'Welcome to the Civ13 Discord Server! Please read the rules and verify your account using the `/approveme` slash command (Civ13; leave the ckey empty to get a code you can enter in game with the **Verify Discord** verb in the OOC tab) or the `/verifyme` slash command (Civ14).'; // . ' Failure to verify in a timely manner will result in an automatic removal from the server.'; /* foreach (['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я', 'і', 'ї', 'є'] as $char) { // // Ban use of Cyrillic characters $arr = ['word' => $char, 'duration' => '999 years', 'reason' => 'только английский.', 'category' => 'language', 'method' => 'str_contains', 'warnings' => 2]; @@ -517,6 +517,7 @@ function loadEnv(string $filePath, bool $explicit = false): array 'web_address' => getenv('web_address') ?: 'www.civ13.com', 'http_port' => intval(getenv('http_port')) ?: 55555, // 25565 for testing on Windows 'http_key' => getenv('WEBAPI_TOKEN') ?: 'CHANGEME', + 'ingame_verify_key' => getenv('INGAME_VERIFY_TOKEN') ?: '', // Shared with desktop bots that relay in-game verification; empty turns the relay endpoint off 'http_whitelist' => $http_whitelist, 'civ_token' => getenv('CIV_TOKEN') ?: 'CHANGEME', 'civ13_server_settings' => $civ13_server_settings, // Server specific settings, listed in the order in which they appear on the VZG server list. @@ -536,6 +537,7 @@ function loadEnv(string $filePath, bool $explicit = false): array $options = PortableProfile::runtimeOptions($portable); $hidden_options['http_key'] = PortableProfile::environmentValue('WEBAPI_TOKEN', $loadedNames); $hidden_options['civ_token'] = PortableProfile::environmentValue('CIV_TOKEN', $loadedNames); + $hidden_options['ingame_verify_key'] = PortableProfile::environmentValue('INGAME_VERIFY_TOKEN', $loadedNames); $civ13_server_settings = $portable['servers']; $civ14_server_settings = []; $hidden_options['civ13_server_settings'] = $civ13_server_settings; diff --git a/docs/ingame-verification.md b/docs/ingame-verification.md new file mode 100644 index 00000000..9bb1acce --- /dev/null +++ b/docs/ingame-verification.md @@ -0,0 +1,34 @@ +# In-game verification + +Players can link their BYOND key to Discord without editing their BYOND profile. + +1. In Discord, the player runs `/approveme` **without** a ckey. CivilizationBot replies + privately with a single-use code such as `ABCD-EFGH`, valid for 10 minutes. +2. In any Civ13 server, the player opens the OOC tab, clicks **Verify Discord** and types the code. +3. The game sends `ckey` + `code` to its own bot as the `discord_verify` webhook method + (`/webhook//discord_verify?key=&data={"ckey","code"}`) and shows the + JSON `{ok, message}` answer to the player. + +BYOND has already signed the player in, so the game proves the ckey and the private code proves +the Discord account. Bans, investigations, existing links, the BYOND account age rule and the +alt/multi-Discord staff review still apply (`Verifier::processInGame`). The "seen on our servers" +check is skipped because the player is on a server right now. Five wrong codes lock that ckey +out of in-game verification for ten minutes. Codes are kept in memory only. + +## Primary and desktop bots + +- **CivilizationBot** (primary, writes the verified list) redeems the code itself. +- **VZGCivilizationBot** (desktop profile with the read-only hosted verifier) cannot register anyone. + It forwards the request to the primary bot's `POST /verified/ingame` endpoint next to the hosted + verified list (`verification_source.url` + `/ingame`), signed with `X-Ingame-Verify-Time` and + `X-Ingame-Verify-Signature` (HMAC-SHA256 of `time + "\n" + body` with the shared secret), then passes the primary bot's answer back to the game. The link reaches the desktop game through + the normal hosted verified-list refresh and access-file sync. + +Both bots need the same random secret as `INGAME_VERIFY_TOKEN`: in the primary bot's `.env` and +in the desktop profile's environment file. Without it the primary bot refuses relays (403) and the +desktop bot tells players to use `/approveme` in Discord instead. The secret itself is never sent, so +the plain-HTTP `http://civ13.com:55555` source is acceptable: a captured request expires after 60 seconds +and its code is single use. Anyone holding the secret could link any ckey to a Discord user with a live +code, so keep it out of logs and chat. + +`/approveme` is re-registered on every start so existing installs get the optional ckey. diff --git a/docs/windows-test1714.md b/docs/windows-test1714.md index b6b533ac..8d2fffc5 100644 --- a/docs/windows-test1714.md +++ b/docs/windows-test1714.md @@ -58,7 +58,7 @@ exclusive state lock. A duplicate launch cannot enter the bot bootstrap after that lock. stop writes a one-use marker consumed by the owning loop, not a process name kill. A stop marker left by an absent/crashed process requires operator inspection before restart. A stop request is not evidence that a process exited. -Only WEBAPI_TOKEN and CIV_TOKEN explicitly present in the separate environment file +Only WEBAPI_TOKEN, CIV_TOKEN and INGAME_VERIFY_TOKEN explicitly present in the separate environment file are used; inherited values are ignored. Cache files are pinned under state/json. The check/start/stop tools reject a profile belonging to a different checkout. diff --git a/src/Civ13/Civ13.php b/src/Civ13/Civ13.php index 36997e94..29b1aec0 100644 --- a/src/Civ13/Civ13.php +++ b/src/Civ13/Civ13.php @@ -533,6 +533,7 @@ private function resolveOptions(array &$options = []): array 'gitdir', 'github', 'http_key', + 'ingame_verify_key', 'http_port', 'http_whitelist', 'launcher_directory', @@ -583,6 +584,7 @@ private function resolveOptions(array &$options = []): array 'gitdir' => '', 'github' => 'https://github.com/VZGCoders/Civilizationbot', 'http_key' => '', + 'ingame_verify_key' => '', 'http_port' => 0, 'http_whitelist' => [], 'launcher_directory' => [], @@ -637,6 +639,7 @@ private function resolveOptions(array &$options = []): array ->setAllowedTypes('gitdir', 'string') ->setAllowedTypes('github', 'string') ->setAllowedTypes('http_key', 'string') + ->setAllowedTypes('ingame_verify_key', 'string') ->setAllowedTypes('game_ready_events', 'array') ->setAllowedTypes('http_port', 'int') ->setAllowedTypes('http_whitelist', 'array') diff --git a/src/Civ13/HttpServiceManager.php b/src/Civ13/HttpServiceManager.php index 285d5d02..8df7b224 100644 --- a/src/Civ13/HttpServiceManager.php +++ b/src/Civ13/HttpServiceManager.php @@ -22,6 +22,7 @@ use Discord\Parts\Channel\Message; use Discord\Parts\User\Member; use Monolog\Logger; +use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use React\EventLoop\TimerInterface; use React\Http\HttpServer; @@ -349,6 +350,112 @@ public function handleShutdownNoticeWebhook(ServerRequestInterface $request, Gam return new HttpResponse(HttpResponse::STATUS_ACCEPTED); } + /** + * In-game verification (Civ13 code/modules/accounts/discord_verify.dm): the game sends the + * player's ckey and the code they typed. The primary bot redeems it; a desktop bot with a + * read-only verifier relays it to the primary bot. Once authenticated the answer is always + * 200 JSON {ok, message}, which the game shows to the player. + */ + public function handleDiscordVerifyWebhook(ServerRequestInterface $request, GameServer $gameserver): HttpResponse + { + $secret = $this->civ13->options['http_key'] ?? ''; + $key = $request->getQueryParams()['key'] ?? null; + if (!is_string($secret) || $secret === '' || !is_string($key) || !hash_equals($secret, $key) || $gameserver->legacy_relay) { + return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); + } + if (!$data = self::inGameVerifyRequest(self::decodeParamData($request))) { + return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); + } + if (!$this->civ13->verifier->readOnly) { + return HttpResponse::json($this->civ13->verifier->redeemInGame($data['ckey'], $data['code'])); + } + + // The web API runs each request in a fiber (bot.php), so waiting here does not block the loop. + return HttpResponse::json(\React\Async\await($this->relayInGameVerification($data['ckey'], $data['code']))); + } + + /** Primary bot: in-game registrations relayed by a desktop bot that shares INGAME_VERIFY_TOKEN (HMAC-signed, see below). */ + public function handleInGameVerifyRelay(ServerRequestInterface $request): HttpResponse + { + $secret = $this->civ13->options['ingame_verify_key'] ?? ''; + if (!is_string($secret) || $secret === '' || $this->civ13->verifier->readOnly) { + return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); + } + if ($request->getMethod() !== 'POST') { + return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED); + } + $body = (string) $request->getBody(); + if (strlen($body) > 1024 || !self::inGameRelaySignatureValid($secret, $request->getHeaderLine('X-Ingame-Verify-Time'), $body, $request->getHeaderLine('X-Ingame-Verify-Signature'))) { + return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); + } + $data = json_decode($body, true, 4); + if (!is_array($data) || !$data = self::inGameVerifyRequest($data)) { + return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); + } + + return HttpResponse::json($this->civ13->verifier->redeemInGame($data['ckey'], $data['code'])); + } + + /** Desktop bot: forwards to the primary bot. Resolves {ok, message}; never rejects. */ + public function relayInGameVerification(string $ckey, string $code): PromiseInterface + { + $url = InGameVerification::relayUrl($this->civ13->verifier->verify_url); + $key = $this->civ13->options['ingame_verify_key'] ?? ''; + if ($url === null || !is_string($key) || $key === '') { + return \React\Promise\resolve(['ok' => false, 'message' => 'Verifying from this server is not set up yet. Use /approveme in Discord instead.']); + } + + $body = json_encode(['ckey' => $ckey, 'code' => $code], JSON_THROW_ON_ERROR); + $time = (string) time(); + + return $this->civ13->browser->withTimeout(10.0)->withRejectErrorResponse(false)->post( + $url, + ['Content-Type' => 'application/json', 'X-Ingame-Verify-Time' => $time, 'X-Ingame-Verify-Signature' => self::inGameRelaySignature($key, $time, $body)], + $body + )->then(function (ResponseInterface $response): array { + $body = json_decode((string) $response->getBody(), true, 4); + if ($response->getStatusCode() === 200 && is_array($body) && is_bool($body['ok'] ?? null) && is_string($body['message'] ?? null)) { + return ['ok' => $body['ok'], 'message' => mb_substr($body['message'], 0, 400)]; + } + $this->logger->warning('In-game verification relay refused', ['status' => $response->getStatusCode()]); + + return ['ok' => false, 'message' => 'The main Civ13 bot refused the request. Try again later, or use /approveme in Discord.']; + }, function (\Throwable $error): array { + $this->logger->warning('In-game verification relay unreachable', ['error' => $error->getMessage()]); + + return ['ok' => false, 'message' => 'The main Civ13 bot could not be reached. Try again later, or use /approveme in Discord.']; + }); + } + + /** + * The relay may cross plain HTTP, so the shared secret never travels: the desktop bot signs + * time + body with it. A captured request is useless after a minute, and its code is single use. + */ + public static function inGameRelaySignature(string $secret, string $time, string $body): string + { + return hash_hmac('sha256', $time."\n".$body, $secret); + } + + public static function inGameRelaySignatureValid(string $secret, string $time, string $body, string $signature, ?int $now = null): bool + { + if ($secret === '' || preg_match('/^[0-9]{1,12}$/D', $time) !== 1 || abs(($now ?? time()) - (int) $time) > 60 || preg_match('/^[0-9a-f]{64}$/D', $signature) !== 1) { + return false; + } + + return hash_equals(self::inGameRelaySignature($secret, $time, $body), $signature); + } + + /** {ckey, code} from the game or a relay, or null. The game sends a BYOND ckey: lower-case letters and digits. */ + public static function inGameVerifyRequest(array $data): ?array + { + if (!is_string($data['ckey'] ?? null) || preg_match('/^[a-z0-9]{1,32}$/D', $data['ckey']) !== 1 + || !is_string($data['code'] ?? null) || $data['code'] === '' || strlen($data['code']) > 32) { + return null; + } + + return ['ckey' => $data['ckey'], 'code' => $data['code']]; + } + /** "2 minutes", "1 minute 30 seconds", "45 seconds". */ public static function shutdownNoticeDuration(int $seconds): string { @@ -1250,6 +1357,11 @@ function sendGetRequest(endpoint) { ), false ) + ->offsetSet( + '/verified/ingame', // Desktop bots relay in-game verification here (INGAME_VERIFY_TOKEN) + fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleInGameVerifyRelay($request), + false + ) ->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())), @@ -1608,6 +1720,11 @@ function (ServerRequestInterface $request, string $endpoint, bool $whitelisted) fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleShutdownNoticeWebhook($request, $gameserver), true ) + ->offsetSet( + $server_endpoint.'/discord_verify', + fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleDiscordVerifyWebhook($request, $gameserver), + true + ) ->offsetSet( $server_endpoint.'/respawn_notice', function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { // NYI diff --git a/src/Civ13/InGameVerification.php b/src/Civ13/InGameVerification.php new file mode 100644 index 00000000..f7b083f1 --- /dev/null +++ b/src/Civ13/InGameVerification.php @@ -0,0 +1,177 @@ + + * + * This file is subject to the MIT license that is bundled + * with this source code in the LICENSE.md file. + */ + +namespace Civ13; + +/** + * Verification from inside the game. + * + * A player runs `/approveme` without a ckey and gets a short single-use code that + * only they can see. They type it into the game's "Verify Discord" verb. The game + * already knows their BYOND key (BYOND signed them in), so the code proves the + * Discord side and the game proves the ckey; no BYOND profile token is needed. + * + * The game sends `ckey` + `code` to its own bot (`/webhook//discord_verify`). + * The primary bot redeems it here. A desktop bot with a read-only verifier cannot + * register anyone, so it forwards the same request to the primary bot's + * `/verified/ingame` relay endpoint and hands the answer back to the game. + * + * Codes live only in memory: a bot restart simply asks players for a new code. + */ +final class InGameVerification +{ + public const CODE_LIFETIME = 600; // seconds + public const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no 0/O or 1/I + public const CODE_LENGTH = 8; + public const MAX_CODES = 2000; + public const MAX_FAILURES = 5; // per ckey per FAILURE_WINDOW + public const FAILURE_WINDOW = 600; + + /** @var array code => owner */ + private array $codes = []; + /** @var array> ckey => failure times */ + private array $failures = []; + /** @var \Closure():int */ + private \Closure $clock; + + public function __construct(?\Closure $clock = null) + { + $this->clock = $clock ?? static fn (): int => time(); + } + + /** A fresh code for this Discord user; any older code of theirs stops working. */ + public function issue(string $discord_id): string + { + if (preg_match('/^[0-9]{17,20}$/D', $discord_id) !== 1) { + throw new \InvalidArgumentException('Discord ID expected'); + } + $this->prune(); + foreach ($this->codes as $code => $owner) { + if ($owner['discord'] === $discord_id) { + unset($this->codes[$code]); + } + } + if (count($this->codes) >= self::MAX_CODES) { + array_shift($this->codes); // oldest first + } + do { + $code = ''; + for ($i = 0; $i < self::CODE_LENGTH; $i++) { + $code .= self::CODE_ALPHABET[random_int(0, strlen(self::CODE_ALPHABET) - 1)]; + } + } while (isset($this->codes[$code])); + $this->codes[$code] = ['discord' => $discord_id, 'expires' => ($this->clock)() + self::CODE_LIFETIME]; + + return self::display($code); + } + + /** `ABCDEFGH` -> `ABCD-EFGH`, the way players see it. */ + public static function display(string $code): string + { + return substr($code, 0, 4).'-'.substr($code, 4); + } + + /** Players may type the code with spaces, dashes or lower case. Null when it can't be a code. */ + public static function normalize(mixed $code): ?string + { + if (!is_string($code) || strlen($code) > 32) { + return null; + } + $code = strtoupper(preg_replace('/[\s-]+/', '', $code) ?? ''); + $alphabet = preg_quote(self::CODE_ALPHABET, '/'); + + return preg_match('/^['.$alphabet.']{'.self::CODE_LENGTH.'}$/D', $code) === 1 ? $code : null; + } + + /** Whether this ckey has used up its wrong guesses for now. */ + public function locked(string $ckey): bool + { + $this->prune(); + + return count($this->failures[$ckey] ?? []) >= self::MAX_FAILURES; + } + + /** + * Takes the code out of circulation and returns its Discord ID, or null when it is + * unknown or expired (that counts as a wrong guess for the ckey). + */ + public function consume(string $ckey, string $code): ?string + { + $this->prune(); + if ($this->locked($ckey)) { + return null; + } + $code = self::normalize($code); + if ($code === null || !isset($this->codes[$code])) { + $this->failures[$ckey][] = ($this->clock)(); + + return null; + } + $discord_id = $this->codes[$code]['discord']; + unset($this->codes[$code], $this->failures[$ckey]); + + return $discord_id; + } + + /** Number of live codes, for tests and status output. */ + public function count(): int + { + $this->prune(); + + return count($this->codes); + } + + private function prune(): void + { + $now = ($this->clock)(); + foreach ($this->codes as $code => $owner) { + if ($owner['expires'] <= $now) { + unset($this->codes[$code]); + } + } + foreach ($this->failures as $ckey => $times) { + $times = array_values(array_filter($times, static fn (int $time): bool => $time > $now - self::FAILURE_WINDOW)); + if ($times) { + $this->failures[$ckey] = $times; + } else { + unset($this->failures[$ckey]); + } + } + } + + /** + * Where a read-only desktop bot forwards in-game registrations: the primary bot's relay + * endpoint beside its public verified list. HTTPS when the profile names an HTTPS source. + */ + public static function relayUrl(string $verify_url): ?string + { + if (!PortableProfile::hostedVerificationUrl($verify_url)) { + return null; + } + + return rtrim($verify_url, '/').'/ingame'; + } + + /** The player-facing reply to `/approveme` without a ckey. */ + public static function codeMessage(string $code): string + { + $minutes = intdiv(self::CODE_LIFETIME, 60); + + return "Your in-game verification code is `$code` (it works once, for the next $minutes minutes).".PHP_EOL + .'1. Join any Civ13 server with the BYOND account you want to link.'.PHP_EOL + .'2. Open the **OOC** tab and click **Verify Discord**.'.PHP_EOL + .'3. Type this code when it asks.'.PHP_EOL + .'Never give this code to anyone else: whoever types it in links their BYOND account to your Discord.'.PHP_EOL + .'Prefer the BYOND profile method instead? Use `/approveme ckey:`.'; + } +} diff --git a/src/Civ13/MessageCommand/Commands/ApproveMe.php b/src/Civ13/MessageCommand/Commands/ApproveMe.php index 08dec5c3..b49fb4fa 100644 --- a/src/Civ13/MessageCommand/Commands/ApproveMe.php +++ b/src/Civ13/MessageCommand/Commands/ApproveMe.php @@ -35,7 +35,7 @@ public function __invoke(Message $message, string $command, array $message_filte ->then(static fn () => $message->react('👍')); } if (! $ckey = self::messageWithoutCommand($command, $message_filtered, true, true)) { - return $this->civ13->reply($message, 'Invalid format! Please use the format `approveme ckey`'); + return $this->civ13->reply($message, 'Invalid format! Please use the format `approveme ckey`, or run the `/approveme` slash command without a ckey to get a private code for verifying from inside the game.'); } return $this->civ13->reply($message, $this->civ13->verifier->process($ckey, $message->user_id, $message->member)); diff --git a/src/Civ13/Slash.php b/src/Civ13/Slash.php index 8dd6a634..e9d18165 100644 --- a/src/Civ13/Slash.php +++ b/src/Civ13/Slash.php @@ -557,21 +557,24 @@ private function __updateGuildCommands(): void // if ($command = $commands->get('name', 'restart_server')) $commands->delete($command); // if ($command = $commands->get('name', 'approveme')) $commands->delete($command); - if (! $commands->get('name', 'approveme')) { - $this->save($commands, new Command($this->discord, [ - 'name' => 'approveme', - 'description' => 'Civ13 verification process', - 'contexts' => [Interaction::CONTEXT_TYPE_GUILD], - 'options' => [ - [ - 'name' => 'ckey', - 'description' => 'Byond.com username', - 'type' => Option::STRING, - 'required' => true, - ], + // Reconciled every start so the optional ckey (in-game verification) reaches existing installs. + $approveme = [ + 'name' => 'approveme', + 'description' => 'Civ13 verification: leave ckey empty for an in-game code', + 'contexts' => [Interaction::CONTEXT_TYPE_GUILD], + 'options' => [ + [ + 'name' => 'ckey', + 'description' => 'Byond.com username (leave empty to verify from inside the game)', + 'type' => Option::STRING, + 'required' => false, ], - ])); + ], + ]; + if ($existing = $commands->get('name', 'approveme')) { + $approveme['id'] = $existing->id; } + $this->save($commands, new Command($this->discord, $approveme)); // if ($command = $commands->get('name', 'verifyme')) $commands->delete($command); if (! $commands->get('name', 'verifyme')) { @@ -1076,7 +1079,22 @@ private function __declareListeners(): void if ($interaction->member->roles->has($this->civ13->role_ids['Verified'])) { return $this->respondWithMessage($interaction, Civ13::createBuilder()->setContent('You already have the verification role!'), true); } - if (! isset($interaction->data->options['ckey']) || ! $ckey = Civ13::sanitizeInput($interaction->data->options['ckey']->value)) { + if (! isset($interaction->data->options['ckey'])) { // In-game verification: a private single-use code + if ($this->civ13->verifier->readOnly) { + return $this->respondWithMessage($interaction, Civ13::createBuilder()->setContent('Run `/approveme` with CivilizationBot for your in-game verification code; that code works on every Civ13 server.'), true); + } + if (isset($this->civ13->softbanned[$interaction->member->id])) { + return $this->respondWithMessage($interaction, Civ13::createBuilder()->setContent('This account is currently under investigation.'), true); + } + if ($this->civ13->verifier->get('discord', $interaction->member->id)) { + return $this->respondWithMessage($interaction, Civ13::createBuilder()->setContent('You are already verified! Your roles are being restored.'), true)->then( + fn (): PromiseInterface => $interaction->member->setRoles([$this->civ13->role_ids['Verified']], 'approveme in-game (already verified)') + ); + } + + return $this->respondWithMessage($interaction, Civ13::createBuilder()->setContent(InGameVerification::codeMessage($this->civ13->verifier->inGame->issue($interaction->member->id))), true); + } + if (! $ckey = Civ13::sanitizeInput($interaction->data->options['ckey']->value)) { return $this->respondWithMessage($interaction, Civ13::createBuilder()->setContent('Invalid ckey.'), true); } if (isset($this->civ13->softbanned[$interaction->member->id]) || isset($this->civ13->softbanned[$ckey])) { diff --git a/src/Civ13/Verifier.php b/src/Civ13/Verifier.php index 3a6b531a..3ea10a56 100644 --- a/src/Civ13/Verifier.php +++ b/src/Civ13/Verifier.php @@ -47,6 +47,7 @@ class Verifier public CollectionInterface $pending; public CollectionInterface $provisional; // Allow provisional registration if the website is down, then try to verify when it comes back up public bool $ready = false; + public InGameVerification $inGame; // single-use codes for verifying from inside the game // Generated by the bot /** @@ -67,6 +68,7 @@ public function __construct(Civ13 &$civ13, array $options = []) throw new \InvalidArgumentException('Unexpected read-only verification source'); } $this->pending = new Collection([], 'discord'); + $this->inGame = new InGameVerification(); if ($this->readOnly) { $this->hosted = new HostedVerificationSnapshot(); $this->provisional = new Collection([], 'ss13'); @@ -400,6 +402,109 @@ public function process(string $ckey, string $discord_id, ?Member $m = null): st if (! $ckey = Civ13::sanitizeInput($ckey)) { return 'Invalid ckey!'; } + if (($blocked = $this->eligibility($ckey, $discord_id, $m)) !== null) { + return $blocked; + } + if (! $this->pending->get('discord', $discord_id)) { + // Check if the player's account has played on the server before + $file_contents = array_reduce($this->civ13->enabled_gameservers, function ($carry, $gameserver) { + if (! file_exists($fp = $gameserver->basedir.Civ13::playerlogs) || ! $fc = @file_get_contents($fp)) { + $this->logger->warning("Unable to open `$fp`"); + + return $carry; + } + + return $carry.$fc; + }, ''); + if (! array_reduce(explode('|', $file_contents), fn ($carry, $line) => $carry || explode(';', trim($line))[0] === $ckey, false)) { + return "Byond account `$ckey` has never been seen on the server before! You'll need to join one of our servers at least once before verifying."; + } + if (($blocked = $this->ageCheck($ckey, $discord_id)) !== null) { + return $blocked; + } + + return 'Login to your profile at '.Byond::PROFILE.' and enter this token as your description: `'.$this->generateToken($ckey, $discord_id).PHP_EOL.'`Use the command again once this process has been completed.'.PHP_EOL + .'Or skip the profile step: run `/approveme` without a ckey for a code, then use **Verify Discord** in the game\'s OOC tab.'; + } + + return $this->new($discord_id)['error']; // ['success'] will be false if verification cannot proceed or true if succeeded but is only needed if debugging, ['error'] will contain the error/success message and will be messaged to the user + } + /** + * Verification from inside the game ({@see InGameVerification}). The game has already proven + * the ckey and the single-use code proved the Discord account, so the BYOND profile token and + * the "seen on our servers" check are skipped; bans, age and alt review still apply. + * + * @return array{success: bool, error: string} + */ + public function processInGame(string $ckey, string $discord_id): array + { + if (isset($this->readOnly) && $this->readOnly) { return ['success' => false, 'error' => self::READ_ONLY_MESSAGE]; } + if (! $ckey = Civ13::sanitizeInput($ckey)) { + return ['success' => false, 'error' => 'Invalid ckey!']; + } + $guild = $this->civ13->discord->guilds->get('id', $this->civ13->civ13_guild_id); + $m = $guild ? $guild->members->get('id', $discord_id) : null; + if (! $m) { + return ['success' => false, 'error' => 'That Discord account is not in the Civ13 Discord server. Join it, then run /approveme again for a new code.']; + } + if (($blocked = $this->eligibility($ckey, $discord_id, $m)) !== null) { + return ['success' => false, 'error' => $blocked]; + } + if (($blocked = $this->ageCheck($ckey, $discord_id)) !== null) { + return ['success' => false, 'error' => $blocked]; + } + if (($blocked = $this->reviewCheck($ckey)) !== null) { + return ['success' => false, 'error' => $blocked]; + } + $this->pending->offsetUnset($discord_id); // a half-finished profile-token attempt is superseded + + return $this->verify($ckey, $discord_id); + } + /** + * Redeems a code typed into the game by `$ckey`. The answer is shown to the player in game, + * so it carries no Discord mention markup. + * + * @return array{ok: bool, message: string} + */ + public function redeemInGame(string $ckey, mixed $code): array + { + if (isset($this->readOnly) && $this->readOnly) { return ['ok' => false, 'message' => 'This server relays verification to the main Civ13 bot, which could not be reached. Try again later.']; } + if (! $ckey = Civ13::sanitizeInput($ckey)) { + return ['ok' => false, 'message' => 'Guest accounts cannot be verified. Sign in to BYOND first.']; + } + if ($this->inGame->locked($ckey)) { + return ['ok' => false, 'message' => 'Too many wrong codes. Wait ten minutes, then run /approveme in Discord for a new code.']; + } + if (! $discord_id = $this->inGame->consume($ckey, is_string($code) ? $code : '')) { // malformed input counts as a wrong guess too + return ['ok' => false, 'message' => 'That code is wrong or has expired. Run /approveme in Discord (leave the ckey out) for a new one.']; + } + $result = $this->processInGame($ckey, $discord_id); + if ($result['success']) { + $name = $this->discordName($discord_id); + + return ['ok' => true, 'message' => "Verified! $ckey is now linked to $name on Discord. Your Discord roles update now; the game picks the link up within a few minutes."]; + } + + return ['ok' => false, 'message' => self::plainMessage($result['error'])]; + } + /** The Discord display name players recognise, for the in-game confirmation. */ + protected function discordName(string $discord_id): string + { + $user = $this->discord->users->get('id', $discord_id); + + return $user ? (string) ($user->global_name ?? $user->username) : 'your Discord account'; + } + /** Discord markup out of a verifier message, for showing in game. */ + public static function plainMessage(string $message): string + { + $message = preg_replace('/<@[&!]?[0-9]+>/', 'staff', $message) ?? ''; + $message = str_replace(['`', '**', PHP_EOL], ['', '', ' '], $message); + + return mb_substr(trim($message), 0, 400); + } + /** Bans, investigations and existing links that stop any verification. Null when none applies. */ + private function eligibility(string $ckey, string $discord_id, ?Member $m = null): ?string + { if (isset($this->civ13->channel_ids['ban_appeals'])) { $ban_appeals = $this->civ13->discord->getChannel($this->civ13->channel_ids['ban_appeals']); } @@ -439,44 +544,51 @@ public function process(string $ckey, string $discord_id, ?Member $m = null): st if ($this->get('ss13', $ckey)) { // Verified records are keyed `ss13`, never `ckey` return "`$ckey` is already verified! If this is your account, contact <@{$this->civ13->technician_id}> to delete this entry."; } - if (! $this->pending->get('discord', $discord_id)) { - // Check if the player's account has played on the server before - $file_contents = array_reduce($this->civ13->enabled_gameservers, function ($carry, $gameserver) { - if (! file_exists($fp = $gameserver->basedir.Civ13::playerlogs) || ! $fc = @file_get_contents($fp)) { - $this->logger->warning("Unable to open `$fp`"); - return $carry; - } - - return $carry.$fc; - }, ''); - if (! array_reduce(explode('|', $file_contents), fn ($carry, $line) => $carry || explode(';', trim($line))[0] === $ckey, false)) { - return "Byond account `$ckey` has never been seen on the server before! You'll need to join one of our servers at least once before verifying."; + return null; + } + /** BYOND account age requirement (bans too-new accounts, as the profile route always has). Null when old enough. */ + private function ageCheck(string $ckey, string $discord_id): ?string + { + if (isset($this->civ13->channel_ids['ban_appeals'])) { + $ban_appeals = $this->civ13->discord->getChannel($this->civ13->channel_ids['ban_appeals']); + } + // Check if the player's account is old enough + if (! $age = $this->civ13->getByondAge($ckey)) { + return "Byond account `$ckey` either does not exist or the website can't be reached! Please contact the CTO for assistance."; + } + if (! isset($this->civ13->permitted[$ckey]) && ! $this->civ13->checkByondAge($age)) { + $arr = ['ckey' => $ckey, 'duration' => '999 years', 'reason' => $reason = "Byond account `$ckey` does not meet the requirements to be approved. ($age)"]; + $this->civ13->ban($arr, null, null, true); + if (isset($ban_appeals)) { + $this->civ13->then( + $this->civ13->startForumThread($ban_appeals, "`$ckey`'s Ban Appeal", "<@$discord_id>, your Byond account `$ckey` is currently permanently banned for being too new to be automatically approved. Please follow the posting guidelines and appeal your ban here.") + ->then(fn (Thread $thread): ?PromiseInterface => ($user = $this->discord->users->get('id', $discord_id)) ? $thread->addMember($user) : null) + ); } - // Check if the player's account is old enough - if (! $age = $this->civ13->getByondAge($ckey)) { - return "Byond account `$ckey` either does not exist or the website can't be reached! Please contact the CTO for assistance."; + if (isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->civ13->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { + $this->civ13->sendMessage($channel, "<@&{$this->civ13->role_ids['Ambassador']}>, Byond account `$ckey` was too new to complete the automatic verification process! Please investigate using the `ckeyinfo` command and manually approve if they should be allowed to bypass the requirements."); } - if (! isset($this->civ13->permitted[$ckey]) && ! $this->civ13->checkByondAge($age)) { - $arr = ['ckey' => $ckey, 'duration' => '999 years', 'reason' => $reason = "Byond account `$ckey` does not meet the requirements to be approved. ($age)"]; - $this->civ13->ban($arr, null, null, true); - if (isset($ban_appeals)) { - $this->civ13->then( - $this->civ13->startForumThread($ban_appeals, "`$ckey`'s Ban Appeal", "<@$discord_id>, your Byond account `$ckey` is currently permanently banned for being too new to be automatically approved. Please follow the posting guidelines and appeal your ban here.") - ->then(fn (Thread $thread): ?PromiseInterface => ($user = $this->discord->users->get('id', $discord_id)) ? $thread->addMember($user) : null) - ); - } - if (isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->civ13->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - $this->civ13->sendMessage($channel, "<@&{$this->civ13->role_ids['Ambassador']}>, Byond account `$ckey` was too new to complete the automatic verification process! Please investigate using the `ckeyinfo` command and manually approve if they should be allowed to bypass the requirements."); - } - return $reason; + return $reason; + } + + return null; + } + /** Alt-ban or several Discord accounts on one ckey: staff review first. Null when clear. */ + private function reviewCheck(string $ckey): ?string + { + $ckeyinfo = $this->civ13->ckeyinfo($ckey); + if (($ckeyinfo['altbanned'] || count($ckeyinfo['discords']) > 1) && ! isset($this->civ13->permitted[$ckey])) { // TODO: Add check for permaban + // TODO: add to pending list? + if (isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->civ13->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { + $this->civ13->sendMessage($channel, "<@&{$this->civ13->role_ids['Ambassador']}>, {$ckey} has been flagged as needing additional review. Please `permit` the ckey after reviewing if they should be allowed to complete the verification process."); } - return 'Login to your profile at '.Byond::PROFILE.' and enter this token as your description: `'.$this->generateToken($ckey, $discord_id).PHP_EOL.'`Use the command again once this process has been completed.'; + return "Your ckey `{$ckey}` has been flagged as needing additional review. Please wait for a staff member to assist you."; } - return $this->new($discord_id)['error']; // ['success'] will be false if verification cannot proceed or true if succeeded but is only needed if debugging, ['error'] will contain the error/success message and will be messaged to the user + return null; } /** * This function is called when a user still needs to set their token in their BYOND description and call the approveme prompt. @@ -496,14 +608,8 @@ public function new(string $discord_id): array // ['success' => bool, 'error' => if (! $this->checkToken($discord_id)) { return ['success' => false, 'error' => "You have not set your description yet! It needs to be set to `{$item['token']}`"]; } - $ckeyinfo = $this->civ13->ckeyinfo($item['ss13']); - if (($ckeyinfo['altbanned'] || count($ckeyinfo['discords']) > 1) && ! isset($this->civ13->permitted[$item['ss13']])) { // TODO: Add check for permaban - // TODO: add to pending list? - if (isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->civ13->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - $this->civ13->sendMessage($channel, "<@&{$this->civ13->role_ids['Ambassador']}>, {$item['ss13']} has been flagged as needing additional review. Please `permit` the ckey after reviewing if they should be allowed to complete the verification process."); - } - - return ['success' => false, 'error' => "Your ckey `{$item['ss13']}` has been flagged as needing additional review. Please wait for a staff member to assist you."]; + if (($blocked = $this->reviewCheck($item['ss13'])) !== null) { + return ['success' => false, 'error' => $blocked]; } return $this->verify($item['ss13'], $discord_id); diff --git a/tests/local/ingame-verification.php b/tests/local/ingame-verification.php new file mode 100644 index 00000000..b168eaf7 --- /dev/null +++ b/tests/local/ingame-verification.php @@ -0,0 +1,126 @@ +addPsr4('Civ13\\', __DIR__.'/../../src/Civ13', true); + +use Civ13\Civ13; +use Civ13\HttpServiceManager; +use Civ13\InGameVerification; +use Civ13\Verifier; +use Monolog\Handler\NullHandler; +use Monolog\Logger; +use React\Http\Message\ServerRequest; + +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 inert(string $class): object { return (new ReflectionClass($class))->newInstanceWithoutConstructor(); } +function setProp(object $object, string $name, mixed $value, ?string $class = null): void { $p = new ReflectionProperty($class ?? $object, $name); $p->setValue($object, $value); } + +const ALICE = '123456789012345678'; +const BOB = '223456789012345678'; + +// Codes: format, normalisation, single use, replacement, expiry, lockout. +$now = 1000; +$codes = new InGameVerification(static function () use (&$now): int { return $now; }); +$code = $codes->issue(ALICE); +check(preg_match('/^[A-HJ-NP-Z2-9]{4}-[A-HJ-NP-Z2-9]{4}$/D', $code) === 1, 'code shape '.$code); +check(InGameVerification::normalize(strtolower(str_replace('-', ' ', $code))) === str_replace('-', '', $code), 'players may type spaces and lower case'); +check(InGameVerification::normalize('ABCD-EFG0') === null && InGameVerification::normalize('short') === null && InGameVerification::normalize(['x']) === null, 'bad codes rejected'); +check($codes->consume('alice', $code) === ALICE, 'code redeems to its Discord user'); +check($codes->consume('alice', $code) === null, 'single use'); +$first = $codes->issue(ALICE); +$second = $codes->issue(ALICE); +check($codes->count() === 1 && $codes->consume('alice', $first) === null && $codes->consume('alice', $second) === ALICE, 'a new code replaces the older one'); +$late = $codes->issue(BOB); +$now += InGameVerification::CODE_LIFETIME; +check($codes->consume('bob', $late) === null && $codes->count() === 0, 'codes expire'); +$codes = new InGameVerification(static function () use (&$now): int { return $now; }); +$good = $codes->issue(BOB); +for ($i = 0; $i < InGameVerification::MAX_FAILURES; $i++) { $codes->consume('mallory', 'ZZZZ-ZZZZ'); } +check($codes->locked('mallory') && $codes->consume('mallory', $good) === null, 'wrong guesses lock the ckey out'); +check(! $codes->locked('bob') && $codes->consume('bob', $good) === BOB, 'a lockout does not burn other players\' codes'); +$now += InGameVerification::FAILURE_WINDOW + 1; +check(! $codes->locked('mallory'), 'lockout lifts after the window'); +try { $codes->issue('not-an-id'); check(false, 'non-Discord id accepted'); } catch (InvalidArgumentException) { check(true, ''); } +check(str_contains(InGameVerification::codeMessage('ABCD-EFGH'), 'Verify Discord') && str_contains(InGameVerification::codeMessage('ABCD-EFGH'), '`ABCD-EFGH`'), 'code message explains the verb'); + +// Relay destination only beside the hosted verified list. +check(InGameVerification::relayUrl('http://civ13.com:55555/verified') === 'http://civ13.com:55555/verified/ingame', 'relay url beside hosted list'); +check(InGameVerification::relayUrl('https://civ13.com/verified') === 'https://civ13.com/verified/ingame', 'https relay url'); +check(InGameVerification::relayUrl('http://evil.example/verified') === null && InGameVerification::relayUrl('') === null, 'no relay elsewhere'); + +// Verifier: redeeming in game. +final class FakeVerifier extends Verifier +{ + public array $processed = []; + public array $result = ['success' => true, 'error' => '']; + public function processInGame(string $ckey, string $discord_id): array { $this->processed[] = [$ckey, $discord_id]; return $this->result; } + protected function discordName(string $discord_id): string { return 'Alice'; } +} +function verifier(bool $readOnly): FakeVerifier +{ + $v = inert(FakeVerifier::class); + setProp($v, 'readOnly', $readOnly, Verifier::class); + setProp($v, 'verify_url', $readOnly ? 'http://civ13.com:55555/verified' : 'http://127.0.0.1:8080/verified/', Verifier::class); + $v->inGame = new InGameVerification(); + return $v; +} +$v = verifier(false); +$code = $v->inGame->issue(ALICE); +$ok = $v->redeemInGame('alice', $code); +check($ok['ok'] === true && str_contains($ok['message'], 'alice is now linked to Alice'), 'success message names the Discord account'); +check($v->processed === [['alice', ALICE]], 'ckey and the code owner reach the verifier'); +check($v->redeemInGame('alice', $code)['ok'] === false, 'used code fails'); +$v->result = ['success' => false, 'error' => "`alice` is already verified! If this is your account, contact <@123456789012345678> to delete this entry."]; +$code = $v->inGame->issue(BOB); +$fail = $v->redeemInGame('alice', $code); +check($fail['ok'] === false && ! str_contains($fail['message'], '<@') && ! str_contains($fail['message'], '`') && str_contains($fail['message'], 'contact staff'), 'verifier errors are shown without Discord markup: '.$fail['message']); +check(verifier(true)->redeemInGame('alice', 'ABCD-EFGH')['ok'] === false, 'read-only verifier never registers'); +check(Verifier::plainMessage("a\n**b** <@&1234567890>") === 'a b staff', 'plain message'); + +// HTTP: request validation, relay authentication. +check(HttpServiceManager::inGameVerifyRequest(['ckey' => 'alice', 'code' => 'ABCD-EFGH']) === ['ckey' => 'alice', 'code' => 'ABCD-EFGH'], 'valid request'); +foreach ([['ckey' => 'Alice', 'code' => 'x'], ['ckey' => 'alice'], ['ckey' => 'alice', 'code' => ''], ['ckey' => 'alice', 'code' => str_repeat('A', 33)], ['ckey' => 'a b', 'code' => 'x'], ['ckey' => ['alice'], 'code' => 'x']] as $bad) { + check(HttpServiceManager::inGameVerifyRequest($bad) === null, 'invalid request rejected: '.json_encode($bad)); +} +function manager(Verifier $verifier, string $relayKey): HttpServiceManager +{ + $civ13 = inert(Civ13::class); + $civ13->options = ['http_key' => 'webhook-key', 'ingame_verify_key' => $relayKey]; + $civ13->verifier = $verifier; + $manager = inert(HttpServiceManager::class); + setProp($manager, 'civ13', $civ13); + $manager->logger = new Logger('test', [new NullHandler()]); + return $manager; +} +function relayRequest(string $key, string $body, string $method = 'POST', ?int $time = null): ServerRequest +{ + $time = (string) ($time ?? time()); + return new ServerRequest($method, 'http://civ13.com:55555/verified/ingame', $key === '' ? [] : ['X-Ingame-Verify-Time' => $time, 'X-Ingame-Verify-Signature' => HttpServiceManager::inGameRelaySignature($key, $time, $body)], $body); +} +$v = verifier(false); +$code = $v->inGame->issue(ALICE); +$m = manager($v, 'relay-secret'); +$body = json_encode(['ckey' => 'alice', 'code' => $code]); +check($m->handleInGameVerifyRelay(relayRequest('', $body))->getStatusCode() === 403, 'relay needs the key'); +check($m->handleInGameVerifyRelay(relayRequest('wrong', $body))->getStatusCode() === 403, 'relay rejects a wrong key'); +check($m->handleInGameVerifyRelay(relayRequest('relay-secret', $body, 'POST', time() - 120))->getStatusCode() === 403, 'stale signatures are refused'); +$tampered = relayRequest('relay-secret', $body); +check($m->handleInGameVerifyRelay(new ServerRequest('POST', 'http://civ13.com:55555/verified/ingame', ['X-Ingame-Verify-Time' => $tampered->getHeaderLine('X-Ingame-Verify-Time'), 'X-Ingame-Verify-Signature' => $tampered->getHeaderLine('X-Ingame-Verify-Signature')], json_encode(['ckey' => 'admin', 'code' => $code])))->getStatusCode() === 403, 'a signature does not cover another ckey'); +check(! str_contains(json_encode($tampered->getHeaders()), 'relay-secret'), 'the secret itself is never sent'); +check(manager($v, '')->handleInGameVerifyRelay(relayRequest('', $body))->getStatusCode() === 403, 'relay off without INGAME_VERIFY_TOKEN'); +check(manager(verifier(true), 'relay-secret')->handleInGameVerifyRelay(relayRequest('relay-secret', $body))->getStatusCode() === 403, 'a read-only bot never accepts relays'); +check($m->handleInGameVerifyRelay(relayRequest('relay-secret', $body, 'GET'))->getStatusCode() === 405, 'relay is POST only'); +check($m->handleInGameVerifyRelay(relayRequest('relay-secret', '{"ckey":"alice"}'))->getStatusCode() === 400, 'relay validates the body'); +$response = $m->handleInGameVerifyRelay(relayRequest('relay-secret', $body)); +$answer = json_decode((string) $response->getBody(), true); +check($response->getStatusCode() === 200 && $answer['ok'] === true && $v->processed === [['alice', ALICE]], 'relay redeems on the primary bot'); + +// A desktop bot without a relay key answers the game without any network call. +$relayed = null; +manager(verifier(true), '')->relayInGameVerification('alice', 'ABCD-EFGH')->then(static function (array $r) use (&$relayed): void { $relayed = $r; }); +check(is_array($relayed) && $relayed['ok'] === false && str_contains($relayed['message'], 'not set up'), 'unconfigured relay answers plainly'); + +echo "ingame-verification: $checks checks passed\n"; diff --git a/tests/windows/bootstrap.php b/tests/windows/bootstrap.php index fe07f8e3..83f8e32e 100644 --- a/tests/windows/bootstrap.php +++ b/tests/windows/bootstrap.php @@ -47,7 +47,7 @@ function check(bool $ok): void { if (!$ok) { throw new RuntimeException('Bootstr file_put_contents($root.'/profile.json',json_encode($profile,JSON_THROW_ON_ERROR)); putenv('CIVILIZATIONBOT_PROFILE='.$root.'/profile.json'); // This fresh CLI uses only a synthetic environment; no real credential file is read. - putenv('TOKEN');putenv('CIV_TOKEN');putenv('WEBAPI_TOKEN'); + putenv('TOKEN');putenv('CIV_TOKEN');putenv('WEBAPI_TOKEN');putenv('INGAME_VERIFY_TOKEN'); $source=file_get_contents(__DIR__.'/../../bot.php'); if($negative){ $source=str_replace('if ($portable === null) { // Production server defaults only.','if (true) { // Original unconditional production defaults.',$source,$count); From 28e670787436d8d3f6ffe095fa765c07562c0ea4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 13:16:11 +0000 Subject: [PATCH 2/4] Point at the game verb's file Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016WTP2R6s5HsPDzf2CSzzGM --- src/Civ13/HttpServiceManager.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Civ13/HttpServiceManager.php b/src/Civ13/HttpServiceManager.php index 8df7b224..ba640166 100644 --- a/src/Civ13/HttpServiceManager.php +++ b/src/Civ13/HttpServiceManager.php @@ -351,7 +351,7 @@ public function handleShutdownNoticeWebhook(ServerRequestInterface $request, Gam } /** - * In-game verification (Civ13 code/modules/accounts/discord_verify.dm): the game sends the + * In-game verification (Civ13 code/modules/client/discord_verify.dm): the game sends the * player's ckey and the code they typed. The primary bot redeems it; a desktop bot with a * read-only verifier relays it to the primary bot. Once authenticated the answer is always * 200 JSON {ok, message}, which the game shows to the player. From 4889bd6c9c86c0c6558462acc8fced5ee787949e Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 13:32:22 +0000 Subject: [PATCH 3/4] Never let the source check block booting; add repair start and bot.php warn instead of refusing when the default-branch check fails. update keeps any local composer.lock (stashing it only when the update changes composer.lock itself). New control.php repair: stash local edits, keep local commits on a backup branch, and fast-forward a clean main, for the launcher's Repair and update button. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016WTP2R6s5HsPDzf2CSzzGM --- bot.php | 5 +- docs/windows-test1714.md | 10 +++- scripts/windows/control.php | 20 ++++++- src/Civ13/DefaultBranchGuard.php | 98 ++++++++++++++++++++++++++++--- tests/windows/default-branch.php | 43 ++++++++++---- tests/windows/lock-path-guard.php | 50 ++++++++-------- 6 files changed, 176 insertions(+), 50 deletions(-) diff --git a/bot.php b/bot.php index dc94a53d..0e93fe9e 100644 --- a/bot.php +++ b/bot.php @@ -111,7 +111,10 @@ function loadEnv(string $filePath, bool $explicit = false): array $portable = CIVILIZATIONBOT_PACKAGED_PROFILE; PortableProfile::assertRoot($portable, CIVILIZATIONBOT_PACKAGED_SOURCE_ROOT); } else { - \Civ13\DefaultBranchGuard::verify(__DIR__); // Before profile credentials, Composer, sockets or Discord. + // Before profile credentials, Composer, sockets or Discord. A failed source check is a warning, + // never a boot blocker; the launcher's Update / Repair and update fix what it reports. + try { \Civ13\DefaultBranchGuard::verify(__DIR__); } + catch (\RuntimeException $sourceCheck) { fwrite(STDERR, 'Source check warning (starting anyway): '.$sourceCheck->getMessage().PHP_EOL); } $portable = PortableProfile::load($portablePath); PortableProfile::assertRoot($portable, __DIR__); } diff --git a/docs/windows-test1714.md b/docs/windows-test1714.md index 8d2fffc5..664cbef8 100644 --- a/docs/windows-test1714.md +++ b/docs/windows-test1714.md @@ -34,8 +34,12 @@ From PowerShell, with explicit executable and profile paths: ```powershell C:/php/php.exe scripts/windows/control.php check D:/Civilizationbot-local/profile.json -# While stopped, explicitly fetch and fast-forward clean default-branch source: +# While stopped, explicitly fetch and fast-forward default-branch source (a local +# composer.lock is kept; if the update changes composer.lock it is stashed instead): C:/php/php.exe scripts/windows/control.php update D:/Civilizationbot-local/profile.json +# While stopped, whatever update refused for: stash local edits, keep local commits on a +# civilizationbot-backup-* branch, and fast-forward a clean main (launcher "Repair and update"): +C:/php/php.exe scripts/windows/control.php repair D:/Civilizationbot-local/profile.json # Only after the separate activation gate: C:/php/php.exe scripts/windows/control.php start D:/Civilizationbot-local/profile.json # From another terminal, requests graceful shutdown of this profile only: @@ -45,6 +49,10 @@ C:/php/php.exe scripts/windows/control.php status D:/Civilizationbot-local/profi C:/php/php.exe scripts/windows/control.php check-update D:/Civilizationbot-local/profile.json ``` +start never refuses because of the source check: it prints "Source check warning +(starting anyway): ..." and boots the current checkout, so a guard problem can always +be fixed from the launcher with Update or Repair and update. + status reports whether the state lock is held (running), any pending stop or reload marker, and the stdout/stderr log paths. check-update fetches origin/main like start does and reports current, available, behind, can_update and reason; diff --git a/scripts/windows/control.php b/scripts/windows/control.php index 55ec6d94..6f05bac0 100644 --- a/scripts/windows/control.php +++ b/scripts/windows/control.php @@ -7,7 +7,7 @@ use Civ13\PortableProcess; try { $json=in_array($argv[1] ?? '',['status','check-update'],true); - if (count($argv)!==3 || !in_array($argv[1],['check','start','stop','update','status','check-update'],true)) { throw new RuntimeException('Usage: php control.php check|start|stop|update|status|check-update ABSOLUTE_PROFILE'); } + if (count($argv)!==3 || !in_array($argv[1],['check','start','stop','update','repair','status','check-update'],true)) { throw new RuntimeException('Usage: php control.php check|start|stop|update|repair|status|check-update ABSOLUTE_PROFILE'); } $profile=PortableProfile::load($argv[2]); PortableProfile::assertRoot($profile, dirname(__DIR__, 2)); if ($argv[1]==='stop') { PortableProcess::requestStop($profile['state_dir']); exit(0); } @@ -21,13 +21,27 @@ $errors=PortableProfile::preflight($profile,extension_loaded(...)); if ($errors!==[]) { throw new RuntimeException(implode('; ',$errors)); } if ($argv[1]==='check') { echo "Preflight passed; not started\n"; exit(0); } + // repair: whatever the source check refused for, set local work aside (stash / backup branch) and + // fast-forward a clean main to origin/main. The launcher's "Repair and update" button. + if ($argv[1]==='repair') { + $lock=PortableProcess::lock($profile['state_dir']); + try { echo json_encode(\Civ13\DefaultBranchGuard::repair($profile['root']),JSON_THROW_ON_ERROR|JSON_UNESCAPED_SLASHES)."\n"; } + finally { fclose($lock); } + exit(0); + } if ($argv[1]==='update') { $lock=PortableProcess::lock($profile['state_dir']); try { echo json_encode(\Civ13\DefaultBranchGuard::verify($profile['root'],true),JSON_THROW_ON_ERROR)."\n"; } finally { fclose($lock); } exit(0); } - \Civ13\DefaultBranchGuard::verify($profile['root']); + // A source check never keeps the bot from booting (Val, 2026-11-13): it warns and starts the + // current checkout. Update or "Repair and update" in the launcher fixes what it reports. + $sourceWarning=static function(string $root): void { + try { \Civ13\DefaultBranchGuard::verify($root); } + catch (RuntimeException $error) { fwrite(STDERR,'Source check warning (starting anyway): '.$error->getMessage().PHP_EOL); } + }; + $sourceWarning($profile['root']); if (is_file($profile['state_dir'].'/stop.request')) { throw new RuntimeException('Unresolved stop request; inspect previous instance before starting'); } // Clear a stale reload request only when no instance holds the lock; a live // instance's pending reload must survive a second start attempt. @@ -54,7 +68,7 @@ PortableProfile::assertRoot($profile, dirname(__DIR__, 2)); $errors=PortableProfile::preflight($profile,extension_loaded(...)); if ($errors!==[]) { throw new RuntimeException('Reload refused: '.implode('; ',$errors)); } - \Civ13\DefaultBranchGuard::verify($profile['root']); + $sourceWarning($profile['root']); } } while ($reload); exit($exit); diff --git a/src/Civ13/DefaultBranchGuard.php b/src/Civ13/DefaultBranchGuard.php index 8cbc2dfe..e1ce3b80 100644 --- a/src/Civ13/DefaultBranchGuard.php +++ b/src/Civ13/DefaultBranchGuard.php @@ -2,7 +2,11 @@ declare(strict_types=1); namespace Civ13; -/** Fail-closed portable bot source policy. No reset, checkout, stash, force or credential loading. */ +/** + * Portable bot source policy. No reset, checkout, force or credential loading. The only stash is a + * local composer.lock set aside when an update itself changes composer.lock (kept, never dropped). + * control.php start treats a refusal as a warning: these checks must never keep the bot from booting. + */ final class DefaultBranchGuard { public const ORIGIN = 'https://github.com/Valgorithms/Civilizationbot.git'; @@ -18,11 +22,11 @@ public static function verify(string $repository, bool $update = false, string $ $require($command(['rev-parse','--abbrev-ref','--symbolic-full-name','@{upstream}']) === 'origin/main', 'upstream origin/main required'); $require($command(['symbolic-ref','--quiet','refs/remotes/origin/HEAD']) === 'refs/remotes/origin/main', 'local origin default main required'); $sourceStatus = $command(['status','--porcelain=v1','--untracked-files=all']); - // composer.lock is not loaded at runtime. A local dependency lock may be - // retained for start on a current main. Update also keeps it when the - // only unstaged difference is packages installed from path repositories. - $lockOnly = in_array($sourceStatus, ['M composer.lock','M composer.lock','MM composer.lock'], true); - $localLockEdit = $lockOnly && (!$update || self::pathOnlyLockEdit($git, $root)); + // composer.lock is not loaded at runtime (vendor/ is), so a local dependency lock + // never blocks start or update. If the update changes composer.lock too, the local + // lock is stashed first and the upstream one kept (composer install is due anyway). + $lockOnly = self::lockOnlyStatus($sourceStatus); + $localLockEdit = $lockOnly; $require($sourceStatus === '' || $localLockEdit, 'local source edits retained'); $lockState = $localLockEdit ? self::lockState($git, $root) : null; $require($command(['remote','get-url','--all','origin']) === $origin, 'unexpected origin retained'); @@ -49,6 +53,16 @@ public static function verify(string $repository, bool $update = false, string $ $require($update, 'main behind; explicit safe update required'); $require($command(['symbolic-ref','--quiet','--short','HEAD']) === 'main' && $command(['status','--porcelain=v1','--untracked-files=all']) === $sourceStatus && (!$localLockEdit || self::lockState($git, $root) === $lockState), 'source changed during verification'); + if ($localLockEdit) { + self::command($git,$root,['diff','--quiet',$before,$target,'--','composer.lock'],[0,1],$lockChanged); + if ($lockChanged === 1) { + $command(['stash','push','-m','civilizationbot update: local composer.lock (upstream changed it)','--','composer.lock']); + $stashedLock = true; + $sourceStatus = $command(['status','--porcelain=v1','--untracked-files=all']); + $require($sourceStatus === '', 'local composer.lock could not be set aside'); + $localLockEdit = false; + } + } $command(['merge','--ff-only',$target]); } $require($command(['symbolic-ref','--quiet','--short','HEAD']) === 'main' @@ -57,7 +71,8 @@ public static function verify(string $repository, bool $update = false, string $ && (!$localLockEdit || self::lockState($git, $root) === $lockState), 'final source identity changed'); return ['branch'=>'main','upstream'=>'origin/main','commit'=>$target,'before'=>$before, - 'fresh_remote_verified'=>true,'local_dependency_lock_edit'=>$localLockEdit]; + 'fresh_remote_verified'=>true,'local_dependency_lock_edit'=>$localLockEdit, + 'local_dependency_lock_stashed'=>$stashedLock ?? false]; } /** @@ -81,13 +96,80 @@ public static function check(string $repository, string $git = 'git', string $or if ($reason === '') { $reason = 'already up to date'; } elseif ($behindOnly) { $dirty = self::command($git, $root, ['status','--porcelain=v1','--untracked-files=all']); - $canUpdate = $dirty === '' || ($dirty === 'M composer.lock' && self::pathOnlyLockEdit($git, $root)); + $canUpdate = $dirty === '' || self::lockOnlyStatus($dirty); $reason = $canUpdate ? '' : 'local edits retained (update needs a clean checkout): '.str_replace("\n", ', ', $dirty); } return ['component'=>'bot','current'=>$current,'available'=>$available,'behind'=>$behind, 'can_update'=>$canUpdate,'reason'=>$reason,'fresh'=>$fresh]; } + /** + * Launcher "Repair and update": brings any checkout back to a clean main that tracks and equals + * origin/main, whatever the guard refused for, and loses nothing. Local edits and untracked files + * go to a labelled stash, local commits not on origin/main stay on a backup branch, and a local + * composer.lock is put back when upstream did not change it. Only call with the bot stopped. + * + * @return array what was set aside, then verify()'s answer after the repair + */ + public static function repair(string $repository, string $git = 'git', string $origin = self::ORIGIN): array + { + $root = realpath($repository); + if ($root === false || !is_dir($root.'/.git') && !is_file($root.'/.git')) { throw new \RuntimeException('Repair refused: repository unavailable'); } + $command = static fn (array $args, array $allowed = [0], ?int &$code = null): string => self::command($git, $root, $args, $allowed, $code); + $stamp = gmdate('Ymd-His'); + $done = ['stash' => null, 'backup_branch' => null, 'origin_was' => null, 'restored_composer_lock' => false]; + // A merge, rebase or cherry-pick left half way stops every other step. + foreach (['merge', 'rebase', 'cherry-pick', 'am'] as $operation) { + $command([$operation, '--abort'], [0, 1, 128]); + } + $currentOrigin = $command(['remote', 'get-url', 'origin'], [0, 2, 128]); + if ($currentOrigin !== $origin) { + $done['origin_was'] = $currentOrigin === '' ? null : $currentOrigin; + $command($currentOrigin === '' ? ['remote', 'add', 'origin', $origin] : ['remote', 'set-url', 'origin', $origin]); + } + $command(['config', 'core.sparseCheckout', 'false']); + foreach (explode("\n", $command(['ls-files', '-v'])) as $line) { // assume-unchanged (lower case) or skip-worktree (S) + if (preg_match('/^([a-z]|S) (.+)$/D', $line, $match)) { + if ($match[1] !== 'S') { $command(['update-index', '--no-assume-unchanged', '--', $match[2]]); } + if (strtoupper($match[1]) === 'S') { $command(['update-index', '--no-skip-worktree', '--', $match[2]]); } + } + } + $command(['fetch', '--no-tags', 'origin', '+refs/heads/main:refs/remotes/origin/main']); + $target = $command(['rev-parse', '--verify', 'refs/remotes/origin/main^{commit}']); + $oldHead = $command(['rev-parse', '--verify', 'HEAD^{commit}'], [0, 128]); + $lockBytes = is_file($root.'/composer.lock') ? file_get_contents($root.'/composer.lock') : false; + $oldLock = $oldHead !== '' ? $command(['rev-parse', '--verify', $oldHead.':composer.lock'], [0, 128]) : ''; + if ($command(['status', '--porcelain=v1', '--untracked-files=all']) !== '') { + $command(['stash', 'push', '--include-untracked', '-m', 'civilizationbot repair '.$stamp]); + $done['stash'] = 'civilizationbot repair '.$stamp; + } + // Commits that exist only locally (on main or a detached/other HEAD) stay reachable. + foreach (array_unique(array_filter([$oldHead, $command(['rev-parse', '--verify', 'refs/heads/main^{commit}'], [0, 128])])) as $tip) { + $command(['merge-base', '--is-ancestor', $tip, $target], [0, 1], $code); + if ($code === 1) { + $name = 'civilizationbot-backup-'.$stamp.($done['backup_branch'] ? '-2' : ''); + $command(['branch', $name, $tip]); + $done['backup_branch'] = $done['backup_branch'] ? $done['backup_branch'].', '.$name : $name; + } + } + $command(['checkout', '-f', '-B', 'main', $target]); + $command(['branch', '--set-upstream-to=origin/main', 'main']); + $command(['symbolic-ref', 'refs/remotes/origin/HEAD', 'refs/remotes/origin/main']); + $newLock = $command(['rev-parse', '--verify', $target.':composer.lock'], [0, 128]); + if (is_string($lockBytes) && $oldLock !== '' && $oldLock === $newLock && hash('sha1', 'blob '.strlen($lockBytes)."\0".$lockBytes) !== $newLock) { + file_put_contents($root.'/composer.lock', $lockBytes); // a local dependency lock (e.g. a path override) survives + $done['restored_composer_lock'] = true; + } + + return $done + self::verify($root, true, $git, $origin); + } + + /** Git porcelain (trimmed) showing composer.lock as the only change, staged or not. */ + public static function lockOnlyStatus(string $status): bool + { + return in_array($status, ['M composer.lock','M composer.lock','MM composer.lock'], true); + } + /** * True when the unstaged composer.lock differs from HEAD only in packages the * working lock installs from a path repository (dist type "path") and in diff --git a/tests/windows/default-branch.php b/tests/windows/default-branch.php index 2c2f9757..7df87a05 100644 --- a/tests/windows/default-branch.php +++ b/tests/windows/default-branch.php @@ -25,7 +25,8 @@ function refused(callable $call):void { try{$call();}catch(RuntimeException $err // Only a retained composer.lock edit may coexist with start on current main. file_put_contents($repo.'/composer.lock', '{"fixture":"local path override"}'); $lockStart=$verify();check($lockStart['local_dependency_lock_edit']===true); - refused(fn()=>$verify(true)); + // Any local composer.lock edit also coexists with update (it is not runtime source). + check($verify(true)['local_dependency_lock_edit']===true&&file_get_contents($repo.'/composer.lock')==='{"fixture":"local path override"}'); git($repo,'add','composer.lock');check($verify()['local_dependency_lock_edit']===true); file_put_contents($repo.'/composer.lock', '{"fixture":"working after stage"}'); check($verify()['local_dependency_lock_edit']===true); @@ -53,20 +54,38 @@ function refused(callable $call):void { try{$call();}catch(RuntimeException $err git($repo,'remote','set-url','origin',$root.'/unexpected.git');refused(fn()=>$verify());git($repo,'remote','set-url','origin',$origin); file_put_contents($seed.'/source.txt','second');git($seed,'add','source.txt');git($seed,'commit','-m','second');git($seed,'push','origin','main'); file_put_contents($repo.'/composer.lock', '{"fixture":"still local"}'); - refused(fn()=>$verify());refused(fn()=>$verify(true)); + refused(fn()=>$verify()); $second=git($seed,'rev-parse','HEAD'); - // Behind with a local lock edit: the check reports the new commit but cannot update. - $state=$checkUpdate();check($state['current']===$first&&$state['available']===$second&&$state['behind']===1&&$state['can_update']===false&&str_contains($state['reason'],'composer.lock')&&$state['fresh']===true); + // Behind with a local lock edit: the check offers the update and the update keeps the local lock. + $state=$checkUpdate();check($state['current']===$first&&$state['available']===$second&&$state['behind']===1&&$state['can_update']===true&&$state['reason']===''&&$state['fresh']===true); check(git($repo,'rev-parse','HEAD')===$first&&file_get_contents($repo.'/composer.lock')==='{"fixture":"still local"}'); - file_put_contents($repo.'/composer.lock', '{"fixture":"local dependency"}'); - refused(fn()=>$verify());check(git($repo,'rev-parse','HEAD')===$first); - $state=$checkUpdate();check($state['behind']===1&&$state['can_update']===true&&$state['reason']===''&&git($repo,'rev-parse','HEAD')===$first); - check($verify(true)['commit']===$second&&git($repo,'symbolic-ref','--short','HEAD')==='main'); + $updated=$verify(true); + check($updated['commit']===$second&&$updated['local_dependency_lock_edit']===true&&$updated['local_dependency_lock_stashed']===false&&git($repo,'symbolic-ref','--short','HEAD')==='main'&&file_get_contents($repo.'/composer.lock')==='{"fixture":"still local"}'); + // Upstream changes composer.lock too: the local lock is stashed (kept) and upstream's is used. + file_put_contents($seed.'/composer.lock','{"fixture":"upstream dependency"}');git($seed,'add','composer.lock');git($seed,'commit','-m','lock');git($seed,'push','origin','main'); + $lockCommit=git($seed,'rev-parse','HEAD'); + $updated=$verify(true); + check($updated['commit']===$lockCommit&&$updated['local_dependency_lock_stashed']===true&&file_get_contents($repo.'/composer.lock')==='{"fixture":"upstream dependency"}'&&str_contains(git($repo,'stash','list'),'local composer.lock')); + check(git($repo,'status','--porcelain')===''); + $second=$lockCommit; file_put_contents($repo.'/source.txt','reviewed local code');git($repo,'add','source.txt');git($repo,'commit','-m','preserve local');$ahead=git($repo,'rev-parse','HEAD'); refused(fn()=>$verify(true));check(git($repo,'rev-parse','HEAD')===$ahead&&file_get_contents($repo.'/source.txt')==='reviewed local code'); file_put_contents($seed.'/source.txt','remote third');git($seed,'add','source.txt');git($seed,'commit','-m','remote third');git($seed,'push','origin','main'); refused(fn()=>$verify(true));check(git($repo,'rev-parse','HEAD')===$ahead); $state=$checkUpdate();check($state['can_update']===false&&str_contains($state['reason'],'diverged')&&$state['behind']===1&&git($repo,'rev-parse','HEAD')===$ahead); + // Repair: diverged + detached + dirty + untracked + hidden index + local lock all come back to a clean, + // current main, and nothing is lost (stash, backup branch, lock restored when upstream left it alone). + $third=git($seed,'rev-parse','HEAD'); + git($repo,'switch','--detach','HEAD');file_put_contents($repo.'/source.txt','uncommitted');file_put_contents($repo.'/scratch.txt','untracked'); + file_put_contents($repo.'/composer.lock','{"fixture":"repair path override"}');git($repo,'update-index','--skip-worktree','composer.lock'); + $repaired=DefaultBranchGuard::repair($repo,'git',$origin); + check($repaired['commit']===$third&&git($repo,'symbolic-ref','--short','HEAD')==='main'&&git($repo,'rev-parse','HEAD')===$third); + check(str_starts_with((string)$repaired['stash'],'civilizationbot repair ')&&str_contains(git($repo,'stash','list'),$repaired['stash'])); + check(str_starts_with((string)$repaired['backup_branch'],'civilizationbot-backup-')&&git($repo,'rev-parse',explode(', ',$repaired['backup_branch'])[0])===$ahead); + check(!is_file($repo.'/scratch.txt')&&file_get_contents($repo.'/source.txt')==='remote third'); + check($repaired['restored_composer_lock']===true&&file_get_contents($repo.'/composer.lock')==='{"fixture":"repair path override"}'); + check($verify()['local_dependency_lock_edit']===true); + git($repo,'checkout','--','composer.lock');$ahead=$third; check(str_starts_with(str_replace('\\','/',realpath($origin)),str_replace('\\','/',realpath($root)).'/'));rename($origin,$root.'/offline.git'); refused(fn()=>$verify());check(git($repo,'rev-parse','HEAD')===$ahead); @@ -78,7 +97,9 @@ function refused(callable $call):void { try{$call();}catch(RuntimeException $err $server=['basedir'=>$app,'ip'=>'127.0.0.1','port'=>1714,'name'=>'fixture','host'=>'fixture','enabled'=>false];foreach(['discussion','playercount','ooc','lobby','asay','ic','transit','adminlog','debug','garbage','runtime','attack']as$key){$server[$key]='';} $profile=['schema'=>'civilizationbot.portable.v1','root'=>$app,'state_dir'=>$state,'env_file'=>$root.'/separate.env','gitdir'=>$repo,'http_port'=>25565,'options'=>['channel_ids'=>[],'role_ids'=>[]],'servers'=>['test'=>$server]]; file_put_contents($root.'/profile.json',json_encode($profile,JSON_THROW_ON_ERROR));git($app,'init','--initial-branch=main');git($app,'add','.');git($app,'commit','-m','fixture application');git($app,'switch','--detach','HEAD'); - foreach(['start','update']as$action){[$code,$out,$err]=command([PHP_BINARY,$app.'/scripts/windows/control.php',$action,$root.'/profile.json'],false);check($code!==0&&str_contains($err,'Default branch guard refused'));} + // update refuses detached source; start only warns (a source check never blocks booting) and then + // stops at Composer, which this fixture forbids, so nothing networked runs. + [$code,$out,$err]=command([PHP_BINARY,$app.'/scripts/windows/control.php','update',$root.'/profile.json'],false);check($code!==0&&str_contains($err,'Default branch guard refused')); require_once __DIR__.'/../../src/Civ13/PortableProcess.php'; $lock=\Civ13\PortableProcess::lock($state); try { [$code,$out,$err]=command([PHP_BINARY,$app.'/scripts/windows/control.php','update',$root.'/profile.json'],false);check($code!==0&&str_contains($err,'Portable instance already running')); @@ -98,8 +119,8 @@ function refused(callable $call):void { try{$call();}catch(RuntimeException $err $owner=\Civ13\PortableProcess::lock($state);fclose($owner);proc_close($child);unlink($state.'/held'); check(\Civ13\PortableProcess::status($state)['running']===false); try { \Civ13\PortableProcess::status($root.'/no-such-state'); check(false); } catch (RuntimeException $error) { check($error->getMessage()==='Portable state lock unavailable'); } - putenv('CIVILIZATIONBOT_PROFILE='.$root.'/profile.json');[$code,$out,$err]=command([PHP_BINARY,$app.'/bot.php'],false);check($code!==0&&str_contains($err,'Default branch guard refused')&&!str_contains($err,'Composer must not load')); - echo "PASS real Git default/main/upstream/origin, detached/PR/dirty/hidden/ahead/diverged/offline controls, safe FF, read-only check-update and status JSON, and actual start/update/bootstrap precredential denial\n"; + putenv('CIVILIZATIONBOT_PROFILE='.$root.'/profile.json');[$code,$out,$err]=command([PHP_BINARY,$app.'/bot.php'],false);check($code!==0&&str_contains($err,'Source check warning (starting anyway): Default branch guard refused')); + echo "PASS real Git default/main/upstream/origin, detached/PR/dirty/hidden/ahead/diverged/offline controls, safe FF, read-only check-update and status JSON, actual update denial, and start/bootstrap warning instead of a boot block\n"; } finally { putenv($previousProfile===false?'CIVILIZATIONBOT_PROFILE':'CIVILIZATIONBOT_PROFILE='.$previousProfile); $resolved=str_replace('\\','/',realpath($root)); diff --git a/tests/windows/lock-path-guard.php b/tests/windows/lock-path-guard.php index 2be343bb..d544eb96 100644 --- a/tests/windows/lock-path-guard.php +++ b/tests/windows/lock-path-guard.php @@ -1,7 +1,7 @@ DefaultBranchGuard::verify($repo, true, 'git', $origin)); - lockCheck(lockGit($repo, 'rev-parse', 'HEAD') === $first, 'refused update kept HEAD'); - - // A staged path-only edit is refused too. - file_put_contents($repo.'/composer.lock', lockJson($pathOnly)); lockGit($repo, 'add', 'composer.lock'); - lockCheck(DefaultBranchGuard::check($repo, 'git', $origin)['can_update'] === false, 'staged lock edit not updatable'); - lockRefused(fn () => DefaultBranchGuard::verify($repo, true, 'git', $origin)); - lockGit($repo, 'reset', '-q', '--', 'composer.lock'); - - // A path-only unstaged edit can update and is kept byte for byte. - $bytes = lockJson($pathOnly); file_put_contents($repo.'/composer.lock', $bytes); - $state = DefaultBranchGuard::check($repo, 'git', $origin); - lockCheck($state['can_update'] === true && $state['reason'] === '', 'path-only lock updatable: '.$state['reason']); + lockCheck($state['behind'] === 1 && $state['can_update'] === true && $state['reason'] === '', 'bumped lock updatable: '.$state['reason']); $result = DefaultBranchGuard::verify($repo, true, 'git', $origin); - lockCheck($result['commit'] === $second && $result['local_dependency_lock_edit'] === true, 'update applied with lock kept'); - lockCheck(lockGit($repo, 'rev-parse', 'HEAD') === $second && file_get_contents($repo.'/composer.lock') === $bytes, 'HEAD advanced and lock bytes kept'); + lockCheck($result['commit'] === $second && $result['local_dependency_lock_edit'] === true && $result['local_dependency_lock_stashed'] === false, 'update applied with lock kept'); + lockCheck(lockGit($repo, 'rev-parse', 'HEAD') === $second && file_get_contents($repo.'/composer.lock') === $bumpedBytes, 'HEAD advanced and lock bytes kept'); - // Another source edit beside the lock is still refused. + // A staged lock edit updates too. file_put_contents($seed.'/source.txt', 'third'); lockGit($seed, 'add', 'source.txt'); lockGit($seed, 'commit', '-m', 'third'); lockGit($seed, 'push', 'origin', 'main'); + $third = lockGit($seed, 'rev-parse', 'HEAD'); + $bytes = lockJson($pathOnly); file_put_contents($repo.'/composer.lock', $bytes); lockGit($repo, 'add', 'composer.lock'); + lockCheck(DefaultBranchGuard::check($repo, 'git', $origin)['can_update'] === true, 'staged lock edit updatable'); + lockCheck(DefaultBranchGuard::verify($repo, true, 'git', $origin)['commit'] === $third && file_get_contents($repo.'/composer.lock') === $bytes, 'staged lock kept through update'); + lockGit($repo, 'reset', '-q', '--', 'composer.lock'); + + // Another source edit beside the lock is still refused by update (repair handles it). + file_put_contents($seed.'/source.txt', 'fourth'); lockGit($seed, 'add', 'source.txt'); lockGit($seed, 'commit', '-m', 'fourth'); lockGit($seed, 'push', 'origin', 'main'); file_put_contents($repo.'/notes.txt', 'unrelated'); lockRefused(fn () => DefaultBranchGuard::verify($repo, true, 'git', $origin)); - lockCheck(lockGit($repo, 'rev-parse', 'HEAD') === $second, 'mixed edits kept HEAD'); + lockCheck(lockGit($repo, 'rev-parse', 'HEAD') === $third, 'mixed edits kept HEAD'); unlink($repo.'/notes.txt'); - // Main changing composer.lock itself makes Git refuse the fast-forward; nothing is lost. + // Main changing composer.lock itself: the local lock is stashed (kept) and upstream's lock is used. $upstream = $committed; $upstream['packages'][1] = $zip('react/http', 'v1.13.0'); file_put_contents($seed.'/composer.lock', lockJson($upstream)); lockGit($seed, 'add', 'composer.lock'); lockGit($seed, 'commit', '-m', 'lock'); lockGit($seed, 'push', 'origin', 'main'); - lockRefused(fn () => DefaultBranchGuard::verify($repo, true, 'git', $origin)); - lockCheck(lockGit($repo, 'rev-parse', 'HEAD') === $second && file_get_contents($repo.'/composer.lock') === $bytes, 'upstream lock change kept local lock and HEAD'); - echo "PASS lock path guard: path-only update, bumped/added/staged/mixed refusals, upstream lock change\n"; + $result = DefaultBranchGuard::verify($repo, true, 'git', $origin); + lockCheck($result['commit'] === lockGit($seed, 'rev-parse', 'HEAD') && $result['local_dependency_lock_stashed'] === true, 'upstream lock change updates'); + lockCheck(file_get_contents($repo.'/composer.lock') === lockJson($upstream) && lockGit($repo, 'status', '--porcelain') === '', 'upstream lock checked out cleanly'); + lockGit($repo, 'checkout', 'stash@{0}', '--', 'composer.lock'); + lockCheck(file_get_contents($repo.'/composer.lock') === $bytes, 'stashed local lock recoverable'); + echo "PASS lock guard: any local lock edit updates (unstaged, staged), mixed edits refused, upstream lock change stashes the local lock\n"; } finally { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); foreach ($it as $file) { @chmod($file->getPathname(), 0700); $file->isDir() ? @rmdir($file->getPathname()) : @unlink($file->getPathname()); } From 5439f3a7a1a8b5292eb465eb4b47962be8540de2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 13:55:38 +0000 Subject: [PATCH 4/4] Seal the in-game verification relay and keep secrets out of URLs The desktop bot's relay to the primary bot is now encrypted end to end with AES-256-GCM under a key derived from INGAME_VERIFY_TOKEN, so a watcher on the plain-HTTP link can no longer read and race a live code. Answers are sealed and bound to their request. The game's discord_verify request is a POST with the webhook key in the X-Webhook-Key header and ckey/code in a JSON body; a key in the query string is refused. Tests cover rejection paths and secrets in logs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016WTP2R6s5HsPDzf2CSzzGM --- docs/ingame-verification.md | 23 +++++--- src/Civ13/HttpHandler.php | 7 ++- src/Civ13/HttpServiceManager.php | 73 +++++++++++------------ src/Civ13/InGameVerification.php | 69 ++++++++++++++++++++-- tests/local/ingame-verification.php | 90 +++++++++++++++++++++++------ 5 files changed, 191 insertions(+), 71 deletions(-) diff --git a/docs/ingame-verification.md b/docs/ingame-verification.md index 9bb1acce..1056751b 100644 --- a/docs/ingame-verification.md +++ b/docs/ingame-verification.md @@ -5,9 +5,11 @@ Players can link their BYOND key to Discord without editing their BYOND profile. 1. In Discord, the player runs `/approveme` **without** a ckey. CivilizationBot replies privately with a single-use code such as `ABCD-EFGH`, valid for 10 minutes. 2. In any Civ13 server, the player opens the OOC tab, clicks **Verify Discord** and types the code. -3. The game sends `ckey` + `code` to its own bot as the `discord_verify` webhook method - (`/webhook//discord_verify?key=&data={"ckey","code"}`) and shows the - JSON `{ok, message}` answer to the player. +3. The game POSTs `{"ckey","code"}` as JSON to its own bot at `/discord_verify` + (for example `/webhook//discord_verify`) with the webhook key in the `X-Webhook-Key` + header, and shows the JSON `{ok, message}` answer to the player. Neither the key nor the code is + ever part of a URL, so proxies and access logs never see them; a key in the query string is refused. + The game only sends this to a loopback (`127.0.0.1`/`localhost`) or `https://` address. BYOND has already signed the player in, so the game proves the ckey and the private code proves the Discord account. Bans, investigations, existing links, the BYOND account age rule and the @@ -20,15 +22,18 @@ out of in-game verification for ten minutes. Codes are kept in memory only. - **CivilizationBot** (primary, writes the verified list) redeems the code itself. - **VZGCivilizationBot** (desktop profile with the read-only hosted verifier) cannot register anyone. It forwards the request to the primary bot's `POST /verified/ingame` endpoint next to the hosted - verified list (`verification_source.url` + `/ingame`), signed with `X-Ingame-Verify-Time` and - `X-Ingame-Verify-Signature` (HMAC-SHA256 of `time + "\n" + body` with the shared secret), then passes the primary bot's answer back to the game. The link reaches the desktop game through + verified list (`verification_source.url` + `/ingame`), sealed with the shared secret + (`InGameVerification::seal`: AES-256-GCM under an HKDF key), then passes the primary bot's answer + back to the game. The answer is sealed too and bound to the request it answers. The link reaches the desktop game through the normal hosted verified-list refresh and access-file sync. Both bots need the same random secret as `INGAME_VERIFY_TOKEN`: in the primary bot's `.env` and in the desktop profile's environment file. Without it the primary bot refuses relays (403) and the -desktop bot tells players to use `/approveme` in Discord instead. The secret itself is never sent, so -the plain-HTTP `http://civ13.com:55555` source is acceptable: a captured request expires after 60 seconds -and its code is single use. Anyone holding the secret could link any ckey to a Discord user with a live -code, so keep it out of logs and chat. +desktop bot tells players to use `/approveme` in Discord instead. The secret itself is never sent and +the ckey and code are encrypted end to end, so someone watching the plain-HTTP `http://civ13.com:55555` +source sees neither and cannot redeem the code for their own account; a changed byte, the wrong +direction, a stale (over 60 seconds) or swapped message is refused. An `https://` source works too. +Anyone holding the secret could link any ckey to a Discord user with a live code, so keep it out of +logs and chat. `/approveme` is re-registered on every start so existing installs get the optional ckey. diff --git a/src/Civ13/HttpHandler.php b/src/Civ13/HttpHandler.php index 84877793..48a9075c 100644 --- a/src/Civ13/HttpHandler.php +++ b/src/Civ13/HttpHandler.php @@ -599,7 +599,12 @@ public function __isWhitelisted(ServerRequestInterface $request, string $ip): bo // Native webhook_send places its secret beside method/data, not inside JSON. $outerKey = $request->getQueryParams()['key'] ?? null; if (str_starts_with($request->getUri()->getPath(), '/webhook/')) { - // A trusted network address is not authentication of a game event. + // A trusted network address is not authentication of a game event. Newer game requests + // (in-game verification) send the key in the X-Webhook-Key header, never in the URL. + $headerKey = $request->getHeaderLine('X-Webhook-Key'); + if ($this->key !== '' && $headerKey !== '' && hash_equals($this->key, $headerKey)) { + return true; + } return $this->key !== '' && is_string($outerKey) && hash_equals($this->key, $outerKey); } if ($this->key) { diff --git a/src/Civ13/HttpServiceManager.php b/src/Civ13/HttpServiceManager.php index ba640166..4fe1342f 100644 --- a/src/Civ13/HttpServiceManager.php +++ b/src/Civ13/HttpServiceManager.php @@ -351,19 +351,25 @@ public function handleShutdownNoticeWebhook(ServerRequestInterface $request, Gam } /** - * In-game verification (Civ13 code/modules/client/discord_verify.dm): the game sends the - * player's ckey and the code they typed. The primary bot redeems it; a desktop bot with a - * read-only verifier relays it to the primary bot. Once authenticated the answer is always - * 200 JSON {ok, message}, which the game shows to the player. + * 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 + * header, so neither secret is ever part of a URL. The primary bot redeems it; a desktop bot + * with a read-only verifier relays it, encrypted, to the primary bot. Once authenticated the + * answer is always 200 JSON {ok, message}, which the game shows to the player. */ public function handleDiscordVerifyWebhook(ServerRequestInterface $request, GameServer $gameserver): HttpResponse { $secret = $this->civ13->options['http_key'] ?? ''; - $key = $request->getQueryParams()['key'] ?? null; - if (!is_string($secret) || $secret === '' || !is_string($key) || !hash_equals($secret, $key) || $gameserver->legacy_relay) { + $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 (!$data = self::inGameVerifyRequest(self::decodeParamData($request))) { + if ($request->getMethod() !== 'POST') { + return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED); + } + $body = (string) $request->getBody(); + $data = strlen($body) <= 1024 ? json_decode($body, true, 4) : null; + if (!is_array($data) || !$data = self::inGameVerifyRequest($data)) { return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); } if (!$this->civ13->verifier->readOnly) { @@ -374,7 +380,11 @@ public function handleDiscordVerifyWebhook(ServerRequestInterface $request, Game return HttpResponse::json(\React\Async\await($this->relayInGameVerification($data['ckey'], $data['code']))); } - /** Primary bot: in-game registrations relayed by a desktop bot that shares INGAME_VERIFY_TOKEN (HMAC-signed, see below). */ + /** + * Primary bot: in-game registrations relayed by a desktop bot that shares INGAME_VERIFY_TOKEN. + * Request and answer are sealed with it ({@see InGameVerification::seal()}), so the code is + * never readable on the wire even over plain HTTP, and the answer is bound to its request. + */ public function handleInGameVerifyRelay(ServerRequestInterface $request): HttpResponse { $secret = $this->civ13->options['ingame_verify_key'] ?? ''; @@ -384,19 +394,20 @@ public function handleInGameVerifyRelay(ServerRequestInterface $request): HttpRe if ($request->getMethod() !== 'POST') { return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED); } - $body = (string) $request->getBody(); - if (strlen($body) > 1024 || !self::inGameRelaySignatureValid($secret, $request->getHeaderLine('X-Ingame-Verify-Time'), $body, $request->getHeaderLine('X-Ingame-Verify-Signature'))) { + $opened = InGameVerification::open($secret, 'request', (string) $request->getBody()); + if ($opened === null) { return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); } - $data = json_decode($body, true, 4); - if (!is_array($data) || !$data = self::inGameVerifyRequest($data)) { + if (!$data = self::inGameVerifyRequest($opened['payload'])) { return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); } + $answer = $this->civ13->verifier->redeemInGame($data['ckey'], $data['code']); - return HttpResponse::json($this->civ13->verifier->redeemInGame($data['ckey'], $data['code'])); + return HttpResponse::plaintext(InGameVerification::seal($secret, 'response', $answer, $opened['nonce'])) + ->withHeader('Content-Type', 'application/json'); } - /** Desktop bot: forwards to the primary bot. Resolves {ok, message}; never rejects. */ + /** Desktop bot: forwards to the primary bot, sealed both ways. Resolves {ok, message}; never rejects. */ public function relayInGameVerification(string $ckey, string $code): PromiseInterface { $url = InGameVerification::relayUrl($this->civ13->verifier->verify_url); @@ -404,18 +415,18 @@ public function relayInGameVerification(string $ckey, string $code): PromiseInte if ($url === null || !is_string($key) || $key === '') { return \React\Promise\resolve(['ok' => false, 'message' => 'Verifying from this server is not set up yet. Use /approveme in Discord instead.']); } - - $body = json_encode(['ckey' => $ckey, 'code' => $code], JSON_THROW_ON_ERROR); - $time = (string) time(); + $body = InGameVerification::seal($key, 'request', ['ckey' => $ckey, 'code' => $code]); + $nonce = InGameVerification::nonceOf($body); return $this->civ13->browser->withTimeout(10.0)->withRejectErrorResponse(false)->post( $url, - ['Content-Type' => 'application/json', 'X-Ingame-Verify-Time' => $time, 'X-Ingame-Verify-Signature' => self::inGameRelaySignature($key, $time, $body)], + ['Content-Type' => 'application/json'], $body - )->then(function (ResponseInterface $response): array { - $body = json_decode((string) $response->getBody(), true, 4); - if ($response->getStatusCode() === 200 && is_array($body) && is_bool($body['ok'] ?? null) && is_string($body['message'] ?? null)) { - return ['ok' => $body['ok'], 'message' => mb_substr($body['message'], 0, 400)]; + )->then(function (ResponseInterface $response) use ($key, $nonce): array { + $opened = $response->getStatusCode() === 200 ? InGameVerification::open($key, 'response', (string) $response->getBody(), $nonce) : null; + $answer = $opened['payload'] ?? null; + if (is_array($answer) && is_bool($answer['ok'] ?? null) && is_string($answer['message'] ?? null)) { + return ['ok' => $answer['ok'], 'message' => mb_substr($answer['message'], 0, 400)]; } $this->logger->warning('In-game verification relay refused', ['status' => $response->getStatusCode()]); @@ -427,24 +438,6 @@ public function relayInGameVerification(string $ckey, string $code): PromiseInte }); } - /** - * The relay may cross plain HTTP, so the shared secret never travels: the desktop bot signs - * time + body with it. A captured request is useless after a minute, and its code is single use. - */ - public static function inGameRelaySignature(string $secret, string $time, string $body): string - { - return hash_hmac('sha256', $time."\n".$body, $secret); - } - - public static function inGameRelaySignatureValid(string $secret, string $time, string $body, string $signature, ?int $now = null): bool - { - if ($secret === '' || preg_match('/^[0-9]{1,12}$/D', $time) !== 1 || abs(($now ?? time()) - (int) $time) > 60 || preg_match('/^[0-9a-f]{64}$/D', $signature) !== 1) { - return false; - } - - return hash_equals(self::inGameRelaySignature($secret, $time, $body), $signature); - } - /** {ckey, code} from the game or a relay, or null. The game sends a BYOND ckey: lower-case letters and digits. */ public static function inGameVerifyRequest(array $data): ?array { diff --git a/src/Civ13/InGameVerification.php b/src/Civ13/InGameVerification.php index f7b083f1..3610b819 100644 --- a/src/Civ13/InGameVerification.php +++ b/src/Civ13/InGameVerification.php @@ -21,10 +21,11 @@ * already knows their BYOND key (BYOND signed them in), so the code proves the * Discord side and the game proves the ckey; no BYOND profile token is needed. * - * The game sends `ckey` + `code` to its own bot (`/webhook//discord_verify`). - * The primary bot redeems it here. A desktop bot with a read-only verifier cannot - * register anyone, so it forwards the same request to the primary bot's - * `/verified/ingame` relay endpoint and hands the answer back to the game. + * The game POSTs `ckey` + `code` to its own bot (`/webhook//discord_verify`, + * key in a header, nothing secret in the URL). The primary bot redeems it here. A desktop + * bot with a read-only verifier cannot register anyone, so it forwards the request, sealed + * with INGAME_VERIFY_TOKEN ({@see seal()}), to the primary bot's `/verified/ingame` relay + * endpoint and hands the sealed answer back to the game. * * Codes live only in memory: a bot restart simply asks players for a new code. */ @@ -162,6 +163,66 @@ public static function relayUrl(string $verify_url): ?string return rtrim($verify_url, '/').'/ingame'; } + public const SEAL_WINDOW = 60; // seconds a sealed relay message stays valid + private const NONCE_BYTES = 12; + private const TAG_BYTES = 16; + + /** + * Relay messages between a desktop bot and the primary bot are sealed with AES-256-GCM + * (OpenSSL, already required by the portable profile) under a key derived from INGAME_VERIFY_TOKEN: the code is never readable + * on the wire, a changed byte is rejected, and each message carries its direction and time. + * An answer also carries the nonce of the request it answers, so it can't be swapped. + */ + public static function seal(string $secret, string $direction, array $payload, ?string $answers = null, ?int $now = null): string + { + $nonce = random_bytes(self::NONCE_BYTES); + $plain = json_encode(['d' => $direction, 't' => $now ?? time(), 'r' => $answers, 'p' => $payload], JSON_THROW_ON_ERROR); + $tag = ''; + $cipher = openssl_encrypt($plain, 'aes-256-gcm', self::sealKey($secret), OPENSSL_RAW_DATA, $nonce, $tag, '', self::TAG_BYTES); + if (!is_string($cipher)) { + throw new \RuntimeException('Could not seal the relay message'); + } + + return json_encode(['v' => 1, 'n' => base64_encode($nonce), 'c' => base64_encode($cipher.$tag)], JSON_THROW_ON_ERROR); + } + + /** @return array{payload: array, nonce: string}|null null for anything forged, stale, mismatched or malformed */ + public static function open(string $secret, string $direction, string $body, ?string $answers = null, ?int $now = null): ?array + { + if ($secret === '' || strlen($body) > 4096) { + return null; + } + $outer = json_decode($body, true, 3); + if (!is_array($outer) || ($outer['v'] ?? null) !== 1 || !is_string($outer['n'] ?? null) || !is_string($outer['c'] ?? null)) { + return null; + } + $nonce = base64_decode($outer['n'], true); + $cipher = base64_decode($outer['c'], true); + if (!is_string($nonce) || strlen($nonce) !== self::NONCE_BYTES || !is_string($cipher) || strlen($cipher) < self::TAG_BYTES) { + return null; + } + $plain = openssl_decrypt(substr($cipher, 0, -self::TAG_BYTES), 'aes-256-gcm', self::sealKey($secret), OPENSSL_RAW_DATA, $nonce, substr($cipher, -self::TAG_BYTES)); + $inner = is_string($plain) ? json_decode($plain, true, 6) : null; + if (!is_array($inner) || ($inner['d'] ?? null) !== $direction || !is_int($inner['t'] ?? null) + || abs(($now ?? time()) - $inner['t']) > self::SEAL_WINDOW || !is_array($inner['p'] ?? null) + || ($inner['r'] ?? null) !== $answers) { + return null; + } + + return ['payload' => $inner['p'], 'nonce' => $outer['n']]; + } + + /** The base64 nonce of a sealed message, which its answer must name. */ + public static function nonceOf(string $sealed): string + { + return (string) (json_decode($sealed, true, 3)['n'] ?? ''); + } + + private static function sealKey(string $secret): string + { + return hash_hkdf('sha256', $secret, 32, 'civ13 in-game verification relay v1'); + } + /** The player-facing reply to `/approveme` without a ckey. */ public static function codeMessage(string $code): string { diff --git a/tests/local/ingame-verification.php b/tests/local/ingame-verification.php index b168eaf7..22169ab8 100644 --- a/tests/local/ingame-verification.php +++ b/tests/local/ingame-verification.php @@ -85,42 +85,98 @@ function verifier(bool $readOnly): FakeVerifier foreach ([['ckey' => 'Alice', 'code' => 'x'], ['ckey' => 'alice'], ['ckey' => 'alice', 'code' => ''], ['ckey' => 'alice', 'code' => str_repeat('A', 33)], ['ckey' => 'a b', 'code' => 'x'], ['ckey' => ['alice'], 'code' => 'x']] as $bad) { check(HttpServiceManager::inGameVerifyRequest($bad) === null, 'invalid request rejected: '.json_encode($bad)); } +final class LogSpy extends Monolog\Handler\AbstractProcessingHandler +{ + public string $text = ''; + protected function write(Monolog\LogRecord $record): void { $this->text .= $record->message.' '.json_encode($record->context).PHP_EOL; } +} +$spy = new LogSpy(); function manager(Verifier $verifier, string $relayKey): HttpServiceManager { + global $spy; $civ13 = inert(Civ13::class); $civ13->options = ['http_key' => 'webhook-key', 'ingame_verify_key' => $relayKey]; $civ13->verifier = $verifier; $manager = inert(HttpServiceManager::class); setProp($manager, 'civ13', $civ13); - $manager->logger = new Logger('test', [new NullHandler()]); + $manager->logger = new Logger('test', [$spy]); return $manager; } -function relayRequest(string $key, string $body, string $method = 'POST', ?int $time = null): ServerRequest +function relayRequest(string $body, string $method = 'POST'): ServerRequest { - $time = (string) ($time ?? time()); - return new ServerRequest($method, 'http://civ13.com:55555/verified/ingame', $key === '' ? [] : ['X-Ingame-Verify-Time' => $time, 'X-Ingame-Verify-Signature' => HttpServiceManager::inGameRelaySignature($key, $time, $body)], $body); + return new ServerRequest($method, 'http://civ13.com:55555/verified/ingame', ['Content-Type' => 'application/json'], $body); } $v = verifier(false); $code = $v->inGame->issue(ALICE); $m = manager($v, 'relay-secret'); +$payload = ['ckey' => 'alice', 'code' => $code]; +$sealed = InGameVerification::seal('relay-secret', 'request', $payload); +check(! str_contains($sealed, $code) && ! str_contains($sealed, str_replace('-', '', $code)) && ! str_contains($sealed, 'alice') && ! str_contains($sealed, 'relay-secret'), 'the sealed relay body shows neither the code, the ckey nor the secret'); +check(InGameVerification::open('relay-secret', 'request', $sealed)['payload'] === $payload, 'seal round trip'); +check(InGameVerification::open('other-secret', 'request', $sealed) === null, 'a wrong secret cannot open it'); +check(InGameVerification::open('relay-secret', 'response', $sealed) === null, 'a request cannot pose as an answer'); +check(InGameVerification::open('relay-secret', 'request', $sealed, null, time() + 120) === null, 'a stale message is refused'); +$outer = json_decode($sealed, true); +$cipher = base64_decode($outer['c']); +$cipher[20] = chr(ord($cipher[20]) ^ 1); +check(InGameVerification::open('relay-secret', 'request', json_encode(['v' => 1, 'n' => $outer['n'], 'c' => base64_encode($cipher)])) === null, 'a changed byte is refused'); +check(InGameVerification::open('relay-secret', 'request', '') === null && InGameVerification::open('', 'request', $sealed) === null && InGameVerification::open('relay-secret', 'request', '{"v":1}') === null, 'malformed or keyless input is refused'); +check($m->handleInGameVerifyRelay(relayRequest(json_encode($payload)))->getStatusCode() === 403, 'an unsealed relay is refused'); +check($m->handleInGameVerifyRelay(relayRequest(InGameVerification::seal('wrong', 'request', $payload)))->getStatusCode() === 403, 'relay rejects a wrong secret'); +check($m->handleInGameVerifyRelay(relayRequest(InGameVerification::seal('relay-secret', 'request', $payload, null, time() - 120)))->getStatusCode() === 403, 'stale relays are refused'); +check(manager($v, '')->handleInGameVerifyRelay(relayRequest($sealed))->getStatusCode() === 403, 'relay off without INGAME_VERIFY_TOKEN'); +check(manager(verifier(true), 'relay-secret')->handleInGameVerifyRelay(relayRequest($sealed))->getStatusCode() === 403, 'a read-only bot never accepts relays'); +check($m->handleInGameVerifyRelay(relayRequest($sealed, 'GET'))->getStatusCode() === 405, 'relay is POST only'); +check($m->handleInGameVerifyRelay(relayRequest(InGameVerification::seal('relay-secret', 'request', ['ckey' => 'alice'])))->getStatusCode() === 400, 'relay validates the payload'); +$response = $m->handleInGameVerifyRelay(relayRequest($sealed)); +$answerBody = (string) $response->getBody(); +check(! str_contains($answerBody, 'linked'), 'the answer is sealed too'); +check(InGameVerification::open('relay-secret', 'response', $answerBody, InGameVerification::nonceOf(InGameVerification::seal('relay-secret', 'request', $payload))) === null, 'an answer only opens for the request it answers'); +$answer = InGameVerification::open('relay-secret', 'response', $answerBody, InGameVerification::nonceOf($sealed)); +check($response->getStatusCode() === 200 && $answer['payload']['ok'] === true && $v->processed === [['alice', ALICE]], 'relay redeems on the primary bot'); + +// Game webhook: key only in the X-Webhook-Key header, ckey and code only in a POST body. +$gameserver = inert(\Civ13\GameServer::class); +setProp($gameserver, 'legacy_relay', false); +function gameRequest(array $headers, string $body, string $method = 'POST', string $query = ''): ServerRequest +{ + return new ServerRequest($method, 'http://127.0.0.1:55555/webhook/nomads/discord_verify'.$query, $headers, $body); +} +$v = verifier(false); +$code = $v->inGame->issue(ALICE); +$m = manager($v, ''); $body = json_encode(['ckey' => 'alice', 'code' => $code]); -check($m->handleInGameVerifyRelay(relayRequest('', $body))->getStatusCode() === 403, 'relay needs the key'); -check($m->handleInGameVerifyRelay(relayRequest('wrong', $body))->getStatusCode() === 403, 'relay rejects a wrong key'); -check($m->handleInGameVerifyRelay(relayRequest('relay-secret', $body, 'POST', time() - 120))->getStatusCode() === 403, 'stale signatures are refused'); -$tampered = relayRequest('relay-secret', $body); -check($m->handleInGameVerifyRelay(new ServerRequest('POST', 'http://civ13.com:55555/verified/ingame', ['X-Ingame-Verify-Time' => $tampered->getHeaderLine('X-Ingame-Verify-Time'), 'X-Ingame-Verify-Signature' => $tampered->getHeaderLine('X-Ingame-Verify-Signature')], json_encode(['ckey' => 'admin', 'code' => $code])))->getStatusCode() === 403, 'a signature does not cover another ckey'); -check(! str_contains(json_encode($tampered->getHeaders()), 'relay-secret'), 'the secret itself is never sent'); -check(manager($v, '')->handleInGameVerifyRelay(relayRequest('', $body))->getStatusCode() === 403, 'relay off without INGAME_VERIFY_TOKEN'); -check(manager(verifier(true), 'relay-secret')->handleInGameVerifyRelay(relayRequest('relay-secret', $body))->getStatusCode() === 403, 'a read-only bot never accepts relays'); -check($m->handleInGameVerifyRelay(relayRequest('relay-secret', $body, 'GET'))->getStatusCode() === 405, 'relay is POST only'); -check($m->handleInGameVerifyRelay(relayRequest('relay-secret', '{"ckey":"alice"}'))->getStatusCode() === 400, 'relay validates the body'); -$response = $m->handleInGameVerifyRelay(relayRequest('relay-secret', $body)); -$answer = json_decode((string) $response->getBody(), true); -check($response->getStatusCode() === 200 && $answer['ok'] === true && $v->processed === [['alice', ALICE]], 'relay redeems on the primary bot'); +check($m->handleDiscordVerifyWebhook(gameRequest([], $body), $gameserver)->getStatusCode() === 403, 'game request needs the key header'); +check($m->handleDiscordVerifyWebhook(gameRequest(['X-Webhook-Key' => 'wrong'], $body), $gameserver)->getStatusCode() === 403, 'game request rejects a wrong key'); +check($m->handleDiscordVerifyWebhook(gameRequest([], $body, 'POST', '?key=webhook-key'), $gameserver)->getStatusCode() === 403, 'a key in the URL is not accepted'); +check($m->handleDiscordVerifyWebhook(gameRequest(['X-Webhook-Key' => 'webhook-key'], '', 'GET', '?key=webhook-key&method=discord_verify&data='.urlencode($body)), $gameserver)->getStatusCode() === 405, 'the old query-string request is refused'); +check($m->handleDiscordVerifyWebhook(gameRequest(['X-Webhook-Key' => 'webhook-key'], '{"ckey":"alice"}'), $gameserver)->getStatusCode() === 400, 'game request validates the body'); +check($v->processed === [], 'nothing redeemed by refused requests'); +$response = $m->handleDiscordVerifyWebhook(gameRequest(['X-Webhook-Key' => 'webhook-key'], $body), $gameserver); +check($response->getStatusCode() === 200 && json_decode((string) $response->getBody(), true)['ok'] === true && $v->processed === [['alice', ALICE]], 'game request redeems with header key and JSON body'); +$handler = inert(\Civ13\HttpHandler::class); +setProp($handler, 'key', 'webhook-key'); +check($handler->__isWhitelisted(gameRequest(['X-Webhook-Key' => 'webhook-key'], $body), '203.0.113.9'), 'the router accepts the header key on webhook paths'); +check(! $handler->__isWhitelisted(gameRequest(['X-Webhook-Key' => 'nope'], $body), '203.0.113.9'), 'the router refuses a wrong header key'); // A desktop bot without a relay key answers the game without any network call. $relayed = null; manager(verifier(true), '')->relayInGameVerification('alice', 'ABCD-EFGH')->then(static function (array $r) use (&$relayed): void { $relayed = $r; }); check(is_array($relayed) && $relayed['ok'] === false && str_contains($relayed['message'], 'not set up'), 'unconfigured relay answers plainly'); +// Logs: nothing above wrote a code, a ckey's code, a key or a relay secret. +foreach (array_merge([$code, str_replace('-', '', $code), 'webhook-key', 'relay-secret'], array_map(static fn (string $c): string => str_replace('-', '', $c), [$first, $second, $late, $good])) as $secret) { + check(! str_contains($spy->text, $secret), 'secret kept out of the logs: '.$secret); +} + +// And no log call in the verification paths names the code, the key, the body or the secret. +$source = file_get_contents(__DIR__.'/../../src/Civ13/HttpServiceManager.php'); +$from = strpos($source, 'public function handleDiscordVerifyWebhook'); +$section = substr($source, $from, strpos($source, 'public static function inGameVerifyRequest') - $from); +preg_match_all('/logger->\w+\((.*?)\);/s', $section, $calls); +check(count($calls[1]) >= 2, 'log calls found in the verification paths'); +foreach ($calls[1] as $call) { + check(preg_match('/\$(code|key|secret|body|data|payload|request)\b/', $call) !== 1, 'log call carries no secret: '.$call); +} + echo "ingame-verification: $checks checks passed\n";