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
2 changes: 2 additions & 0 deletions .github/workflows/local-profile.yml
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ jobs:
- run: php -d memory_limit=128M tests/local/game-ready-http.php vendor/autoload.php
timeout-minutes: 2
- run: php tests/local/ingame-verification.php vendor/autoload.php
- run: php tests/local/voice-lobbies.php vendor/autoload.php
- name: Ckeyinfo loopback identity contracts (offline)
timeout-minutes: 2
run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/ckeyinfo-loopback.php vendor/autoload.php
Expand Down Expand Up @@ -170,6 +171,7 @@ jobs:
- run: php -d memory_limit=128M -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,stream_socket_server,stream_socket_accept,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/game-ready-http.php vendor/autoload.php
timeout-minutes: 2
- run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/ingame-verification.php vendor/autoload.php
- run: php -d allow_url_fopen=0 -d disable_functions=fsockopen,pfsockopen,stream_socket_client,curl_exec,curl_multi_exec,socket_create,exec,shell_exec,system,passthru,proc_open,popen tests/local/voice-lobbies.php vendor/autoload.php
windows-exe-smoke:
if: github.event_name == 'workflow_dispatch' && inputs.native_smoke
runs-on: windows-latest
Expand Down
26 changes: 26 additions & 0 deletions docs/launcher-voice.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Launcher voice lobbies

Bot side of Civ13 launcher voice (Civ13 issue #5122, Phase 3). The game side
is Civ13 `code/modules/voice/voice_chat.dm`, and the design is in Civ13
`docs/launcher-voice-plan.md`. The code is `src/Civ13/VoiceLobbies.php`.

- `POST /webhook/<server>/voice_roster` (whitelisted; `X-Webhook-Key`): the
game's `{v: 1, members: [{ckey, key, team}]}`. The answer is
`{ids: {ckey: Discord user ID}}` for every ckey that has an account so far.
- Each ckey gets a Discord provisional account through
`partner-sdk/token/bot`, with external user ID `byond:<ckey>`. Players need
no Discord login. Tokens live only in memory.
- One lobby per world (`civ13_kind: region`) and one per team
(`civ13_kind: team`, `civ13_team`), created with the bot token. Members
follow the roster. A player who drops out of it is removed after 30
seconds; their launcher key stops working at once.
- `POST /voice/token` (public, 30 per minute per address):
`{id: sha256("civ13-voice-token:" + key)}`. The answer is 202 until the
token exists, then `{v: 1, sealed}`. `sealed` is base64(nonce | ciphertext |
tag) under AES-256-GCM, with key `HKDF-SHA256(key, info "civ13-voice-seal")`
and the token ID as AAD. It opens to `{application_id, server, user_id,
access_token, expires_in}`.

Needs the Social SDK enabled on the bot's own application in the Discord
Developer Portal (the launcher uses the `application_id` it is given).
Offline contracts: `php tests/local/voice-lobbies.php vendor/autoload.php`.
96 changes: 96 additions & 0 deletions src/Civ13/HttpServiceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ class HttpServiceManager
protected array $dwa_discord_ids = [];
private ?Directory $launcherDirectory = null;
private ?GameReady $gameReady = null;
private ?VoiceLobbies $voiceLobbies = null;
private ?TimerInterface $launcherDirectoryTimer = null;

/** @param Civ13 $civ13 The bot instance; builds the {@see HttpHandler} and binds `discord`/`logger` by reference. */
Expand Down Expand Up @@ -350,6 +351,90 @@ public function handleShutdownNoticeWebhook(ServerRequestInterface $request, Gam
return new HttpResponse(HttpResponse::STATUS_ACCEPTED);
}

/**
* Launcher voice (Civ13 code/modules/voice/voice_chat.dm): the game POSTs its voice roster as
* JSON with the webhook key in X-Webhook-Key, and gets back {ids: {ckey: Discord user ID}}.
* See {@see VoiceLobbies}.
*/
public function handleVoiceRosterWebhook(ServerRequestInterface $request, GameServer $gameserver): HttpResponse
{
$secret = $this->civ13->options['http_key'] ?? '';
$key = $request->getHeaderLine('X-Webhook-Key');
if (!is_string($secret) || $secret === '' || $key === '' || !hash_equals($secret, $key) || $gameserver->legacy_relay) {
return new HttpResponse(HttpResponse::STATUS_FORBIDDEN);
}
if ($request->getMethod() !== 'POST') {
return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED);
}
$body = (string) $request->getBody();
$data = strlen($body) <= 131072 ? json_decode($body, true, 5) : null;
if (($members = VoiceLobbies::parseRoster($data)) === null) {
return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST);
}
if (!$voice = $this->voiceLobbies()) {
return new HttpResponse(HttpResponse::STATUS_SERVICE_UNAVAILABLE);
}

return HttpResponse::json(['ids' => (object) $voice->roster($gameserver->key, $members)]);
}

/**
* Launcher voice: the launcher POSTs {id: sha256("civ13-voice-token:" + key)} and gets its
* Discord access token sealed with a key only it and the game know (202 while it is minted).
*/
public function handleVoiceToken(ServerRequestInterface $request): HttpResponse
{
if ($request->getMethod() !== 'POST') {
return new HttpResponse(HttpResponse::STATUS_METHOD_NOT_ALLOWED);
}
$body = (string) $request->getBody();
$data = strlen($body) <= 256 ? json_decode($body, true, 2) : null;
$id = is_array($data) ? ($data['id'] ?? null) : null;
if (!is_string($id) || preg_match('/^[0-9a-f]{64}$/D', $id) !== 1) {
return new HttpResponse(HttpResponse::STATUS_BAD_REQUEST);
}
$sealed = $this->voiceLobbies()?->token($id);

return $sealed === null
? HttpResponse::json(['v' => 1, 'ready' => false])->withStatus(HttpResponse::STATUS_ACCEPTED)
: HttpResponse::plaintext($sealed)->withHeader('Content-Type', 'application/json');
}

/** The voice service, made on first use once the bot knows its application. */
private function voiceLobbies(): ?VoiceLobbies
{
if ($this->voiceLobbies !== null) {
return $this->voiceLobbies;
}
$application = $this->discord->application->id ?? null;
if (!is_string($application) || $application === '') {
return null;
}
$discord = $this->discord;

return $this->voiceLobbies = new VoiceLobbies(
mint: static fn (string $ckey): PromiseInterface => $discord->getHttpClient()->post(\Discord\Http\Endpoint::PARTNER_SDK_TOKEN_BOT, [
'external_user_id' => 'byond:'.$ckey,
'preferred_global_name' => $ckey,
]),
createLobby: static fn (array $metadata): PromiseInterface => $discord->lobbies->createLobby([
'metadata' => $metadata,
'idle_timeout_seconds' => VoiceLobbies::IDLE_TIMEOUT,
])->then(static fn ($lobby) => (string) $lobby->id),
// Resolves to the user IDs Discord confirmed as added or updated.
updateMembers: static fn (string $lobby, array $members): PromiseInterface => $discord->lobbies->bulkUpdateMembers($lobby, $members)
->then(static function ($confirmed): array {
$ids = [];
foreach ($confirmed as $member) {
$ids[] = (string) ($member->id ?? '');
}

return $ids;
}),
applicationId: $application,
);
}

/**
* In-game verification (Civ13 code/modules/client/discord_verify.dm): the game POSTs the
* player's ckey and the code they typed as JSON, with the webhook key in the X-Webhook-Key
Expand Down Expand Up @@ -1377,6 +1462,12 @@ function sendGetRequest(endpoint) {
fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleInGameVerifyRelay($request),
false
)
->offsetSet(
'/voice/token', // Launcher voice: sealed Discord token for a voice key (VoiceLobbies)
fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleVoiceToken($request),
false
)
->setRateLimit('/voice/token', 30, 60)
->offsetSet(
'/ss14verified',
fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => ($this->civ13->ss14verifier === null ? HttpResponse::json(['error' => 'SS14 verification unavailable'])->withStatus(503) : HttpResponse::json($this->civ13->ss14verifier->toArray())),
Expand Down Expand Up @@ -1740,6 +1831,11 @@ function (ServerRequestInterface $request, string $endpoint, bool $whitelisted)
fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleDiscordVerifyWebhook($request, $gameserver),
true
)
->offsetSet(
$server_endpoint.'/voice_roster',
fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => $this->handleVoiceRosterWebhook($request, $gameserver),
true
)
->offsetSet(
$server_endpoint.'/respawn_notice',
function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { // NYI
Expand Down
2 changes: 1 addition & 1 deletion src/Civ13/Verifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,7 @@ protected function discordName(string $discord_id): string
public static function plainMessage(string $message): string
{
$message = preg_replace('/<@[&!]?[0-9]+>/', 'staff', $message) ?? '';
$message = str_replace(['`', '**', PHP_EOL], ['', '', ' '], $message);
$message = str_replace(['`', '**', "\r\n", "\r", "\n"], ['', '', ' ', ' ', ' '], $message);

return mb_substr(trim($message), 0, 400);
}
Expand Down
Loading
Loading