From 942ac801d8de83595b09a932aceec98d5547ba9e Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 17 Nov 2026 15:58:43 +0000 Subject: [PATCH] Relay the join screen to the lobby channel both ways The lobby webhook now checks the service key like the other chat routes and takes a kind: chat (the existing LOBBY line), join_screen and entered arrival notices. Plain messages in a server's lobby channel go to the game through SQL/discord2lobby.txt with the same eligibility, formatting and badword rules as Discord OOC; secondary shard regions are skipped. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016WTP2QxSKVCEeWYEHrcnJq --- .github/workflows/local-profile.yml | 1 + src/Civ13/Civ13.php | 1 + src/Civ13/GameServer.php | 11 ++++ src/Civ13/HttpServiceManager.php | 74 +++++++++++++++++++-------- src/Civ13/MessageServiceManager.php | 17 +++++-- tests/local/lobby-webhook.php | 78 +++++++++++++++++++++++++++++ tests/local/ooc-auto-relay.php | 24 ++++++++- 7 files changed, 181 insertions(+), 25 deletions(-) create mode 100644 tests/local/lobby-webhook.php diff --git a/.github/workflows/local-profile.yml b/.github/workflows/local-profile.yml index 3255dd13..8b93767d 100644 --- a/.github/workflows/local-profile.yml +++ b/.github/workflows/local-profile.yml @@ -114,6 +114,7 @@ jobs: - run: php tests/local/message-delivery.php vendor/autoload.php - run: php tests/local/ooc-webhook.php vendor/autoload.php - run: php tests/local/ooc-auto-relay.php vendor/autoload.php + - run: php tests/local/lobby-webhook.php vendor/autoload.php - run: php tests/local/game-ready.php vendor/autoload.php timeout-minutes: 2 - run: php -d memory_limit=128M tests/local/game-ready-http.php vendor/autoload.php diff --git a/src/Civ13/Civ13.php b/src/Civ13/Civ13.php index 29b1aec0..3ee97a38 100644 --- a/src/Civ13/Civ13.php +++ b/src/Civ13/Civ13.php @@ -111,6 +111,7 @@ class Civ13 public const discord2ooc = '/SQL/discord2ooc.txt'; public const discord2admin = '/SQL/discord2admin.txt'; + public const discord2lobby = '/SQL/discord2lobby.txt'; public const discord2dm = '/SQL/discord2dm.txt'; public const discord2ban = '/SQL/discord2ban.txt'; public const discord2unban = '/SQL/discord2unban.txt'; diff --git a/src/Civ13/GameServer.php b/src/Civ13/GameServer.php index 000a6ec4..c63ab7bb 100644 --- a/src/Civ13/GameServer.php +++ b/src/Civ13/GameServer.php @@ -978,6 +978,17 @@ public function OOCMessage(string $message, string $sender): bool { return $this->enabled && \Civ13\Server\Ipc::append($this->basedir.Civ13::discord2ooc, [$sender, $message]); } + /** + * Sends a Discord lobby-channel message to the players on the join screen. + * + * @param string $message The message to be sent. + * @param string $sender The sender of the message. + * @return bool True when the line was written for the game to pick up. + */ + public function LobbyMessage(string $message, string $sender): bool + { + return $this->enabled && \Civ13\Server\Ipc::append($this->basedir.Civ13::discord2lobby, [$sender, $message]); + } /** * Sends an admin message to the server. * diff --git a/src/Civ13/HttpServiceManager.php b/src/Civ13/HttpServiceManager.php index 9f14d401..b6454312 100644 --- a/src/Civ13/HttpServiceManager.php +++ b/src/Civ13/HttpServiceManager.php @@ -192,6 +192,58 @@ public function handleStructuredChatWebhook(ServerRequestInterface $request, Gam return new HttpResponse(HttpResponse::STATUS_ACCEPTED); } + /** + * Join-screen relay for the server's lobby channel. kind "chat" (default) + * is lobby chat and needs a message; "join_screen" and "entered" are short + * arrival notices that carry only the player's key. + */ + public function handleLobbyWebhook(ServerRequestInterface $request, GameServer $gameserver): HttpResponse + { + $data = self::decodeParamData($request); + $key = $this->civ13->options['http_key'] ?? ''; + $requestKey = $request->getQueryParams()['key'] ?? null; + if (!is_string($key) || $key === '' || !is_string($requestKey) || !hash_equals($key, $requestKey)) { + return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); + } + $kind = $data['kind'] ?? 'chat'; + if (!is_string($kind) || !in_array($kind, ['chat', 'join_screen', 'entered'], true)) { + return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); + } + if (!is_string($data['ckey'] ?? null) || !preg_match('/^[A-Za-z0-9_ ]{1,64}$/D', $data['ckey'])) { + return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); + } + $ckey = Civ13::sanitizeInput($data['ckey']); + if ($ckey === '') { return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); } + if ($kind === 'chat' && (!is_string($data['message'] ?? null) || $data['message'] === '' + || strlen($data['message']) > 16384 || str_contains($data['message'], "\0"))) { + return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); + } + if ($gameserver->legacy_relay) { return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); } + $channel = $gameserver->lobby ?? ''; + if (!$channel || !$this->discord->getChannel($channel)) { + return new HttpResponse(HttpResponse::STATUS_SERVICE_UNAVAILABLE); + } + $time = '['.date('H:i:s').']'; + if ($kind === 'chat') { + $message = strip_tags(htmlspecialchars_decode(html_entity_decode($data['message']))); + if ($message === '') { return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST); } + $relay = $gameserver->gameChatWebhookRelay("**__{$time} LOBBY__ $ckey:** $message", $channel, $ckey, true); + } else { + $name = self::lobbyMarkdownName($data['ckey']); + $line = $kind === 'join_screen' ? "`{$time}` **{$name}** is on the join screen." : "`{$time}` **{$name}** entered the world."; + $relay = $gameserver->gameChatWebhookRelay($line, $channel); + } + $relay->then(null, fn (\Throwable $error) => $this->logger->error('Lobby relay failed: '.$error->getMessage())); + + return new HttpResponse(HttpResponse::STATUS_ACCEPTED); + } + + /** A BYOND key as literal Discord text: markdown characters escaped. */ + public static function lobbyMarkdownName(string $key): string + { + return preg_replace('/([\\\\_*~`|>])/', '\\\\$1', $key); + } + /** Existing keyed bridge only. Observations never upgrade lifecycle/Topic readiness. */ public function handleGameReadyWebhook(ServerRequestInterface $request, GameServer $gameserver): HttpResponse { @@ -1743,27 +1795,7 @@ function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): ->offsetSet( $server_endpoint.'/lobbymessage', - function (ServerRequestInterface $request, string $endpoint, bool $whitelisted) use (&$gameserver): HttpResponse { - if ($gameserver->legacy_relay) { - return new HttpResponse(HttpResponse::STATUS_FORBIDDEN); - } - if (! isset($gameserver->lobby)) { - return HttpResponse::plaintext('Webhook Channel Not Defined')->withStatus(HttpResponse::STATUS_INTERNAL_SERVER_ERROR); - } - if (! $this->discord->getChannel($channel_id = $gameserver->lobby)) { - return HttpResponse::plaintext('Discord Channel Not Found')->withStatus(HttpResponse::STATUS_INTERNAL_SERVER_ERROR); - } - - $data = self::decodeParamData($request); - $time = '['.date('H:i:s', time()).']'; - isset($data['ckey']) ? $ckey = Civ13::sanitizeInput($data['ckey']) : $ckey = '(NULL)'; - isset($data['message']) ? $message = strip_tags(htmlspecialchars_decode(html_entity_decode($data['message']))) : $message = '(NULL)'; - $message = "**__{$time} LOBBY__ $ckey:** $message"; - - $gameserver->gameChatWebhookRelay($message, $channel_id, $ckey, true); - - return new HttpResponse(HttpResponse::STATUS_OK); - }, + fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleLobbyWebhook($request, $gameserver), true ) ->offsetSet( diff --git a/src/Civ13/MessageServiceManager.php b/src/Civ13/MessageServiceManager.php index 742ebc97..87dbf145 100644 --- a/src/Civ13/MessageServiceManager.php +++ b/src/Civ13/MessageServiceManager.php @@ -358,17 +358,28 @@ private function __declareListener() } /** - * Relays a plain (non-command) message posted in a server's #ooc channel to that server's in-game OOC. + * Relays a plain (non-command) message posted in a server's #ooc channel to that server's in-game OOC, + * or one posted in its lobby channel to the players on that server's join screen. * Only verified, non-banished members are relayed; badword matches and empty messages are dropped. * A failed IPC write is marked with a 🔥 reaction; successful relays stay quiet. */ public function relayOocMessage(Message $message): ?PromiseInterface { $gameserver = null; + $lobby = false; foreach ($this->civ13->enabled_gameservers as $candidate) { // A secondary shard region shares its parent's OOC channel; Discord OOC goes to the parent world only. - if ($candidate->ooc !== '' && $candidate->ooc === $message->channel_id && $candidate->shardOf === '') { + if ($candidate->shardOf !== '') { + continue; + } + if ($candidate->ooc !== '' && $candidate->ooc === $message->channel_id) { + $gameserver = $candidate; + break; + } + // The lobby channel reaches only the players on that world's join screen. + if (($candidate->lobby ?? '') !== '' && $candidate->lobby === $message->channel_id) { $gameserver = $candidate; + $lobby = true; break; } } @@ -415,7 +426,7 @@ public function relayOocMessage(Message $message): ?PromiseInterface if (OocAutoRelay::blocked($text, $this->civ13->ooc_badwords)) { return null; } - if ($gameserver->OOCMessage($text, $ckey)) { + if ($lobby ? $gameserver->LobbyMessage($text, $ckey) : $gameserver->OOCMessage($text, $ckey)) { return null; } diff --git a/tests/local/lobby-webhook.php b/tests/local/lobby-webhook.php new file mode 100644 index 00000000..86af314b --- /dev/null +++ b/tests/local/lobby-webhook.php @@ -0,0 +1,78 @@ +found ? (new ReflectionClass(\Discord\Parts\Channel\Channel::class))->newInstanceWithoutConstructor() : null; } +} +final class LobbyServer extends \Civ13\GameServer { + public array $calls = []; + public function gameChatWebhookRelay(string $message, string $channel_id, ?string $ckey = null, ?bool $ooc = true, ?bool $moderate = true): PromiseInterface + { $this->calls[] = [$message, $channel_id, $ckey, $ooc]; return resolve(null); } +} +$civ = (new ReflectionClass(\Civ13\Civ13::class))->newInstanceWithoutConstructor(); +$civ->options = ['http_key' => 'synthetic-lobby-key']; +$manager = (new ReflectionClass(\Civ13\HttpServiceManager::class))->newInstanceWithoutConstructor(); +$manager->civ13 = $civ; +$manager->discord = (new ReflectionClass(LobbyDiscord::class))->newInstanceWithoutConstructor(); +$manager->logger = new \Monolog\Logger('offline-lobby', [new \Monolog\Handler\NullHandler()]); +$server = (new ReflectionClass(LobbyServer::class))->newInstanceWithoutConstructor(); +$server->legacy_relay = false; $server->lobby = '123456789012345678'; +$send = static function (array $data, ?string $key = 'synthetic-lobby-key') use ($manager, $server): int { + $query = ['method' => 'lobbymessage', 'data' => json_encode($data)]; + if ($key !== null) { $query['key'] = $key; } + return $manager->handleLobbyWebhook(new ServerRequest('GET', 'http://localhost/webhook/test?'.http_build_query($query)), $server)->getStatusCode(); +}; + +// Lobby chat keeps the old LOBBY line, moderated like OOC, posted under the player's ckey. +check($send(['ckey' => 'Real_Player', 'message' => 'hello & welcome']) === 202, 'Lobby chat rejected'); +[$line, $channel, $ckey, $ooc] = end($server->calls); +check($channel === '123456789012345678' && $ckey === 'realplayer' && $ooc === true, 'Lobby chat routed wrongly'); +check(str_contains($line, 'LOBBY__ realplayer:** hello & welcome'), 'Lobby chat text changed: '.$line); +check($send(['ckey' => 'Real_Player', 'kind' => 'chat', 'message' => 'again']) === 202, 'Explicit chat kind rejected'); + +// Arrival notices: no ckey identity lookup, markdown in the key escaped. +check($send(['ckey' => 'Real_Player', 'kind' => 'join_screen']) === 202, 'Join-screen notice rejected'); +[$line, , $ckey] = end($server->calls); +check($ckey === null && str_contains($line, '**Real\_Player** is on the join screen.'), 'Join-screen notice wrong: '.$line); +check($send(['ckey' => 'Real Player', 'kind' => 'entered']) === 202, 'Entered notice rejected'); +[$line, , $ckey] = end($server->calls); +check($ckey === null && str_contains($line, '**Real Player** entered the world.'), 'Entered notice wrong: '.$line); + +// Rejections never reach the channel. +$count = count($server->calls); +check($send(['ckey' => 'Real_Player', 'message' => 'x'], 'wrong') === 403, 'Wrong key accepted'); +check($send(['ckey' => 'Real_Player', 'message' => 'x'], null) === 403, 'Missing key accepted'); +foreach ([ + ['ckey' => 'Real_Player'], + ['ckey' => 'Real_Player', 'message' => ''], + ['ckey' => 'Real_Player', 'message' => "bad\0line"], + ['ckey' => 'Real_Player', 'message' => []], + ['ckey' => 'Real_Player', 'kind' => 'explode'], + ['ckey' => 'Real_Player', 'kind' => []], + ['ckey' => '<@&1>', 'kind' => 'entered'], + ['ckey' => str_repeat('a', 65), 'kind' => 'entered'], + ['kind' => 'join_screen'], +] as $bad) { + check($send($bad) === 400, 'Malformed lobby request accepted: '.json_encode($bad)); +} +$server->legacy_relay = true; +check($send(['ckey' => 'Real_Player', 'kind' => 'entered']) === 403, 'Legacy relay posted'); +$server->legacy_relay = false; $server->lobby = ''; +check($send(['ckey' => 'Real_Player', 'kind' => 'entered']) === 503, 'Missing lobby channel accepted'); +$server->lobby = '123456789012345678'; $manager->discord->found = false; +check($send(['ckey' => 'Real_Player', 'kind' => 'entered']) === 503, 'Unknown lobby channel accepted'); +check(count($server->calls) === $count, 'A rejected request reached the channel'); +check(\Civ13\HttpServiceManager::lobbyMarkdownName('a_b*c~d`e|f>g\\h') === 'a\_b\*c\~d\`e\|f\>g\\\\h', 'Markdown escape wrong'); + +echo "Lobby webhook checks passed\n"; diff --git a/tests/local/ooc-auto-relay.php b/tests/local/ooc-auto-relay.php index d9b30435..48c6d29b 100644 --- a/tests/local/ooc-auto-relay.php +++ b/tests/local/ooc-auto-relay.php @@ -92,16 +92,19 @@ public function getVerifiedItem(\Discord\Parts\User\Member|\Discord\Parts\User\U } final class RelayServer extends \Civ13\GameServer { public array $sent = []; public bool $fail = false; + public array $lobbySent = []; public function OOCMessage(string $message, string $sender): bool { if ($this->fail) { return false; } $this->sent[] = [$sender, $message]; return true; } + public function LobbyMessage(string $message, string $sender): bool { if ($this->fail) { return false; } $this->lobbySent[] = [$sender, $message]; return true; } } $civ = (new ReflectionClass(RelayCiv::class))->newInstanceWithoutConstructor(); $civ->owner_id = 'owner'; $civ->role_ids = ['Banished' => 'banished-role']; $civ->bans = ['bannedckey']; $civ->ooc_badwords = [['word' => 'badword', 'method' => 'exact', 'category' => 'toxic']]; $civ->verifier = (new ReflectionClass(RelayVerifier::class))->newInstanceWithoutConstructor(); $nomads = (new ReflectionClass(RelayServer::class))->newInstanceWithoutConstructor(); $nomads->ooc = 'ooc-nomads'; +$nomads->lobby = 'lobby-nomads'; $tdm = (new ReflectionClass(RelayServer::class))->newInstanceWithoutConstructor(); $tdm->ooc = 'ooc-tdm'; // A secondary shard region (the TDM battle world) shares the Barracks' OOC channel and is listed first on purpose. -$battle = (new ReflectionClass(RelayServer::class))->newInstanceWithoutConstructor(); $battle->ooc = 'ooc-tdm'; $battle->shardOf = 'tdm'; +$battle = (new ReflectionClass(RelayServer::class))->newInstanceWithoutConstructor(); $battle->ooc = 'ooc-tdm'; $battle->lobby = 'lobby-nomads'; $battle->shardOf = 'tdm'; $civ->enabled_gameservers = ['nomads' => $nomads, 'tdmbattle' => $battle, 'tdm' => $tdm]; $manager = (new ReflectionClass(\Civ13\MessageServiceManager::class))->newInstanceWithoutConstructor(); $manager->civ13 = $civ; $guild = (object) ['owner_id' => 'owner', 'members' => new RelayLookup(['20' => (object) ['nick' => 'Taislin']]), 'channels' => new RelayLookup(['77' => (object) ['name' => 'rules']])]; @@ -117,6 +120,13 @@ public function OOCMessage(string $message, string $sender): bool { if ($this->f $manager->relayOocMessage($message(['channel_id' => 'ooc-tdm', 'content' => 'tdm chat'])); check($tdm->sent === [['valckey', 'tdm chat']], 'Second server channel not routed'); check($battle->sent === [], 'Discord OOC reached a secondary shard region instead of its parent'); +// The lobby channel reaches the join screen only, never OOC, and never a secondary shard region. +$manager->relayOocMessage($message(['channel_id' => 'lobby-nomads', 'content' => 'welcome <@20>', 'mentions' => [RelayUser::with('20')]])); +check($nomads->lobbySent === [['valckey', 'welcome @Taislin']] && count($nomads->sent) === 2, 'Lobby channel message not relayed to the join screen only'); +check($battle->lobbySent === [] && $tdm->lobbySent === [], 'Lobby message reached another world'); +$banished = $message(['channel_id' => 'lobby-nomads', 'author' => RelayUser::with('11', false)]); $manager->relayOocMessage($banished); +check(count($nomads->lobbySent) === 1, 'Banned member reached the join screen'); +$nomads->sent = []; $nomads->lobbySent = []; $nomads->sent = []; foreach ([ 'other channel' => ['channel_id' => 'general'], @@ -135,5 +145,17 @@ public function OOCMessage(string $message, string $sender): bool { if ($this->f } $nomads->fail = true; $failed = $message(); $manager->relayOocMessage($failed); check($failed->reactions === ['🔥'], 'Failed IPC write not reported'); +$failedLobby = $message(['channel_id' => 'lobby-nomads']); $manager->relayOocMessage($failedLobby); +check($failedLobby->reactions === ['🔥'] && $nomads->lobbySent === [], 'Failed lobby IPC write not reported'); + +// The real writer frames lobby lines for SQL/discord2lobby.txt like OOC. +$dir = sys_get_temp_dir().'/civilizationbot-lobby-'.bin2hex(random_bytes(6)); mkdir($dir.'/SQL', 0700, true); +try { + $real = (new ReflectionClass(\Civ13\GameServer::class))->newInstanceWithoutConstructor(); $real->enabled = true; (new ReflectionProperty(\Civ13\GameServer::class, 'basedir'))->setValue($real, $dir); + check($real->LobbyMessage(OocAutoRelay::format("hi\nthere:::x"), 'valckey'), 'Lobby IPC write failed'); + check(file_get_contents($dir.\Civ13\Civ13::discord2lobby) === "valckey:::hi there: : :x\n", 'Lobby IPC record wrong: '.json_encode(file_get_contents($dir.\Civ13\Civ13::discord2lobby))); +} finally { + @unlink($dir.'/SQL/discord2lobby.txt'); @rmdir($dir.'/SQL'); @rmdir($dir); +} echo "OOC auto-relay checks passed\n";