Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/local-profile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions src/Civ13/Civ13.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
11 changes: 11 additions & 0 deletions src/Civ13/GameServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down
74 changes: 53 additions & 21 deletions src/Civ13/HttpServiceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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(
Expand Down
17 changes: 14 additions & 3 deletions src/Civ13/MessageServiceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Expand Down Expand Up @@ -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;
}

Expand Down
78 changes: 78 additions & 0 deletions tests/local/lobby-webhook.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
<?php
declare(strict_types=1);
// Join-screen relay: lobby chat and arrival notices reach the lobby channel, offline.
require $argv[1] ?? __DIR__.'/../../vendor/autoload.php';
require __DIR__.'/../../src/Civ13/Civ13.php';
require __DIR__.'/../../src/Civ13/GameServer.php';
require __DIR__.'/../../src/Civ13/HttpServiceManager.php';
require_once __DIR__.'/../../src/Civ13/Verifier.php';
require_once __DIR__.'/../../src/Civ13/Moderator.php';
use React\Http\Message\ServerRequest;
use React\Promise\PromiseInterface;
use function React\Promise\resolve;
function check(bool $ok, string $message): void { if (!$ok) { throw new RuntimeException($message); } }
final class LobbyDiscord extends \Discord\Discord {
public bool $found = true;
public function getChannel($channel_id): ?\Discord\Parts\Channel\Channel { return $this->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 &amp; <b>welcome</b>']) === 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";
24 changes: 23 additions & 1 deletion tests/local/ooc-auto-relay.php
Original file line number Diff line number Diff line change
Expand Up @@ -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']])];
Expand All @@ -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'],
Expand All @@ -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";
Loading