diff --git a/.github/workflows/local-profile.yml b/.github/workflows/local-profile.yml index 73d2d395..567bd07c 100644 --- a/.github/workflows/local-profile.yml +++ b/.github/workflows/local-profile.yml @@ -108,6 +108,7 @@ jobs: - run: php tests/local/controls.php - run: php tests/local/gaia-host.php vendor/autoload.php - run: php tests/local/shard-region.php vendor/autoload.php + - run: php tests/local/tdm-group-configuration.php - run: php tests/local/systemd-unit.php vendor/autoload.php - run: php tests/local/server-compatibility.php vendor/autoload.php timeout-minutes: 2 diff --git a/bot.php b/bot.php index c0dff759..22914852 100644 --- a/bot.php +++ b/bot.php @@ -446,48 +446,14 @@ function loadEnv(string $filePath, bool $explicit = false): array 'attack' => '1139614643954921593', ], ]; -// Sharded TDM (docs/shard-group.md): the always-on Barracks world (region "barracks", port 1714) and the battle -// world (region "battle", port 1715) of Civ13 shard group "tdm", both driven by shard_group.py. Until the group's -// config exists the single civ13-tdm.service server above stays in use, so this file can ship before the move. -$tdm_group = '/home/civ13/tdm.json'; -if (is_file($tdm_group)) { - // The script lives in the group's own Civ13 checkout ("repository" in tdm.json), which the host keeps current. - $tdm_repository = json_decode((string) file_get_contents($tdm_group), true)['repository'] ?? null; - $tdm_script = is_string($tdm_repository) && $tdm_repository !== '' ? rtrim($tdm_repository, '/').'/scripts/shard-group/shard_group.py' : ''; - $tdm_shard_group = static fn (string $region): array => [ - 'enabled' => true, - 'python' => '/usr/bin/python3', - 'script' => $tdm_script, // empty or missing: host controls refuse with the reason - 'config' => $tdm_group, - 'region' => $region, - 'kill' => 'stop', // save if the world saves, then stop; 'kill' forces it down without saving - ]; - unset($civ13_server_settings['tdm']['systemd']); - // "tdm" is the group's front door, the world on port 1714 that posts to /webhook/tdm: the Barracks, or the - // gateway once `shard_group.py set-gate` puts one in front. Follow it like a portable profile's - // follow_front_door (basedir, and the shared front-door/SQL/admins.txt), so a gate move needs only a bot - // restart. An unreadable group file or a front door that is not set up keeps the Barracks. - $tdm_front = \Civ13\PortableProfile::followFrontDoor(['region_group' => $tdm_group, 'basedir' => '/home/civ13/tdm/barracks']); - $civ13_server_settings['tdm']['basedir'] = $tdm_front['basedir']; - if (isset($tdm_front['admin_file'])) { - $civ13_server_settings['tdm']['admin_file'] = $tdm_front['admin_file']; - } - $civ13_server_settings['tdm']['shard_group'] = $tdm_shard_group(basename($tdm_front['basedir'])); - $civ13_server_settings['tdm']['region_group'] = $tdm_group; // the player-count channel counts every region - // Battle posts to /webhook/tdmbattle and shares the TDM channels. It never renames the player-count channel - // (the front door counts it) but keeps its own round embed there; Discord OOC goes to the front door only, - // which shares it with the other worlds in game (Civ13 region OOC). - $civ13_server_settings['tdmbattle'] = array_merge($civ13_server_settings['tdm'], [ - 'supported' => false, // hidden from the hub - 'name' => 'TDM Battle', - 'port' => '1715', - 'basedir' => '/home/civ13/tdm/battle', - 'shard_group' => $tdm_shard_group('battle'), - 'shard_of' => 'tdm', - ]); - // Battle keeps the inherited TDM Play link, so its round embed in the TDM channel enters through the front door - // too; the aggregate status skips shards (shard_of), so it still shows one TDM button. - unset($civ13_server_settings['tdmbattle']['region_group']); +// Use one validated snapshot for the official front door and Battle. A configured +// group that cannot be read must never put the old single-world service back in use. +try { + $civ13_server_settings = array_replace($civ13_server_settings, + \Civ13\Local\TdmGroupConfiguration::profiles('/home/civ13/tdm.json', $civ13_server_settings['tdm'])); +} catch (\UnexpectedValueException $error) { + unset($civ13_server_settings['tdm'], $civ13_server_settings['tdmbattle']); + $logger->error('TDM integrations disabled: '.$error->getMessage()); } foreach ($civ13_server_settings as $key => $value) { $civ13_server_settings[$key]['key'] = $key; diff --git a/docs/local-profile.md b/docs/local-profile.md index d95af054..bf57b519 100644 --- a/docs/local-profile.md +++ b/docs/local-profile.md @@ -40,6 +40,8 @@ The local endpoint permits only authenticated `GET /v1/verification-replica`, ma ## Supervision and remaining limits +Bot code, dependency updates and bot restarts belong to the installation operator, not Discord or the bot's HTTP server. Deploy a reviewed revision and run `composer install` from its lockfile in the operator's deployment procedure; then manage the bot process using the installation's service supervisor. The staff dashboard no longer offers Git or Composer actions. Stale `/pull` and `/update` interactions and the old `updatedeps` and `stop` text commands do not execute anything. The old maintenance HTTP routes return `410 Gone` to admitted callers (`/githubupdated` still rejects missing or invalid signatures); remove update webhooks targeting that route. `ts` no longer manages the TypeSpess process; use the TypeSpess host's operator procedure. These changes do not retire game-server controls. + Legacy restart remains the default. Explicit `restart_mode:supervised` stops the current bot gracefully and leaves replacement to its supervisor; it never self-spawns PHP. Repeated requests stop once, and selecting another entry point is rejected. Games need independently supervised fixed units/scopes and narrowly reviewed helper permissions. A bot unit using KillMode=control-group can kill game descendants launched by legacy PHP. Nohup/disown do not detach cgroups. KillMode=process leaves child ownership/orphan risks and requires a separate reviewed compatibility decision. Replica publication uses a private lock, staged file flush/fsync and same-directory rename. Tests cover process interruption before publication and lock exclusion. They do not prove power-loss directory fsync ordering, hostile-owner filesystem races, production exporter consistency, multiweek freshness or actual guild permissions. No official cutover or live activation is included. diff --git a/docs/shard-group.md b/docs/shard-group.md index 05b67753..9097a43e 100644 --- a/docs/shard-group.md +++ b/docs/shard-group.md @@ -5,11 +5,37 @@ own worktree with its own port, `serverdata.txt`, IPC files and webhooks (see Civ13's `scripts/shard-group/README.md`). The bot treats each region as a normal game server entry and drives it with `scripts/shard-group/shard_group.py`. -civ13.com's TDM is the first such group: shard group `tdm` with the always-on -**Barracks** (region `barracks`, port 1714, server key `tdm`) and the **battle** -world (region `battle`, port 1715, server key `tdmbattle`). `bot.php` switches -to it by itself once `/home/civ13/tdm.json` exists; until then the single -`civ13-tdm.service` server stays in use. +For civ13.com's TDM, `bot.php` reads one validated `/home/civ13/tdm.json` +snapshot. The `tdm` entry follows the configured front door (Barracks or +gateway), and `tdmbattle` follows the configured Battle region. Each uses its +actual region directory and port. Battle keeps the public TDM Play link and +does not produce another aggregate Play button. A genuinely absent group file +keeps legacy single-world status only; an invalid configured file disables +the TDM integrations rather than falling back to the wrong service. + +The official TDM aliases are **status-only for lifecycle management**. +`tdmrestart` previously acted on the front door, including the gateway. +`tdmbattlerestart` only acted on Battle. The old host, kill, restart, update, +and map-swap handlers now refuse for these entries across text, slash, and +panel surfaces. Use the maintainer runbook, not a Discord alias. + +### TDM operator checks + +1. Fast-forward the configured shared TDM source checkout, and reload the + `civ13-tdm-host` service. This refreshes the coordinator, not the separate + running world processes. +2. Use the coordinator's group `restart` **without a region argument**. + Expect all intended non-gateway regions under `accepted`. When a gateway + exists, the coordinator deliberately lists it under `refused` with the + reason that it stays on its port. Treat any other refusal as a failure, + even when the aggregate reply says `ok`. +3. Check the worlds and hub listing after they finish. An accepted operation + is queued, not proof they are ready. Restart the gateway by name only + when deliberately updating the front door. + +The bot itself is updated by fast-forwarding its own checkout and restarting +the operator-managed `civilizationbot` unit. The bot no longer runs these +updates or restarts through its retired maintenance commands. ## Host controls @@ -36,8 +62,8 @@ DreamDaemon itself. | Discord | shard_group.py | | --- | --- | | `host`, panel Host | `start --region=` | -| `kill`, panel Kill | `stop --region=` (or `kill`, see above), announced in OOC first | -| `restart`, panel Restart, `/restart_server` | `restart --region=`, announced in OOC first | +| `kill`, panel Kill | `stop --region=` (or `kill`, see above) | +| `restart`, panel Restart, `/restart_server` | `restart --region=` | | `update` | `update --region=` | | `hoststatus` | `status --region=`: region name, port, world ready, players, last action, map | | `activity` (Ambassador, Admin) | none: reads `/player-activity-weekly.json` from the server's `region_group` | @@ -57,7 +83,13 @@ per ckey whenever that ckey's karma changes; the bot never opens its database. start, stop, restart and update are accepted within seconds and finish in the script's detached worker; `hoststatus` shows progress. The bot runs as the same user as the group (`civ13`), so no sudo is involved. Roles are the same as for -[gaia_host](gaia-host.md). +[gaia_host](gaia-host.md). A frozen region may accept an update as build staging; +its running version has not changed. The table describes explicitly managed +non-TDM entries that have not retired their legacy aliases. + +Awards belong to the world that writes them. Do not use an empty awards file +on the gateway as a substitute for the awarding world. Missing awards now +leave the ranking unchanged rather than creating a placeholder or wiping it. ## Following the front door (`follow_front_door`) diff --git a/src/Civ13/GameServer.php b/src/Civ13/GameServer.php index fa7d1525..de446f9f 100644 --- a/src/Civ13/GameServer.php +++ b/src/Civ13/GameServer.php @@ -17,7 +17,6 @@ use Civ13\Exceptions\InvalidConfigException; use Civ13\Exceptions\MissingSystemPermissionException; use Civ13\Exceptions\PartException; -use Civ13\Exceptions\UserInputException; use Civ13\Exceptions\VerifierException; use Discord\Discord; use Discord\Builders\Components\ActionRow; @@ -74,6 +73,7 @@ class GameServer public ?\Civ13\Local\LauncherManagement $launcherManagement = null; /** Set whenever management is enabled, even if its configuration is invalid, so legacy lifecycle commands fail closed. */ private bool $launcherManagementRequired = false; + private bool $retireLegacyLifecycle = false; /** Host script control: gaia_host.py for a scheduled-task host, or shard_group.py for one region of a shard group. */ private \Civ13\Local\GaiaHostControl|\Civ13\Local\ShardRegionControl|null $gaiaHost = null; /** Set when shard_group is configured but unusable: host controls then refuse instead of launching DreamDaemon. */ @@ -233,6 +233,7 @@ public function __construct(public Civ13 &$civ13, array &$options) $this->hostUnavailable = $error->getMessage(); } } + $this->retireLegacyLifecycle = ($options['retire_legacy_lifecycle'] ?? false) === true; $this->launcherManagementRequired = ($options['shard_group']['management']['enabled'] ?? false) === true; // Additional launcher actions never inherit legacy role authority or implicit enablement. if (($options['shard_group']['management']['enabled'] ?? false) === true && $this->hostUnavailable === null && $this->gaiaHost instanceof \Civ13\Local\ShardRegionControl) { @@ -1077,102 +1078,64 @@ public function DirectMessage(string $message, string $sender, string $recipient { return $this->enabled && \Civ13\Server\Ipc::append($this->basedir.Civ13::discord2dm, [$sender, $recipient, $message]); } - /** - * Hosts the game server by executing necessary commands and setting up timers for hosting. - * - * @param Message|null $message An optional message object that can be used to react to the hosting action. - */ + /** All legacy entry points (text, slash, staff panels) share this guard. */ + private function legacyLifecycleBlockReason(): ?string + { + if ($this->retireLegacyLifecycle) { + return "Legacy lifecycle controls are retired for {$this->key}. Use the host operator runbook; {$this->key}hoststatus is read-only."; + } + if ($this->launcherManagementRequired || $this->launcherManagement !== null) { + return "Use {$this->key}manage with its per-action confirmation; legacy lifecycle controls are disabled for managed regions."; + } + return null; + } + + private function unavailableLifecycle(): PromiseInterface + { + return reject(new \RuntimeException('No supervised lifecycle control is configured. Use the host launcher or operator runbook.')); + } + + /** Request a start from this world's explicitly configured controller. */ public function Host(?Message $message = null): PromiseInterface { - if ($this->launcherManagementRequired || $this->launcherManagement !== null) { return reject(new \RuntimeException("Use {$this->key}manage with its per-action confirmation; legacy lifecycle controls are disabled for managed regions.")); } + if (($reason = $this->legacyLifecycleBlockReason()) !== null) { return reject(new \RuntimeException($reason)); } if ($this->engine === 'opendream') { return $this->requestEngineControl('start'); } if ($this->hostUnavailable !== null) { return reject(new \RuntimeException('shard_group control unavailable: '.$this->hostUnavailable)); } if ($this->gaiaHost !== null) { return $this->gaiaHostRequest('start', $message); } if (PHP_OS_FAMILY === 'Windows' || getenv('CIVILIZATIONBOT_PROFILE')) { return $this->nativeRequest('start', $message); } if ($this->systemdUnit !== null || $this->systemdUnavailable !== null) { return $this->systemdRequest('start', $message); } - OSFunctions::execInBackground("python3 {$this->basedir}".Civ13::updateserverabspaths); - if (file_exists($this->basedir.Civ13::serverdata)) { - OSFunctions::execInBackground("rm -f {$this->basedir}".Civ13::serverdata); - } - OSFunctions::execInBackground("python3 {$this->basedir}".Civ13::killsudos); - - if (! isset($this->civ13->timers["{$this->key}host"])) { - $this->civ13->timers["{$this->key}host"] = $this->civ13->discord->getLoop()->addTimer(30, function () use ($message) { - unset($this->civ13->timers["{$this->key}host"]); - $promise = OSFunctions::execInBackground("nohup DreamDaemon {$this->basedir}".Civ13::dmb." {$this->port} -trusted -webclient -logself > /dev/null 2>&1 & disown"); - if ($message) { - $message->react('👍'); - } - }); - } else { - $this->logger->info("Server host timer already exists for {$this->key}."); - } - return resolve(['accepted' => true, 'engine' => 'byond', 'state' => 'legacy operation scheduled']); + return $this->unavailableLifecycle(); } - /** Shuts the server down (via `killciv13`), optionally announcing it in OOC first. */ + + /** Request a stop. The controller, not the bot, handles world announcements. */ public function Kill(?Message $message = null, bool $notify = true): PromiseInterface { - if ($this->launcherManagementRequired || $this->launcherManagement !== null) { return reject(new \RuntimeException("Use {$this->key}manage with its per-action confirmation; legacy lifecycle controls are disabled for managed regions.")); } + if (($reason = $this->legacyLifecycleBlockReason()) !== null) { return reject(new \RuntimeException($reason)); } if ($this->engine === 'opendream') { return $this->requestEngineControl('stop'); } if ($this->hostUnavailable !== null) { return reject(new \RuntimeException('shard_group control unavailable: '.$this->hostUnavailable)); } - if ($this->gaiaHost instanceof \Civ13\Local\ShardRegionControl) { - if ($notify) { $this->OOCMessage("Server is shutting down. To get notified when we go live again, please join us on Discord at {$this->civ13->discord_formatted}", $this->civ13->discord->username ?? 'Server'); } - return $this->gaiaHostRequest($this->shardKillAction, $message); - } - if ($this->gaiaHost !== null) { - if ($notify) { $this->OOCMessage('The server is saving and shutting down. Your character will be here when it comes back.', $this->civ13->discord->username ?? 'Server'); } - return $this->gaiaHostRequest('stop', $message); - } + if ($this->gaiaHost instanceof \Civ13\Local\ShardRegionControl) { return $this->gaiaHostRequest($this->shardKillAction, $message); } + if ($this->gaiaHost !== null) { return $this->gaiaHostRequest('stop', $message); } if (PHP_OS_FAMILY === 'Windows' || getenv('CIVILIZATIONBOT_PROFILE')) { return $this->nativeRequest('save-stop', $message); } - if ($this->systemdUnit !== null || $this->systemdUnavailable !== null) { - if ($notify) { $this->OOCMessage("Server is shutting down. To get notified when we go live again, please join us on Discord at {$this->civ13->discord_formatted}", $this->civ13->discord->username ?? 'Server'); } - return $this->systemdRequest('stop', $message); - } - if ($notify) { - $sender = (string) ((($message && $message->user_id) ? ($this->civ13->verifier->getVerifiedItem($message->user_id)['ss13'] ?? null) : null) ?? $this->civ13->discord->username ?? 'Server'); - $this->OOCMessage("Server is shutting down. To get notified when we go live again, please join us on Discord at {$this->civ13->discord_formatted}", $sender); - } - $this->civ13->loop->addTimer(10, function () use ($message): void { - OSFunctions::execInBackground("python3 {$this->basedir}".Civ13::killciv13); - if ($message) { - $message->react('👍'); - } - }); - return resolve(['accepted' => true, 'engine' => 'byond', 'state' => 'legacy operation scheduled']); + if ($this->systemdUnit !== null || $this->systemdUnavailable !== null) { return $this->systemdRequest('stop', $message); } + return $this->unavailableLifecycle(); } - /** Kills the server and re-hosts it 20s later, optionally announcing the restart in OOC. */ + + /** Request a controller-owned restart, never a timer-based kill and rehost. */ public function Restart(?Message $message = null, bool $notify = true): PromiseInterface { - if ($this->launcherManagementRequired || $this->launcherManagement !== null) { return reject(new \RuntimeException("Use {$this->key}manage with its per-action confirmation; legacy lifecycle controls are disabled for managed regions.")); } + if (($reason = $this->legacyLifecycleBlockReason()) !== null) { return reject(new \RuntimeException($reason)); } if ($this->engine === 'opendream') { return $this->requestEngineControl('restart'); } if ($this->hostUnavailable !== null) { return reject(new \RuntimeException('shard_group control unavailable: '.$this->hostUnavailable)); } - if ($this->gaiaHost instanceof \Civ13\Local\ShardRegionControl) { - if ($notify) { $this->OOCMessage("Server is now restarting. To share your feedback or experiences for this round, please join us on Discord at {$this->civ13->discord_formatted}", $this->civ13->discord->username ?? 'Server'); } - return $this->gaiaHostRequest('restart', $message); - } - if ($this->gaiaHost !== null) { - if ($notify) { $this->OOCMessage('The server is saving and restarting. Your character will be here when it comes back.', $this->civ13->discord->username ?? 'Server'); } - return $this->gaiaHostRequest('restart', $message); - } + if ($this->gaiaHost !== null) { return $this->gaiaHostRequest('restart', $message); } if (PHP_OS_FAMILY === 'Windows' || getenv('CIVILIZATIONBOT_PROFILE')) { return $this->nativeRequest('restart', $message); } - if ($this->systemdUnit !== null || $this->systemdUnavailable !== null) { - if ($notify) { $this->OOCMessage("Server is now restarting. To share your feedback or experiences for this round, please join us on Discord at {$this->civ13->discord_formatted}", $this->civ13->discord->username ?? 'Server'); } - return $this->systemdRequest('restart', $message); - } - $this->Kill(null, false); - $this->civ13->loop->addTimer(20, function () use ($message): void { - $this->Host($message); - }); - if ($notify) { - $this->OOCMessage("Server is now restarting. To share your feedback or experiences for this round, please join us on Discord at {$this->civ13->discord_formatted}", $message ? ($this->civ13->verifier->getVerifiedItem($message->author)['ss13'] ?? $this->civ13->discord->username) : $this->civ13->discord->username); - } - return resolve(['accepted' => true, 'engine' => 'byond', 'state' => 'legacy operation scheduled']); + if ($this->systemdUnit !== null || $this->systemdUnavailable !== null) { return $this->systemdRequest('restart', $message); } + return $this->unavailableLifecycle(); } - /** Pulls and compiles master while the server is stopped (gaia_host and shard_group hosts only). */ + /** Ask the configured host to update or stage its configured revision. */ public function Update(?Message $message = null): PromiseInterface { - if ($this->launcherManagementRequired || $this->launcherManagement !== null) { return reject(new \RuntimeException("Use {$this->key}manage with its per-action confirmation; legacy lifecycle controls are disabled for managed regions.")); } + if (($reason = $this->legacyLifecycleBlockReason()) !== null) { return reject(new \RuntimeException($reason)); } if ($this->hostUnavailable !== null) { return reject(new \RuntimeException('shard_group control unavailable: '.$this->hostUnavailable)); } if ($this->gaiaHost === null) { return reject(new \RuntimeException('Updating is only available for a gaia_host or shard_group server')); } return $this->gaiaHostRequest('update', $message); @@ -1222,44 +1185,12 @@ private function nativeRequest(string $action, ?Message $message): PromiseInterf return $result; }); } - /** - * Swaps the current map to the specified map. - * - * @param string $mapto The name of the map to switch to. - * @param string $admin The name of the admin requesting the map swap. - * @return PromiseInterface A promise that resolves with a success message or rejects with an error message. - */ + /** Only an existing typed map controller may accept a map change. */ public function MapSwap(string $mapto, string $admin): PromiseInterface { + if (($reason = $this->legacyLifecycleBlockReason()) !== null) { return reject(new \RuntimeException($reason)); } if ($this->engine === 'opendream') { return $this->requestEngineControl('mapswap', $mapto); } - if (PHP_OS_FAMILY === 'Windows' || getenv('CIVILIZATIONBOT_PROFILE')) { return reject(new \RuntimeException('Native map control is unavailable on Windows')); } - $mapto = strtoupper($mapto); - if (! file_exists($fp = $this->civ13->gitdir.Civ13::maps) || ! $file = @fopen($fp, 'r')) { - $this->logger->error($err = "Unable to open `$fp` for reading."); - - return reject(new FileNotFoundException($err)); - } - - $maps = []; - while (($fp = fgets($file, 4096)) !== false) { - $linesplit = explode(' ', trim(str_replace('"', '', $fp))); - if (isset($linesplit[2]) && $map = trim($linesplit[2])) { - $maps[] = $map; - } - } - fclose($file); - if (! in_array($mapto, $maps)) { - return reject(new UserInputException("`$mapto` was not found in the map definitions.")); - } - - $this->OOCMessage($msg = "Server is now changing map to `$mapto`.", $this->civ13->verifier->getVerifiedItem($admin)['ss13'] ?? $this->civ13->discord->username); - if ($channel = $this->civ13->discord->getChannel($this->discussion)) { - $msg = (isset($this->civ13->role_ids['mapswap']) ? "<@&{$this->civ13->role_ids['mapswap']}>, " : '')."{$this->name} $msg"; - $channel->sendMessage($msg); - } - $this->loop->addTimer(10, fn () => OSFunctions::execInBackground("python3 {$this->basedir}".Civ13::mapswap." $mapto")); - - return resolve($msg); + return reject(new \RuntimeException('Legacy map swaps are retired. Use the world operator runbook or in-game map voting.')); } /** All normal message/slash callers use this adapter, with no native fallback. */ @@ -1947,11 +1878,9 @@ public function getRound(string $game_id): array public function getRank(string $ckey): string { $line_array = []; - $return = ''; - if (! @touch($this->ranking_path) || ! $search = @fopen($this->ranking_path, 'r')) { - $this->logger->warning($return = "Unable to open `{$this->ranking_path}`"); - - return $return; + if (! $search = @fopen($this->ranking_path, 'r')) { + $this->logger->warning("Unable to open ranking for {$this->key}"); + return 'Ranking is unavailable for this world.'; } while (($fp = fgets($search, 4096)) !== false) { $line_array[] = $fp; @@ -1982,8 +1911,8 @@ public function getRank(string $ckey): string */ public function getRanking(): PromiseInterface { - if (! @touch($path = $this->basedir.Civ13::ranking_path) || ! $search = @fopen($path, 'r')) { - return reject(new MissingSystemPermissionException("Unable to open `$path`")); + if (! $search = @fopen($this->basedir.Civ13::ranking_path, 'r')) { + return reject(new MissingSystemPermissionException('Ranking is unavailable for this world.')); } $line_array = []; @@ -2009,7 +1938,7 @@ public function getRanking(): PromiseInterface * @throws MissingSystemPermissionException If the awards or ranking files cannot be accessed or written to. * * The function performs the following steps: - * 1. Attempts to touch the awards and ranking files to ensure they are accessible. + * 1. Requires an existing awards file for this world. * 2. Reads the awards file line by line, skipping empty lines. * 3. Parses each line to extract user data and their corresponding medals. * 4. Calculates the score for each user based on their medals using predefined medal scores. @@ -2018,14 +1947,10 @@ public function getRanking(): PromiseInterface */ public function recalculateRanking(): PromiseInterface { - if (! @touch($awards = $this->basedir.Civ13::awards)) { - return reject(new MissingSystemPermissionException("Unable to access `{$awards}`")); - } - if (! @touch($ranking_path = $this->basedir.Civ13::ranking_path)) { - return reject(new MissingSystemPermissionException("Unable to access `{$ranking_path}`")); - } - if (($lines = file($awards, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) === false) { - return reject(new MissingSystemPermissionException("Unable to read `$awards`")); + $awards = $this->basedir.Civ13::awards; + $ranking_path = $this->basedir.Civ13::ranking_path; + if (! is_file($awards) || ($lines = @file($awards, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)) === false) { + return reject(new MissingSystemPermissionException('No readable awards source is configured for this world.')); } $result = []; foreach ($lines as $line) { diff --git a/src/Civ13/HttpServiceManager.php b/src/Civ13/HttpServiceManager.php index 799a5488..9d72650d 100644 --- a/src/Civ13/HttpServiceManager.php +++ b/src/Civ13/HttpServiceManager.php @@ -19,7 +19,6 @@ use Civ13\ServerDirectory\Endpoint as DirectoryEndpoint; use Discord\Discord; use Discord\DiscordWebAuth; -use Discord\Parts\Channel\Message; use Discord\Parts\User\Member; use Monolog\Logger; use Psr\Http\Message\ResponseInterface; @@ -1044,29 +1043,16 @@ function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): ? new HttpResponse(HttpResponse::STATUS_OK, ['Content-Type' => 'image/x-icon', 'Cache-Control' => 'public, max-age=2592000'], $favicon) : new HttpResponse(HttpResponse::STATUS_NOT_FOUND, ['Content-Type' => 'text/plain'], 'Unable to access `favicon.ico`') ) - // HttpHandler management endpoints - ->offsetSet( - '/reset', - function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { - if (!OSFunctions::legacyShellAvailable()) { - return HttpResponse::plaintext('Legacy maintenance is unavailable in Windows/portable mode.')->withStatus(HttpResponse::STATUS_SERVICE_UNAVAILABLE); - } - OSFunctions::execInBackground('git reset --hard origin/main'); - $message = 'Forcefully moving the HEAD back to origin/main...'; - if (isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - $this->civ13->sendMessage($channel, $message); - } - - return HttpResponse::plaintext($message); - }, + // Retain the old routes' admission policy without allowing bot self-maintenance. + ->offsetSets( + ['/reset', '/pull', '/update', '/restart', '/kill', '/clearenv'], + static fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => + HttpResponse::plaintext('Bot self-maintenance is retired. Use the operator-managed deployment procedure or service supervisor.')->withStatus(HttpResponse::STATUS_GONE), true ) ->offsetSet( '/githubupdated', function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { - if (!OSFunctions::legacyShellAvailable()) { - return HttpResponse::plaintext('Legacy maintenance is unavailable in Windows/portable mode.')->withStatus(HttpResponse::STATUS_SERVICE_UNAVAILABLE); - } $secret = (string) getenv('github_secret'); $body = strval($request->getBody()); // Prefer the SHA-256 signature GitHub sends; fall back to SHA-1. @@ -1088,135 +1074,16 @@ function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): 'secret_configured' => $secret !== '', ]); $this->logger->warning("Rejected unsigned/invalid webhook on `$endpoint`: $meta"); - $tech_ping = isset($this->civ13->technician_id) ? "<@{$this->civ13->technician_id}>, " : ''; - if (isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - $this->civ13->sendMessage($channel, $tech_ping."Rejected unsigned/invalid webhook on `$endpoint` endpoint."); - } - return new HttpResponse(HttpResponse::STATUS_UNAUTHORIZED); } - if (! $channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - return HttpResponse::plaintext('Discord Channel Not Found')->withStatus(HttpResponse::STATUS_INTERNAL_SERVER_ERROR); - } - $promise = isset($this->civ13->restart_message) && $this->civ13->restart_message instanceof Message - ? $this->civ13->restart_message->edit(Civ13::createBuilder()->setContent('Updating code from GitHub... (1/2)')) - : $this->civ13->sendMessage($channel, 'Updating code from GitHub... (1/2)'); - $promise->then(fn (Message $message) => OSFunctions::execInBackground('git pull')); - $this->discord->getLoop()->addTimer( - 5, - fn (): PromiseInterface => $promise - ->then(static fn (Message $message): PromiseInterface => $message->edit(Civ13::createBuilder()->setContent('Forcefully moving the HEAD back to origin/main... (2/2)'))) - ->then(fn (Message $message) => $this->civ13->restart_message = $message) - ->then(static fn () => OSFunctions::execInBackground('git reset --hard origin/main')) - /*if (isset($this->civ13->timers['restart_pending']) && $this->civ13->timers['restart_pending'] instanceof TimerInterface) $this->discord->getLoop()->cancelTimer($this->civ13->timers['restart_pending']); - $this->civ13->timers['restart_pending'] = $this->discord->getLoop()->addTimer(300, fn() => - (isset($this->civ13->restart_message) && $this->civ13->restart_message instanceof Message) - ? $this->civ13->restart_message->edit(Civ13::createBuilder()->setContent('Restarting...'))->then(fn() => $this->civ13->restart()) - : $this->civ13->sendMessage($channel, 'Restarting...')->then(fn() => $this->civ13->restart()) - );*/ - ); - return new HttpResponse(HttpResponse::STATUS_OK); + return HttpResponse::plaintext('Bot self-maintenance is retired. Use the operator-managed deployment procedure or service supervisor.')->withStatus(HttpResponse::STATUS_GONE); } ) ->offsetSet( '/cancelupdaterestart', - function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { - if (!OSFunctions::legacyShellAvailable()) { - return HttpResponse::plaintext('Legacy maintenance is unavailable in Windows/portable mode.')->withStatus(HttpResponse::STATUS_SERVICE_UNAVAILABLE); - } - if (isset($this->civ13->timers['restart_pending']) && $this->civ13->timers['restart_pending'] instanceof TimerInterface) { - $this->discord->getLoop()->cancelTimer($this->civ13->timers['restart_pending']); - unset($this->civ13->timers['restart_pending']); - if (isset($this->civ13->restart_message) && $this->civ13->restart_message instanceof Message) { - $this->civ13->restart_message->edit(Civ13::createBuilder()->setContent('Restart cancelled.')); - } - - return HttpResponse::plaintext('Restart cancelled.'); - } - - return HttpResponse::plaintext('No restart pending.'); - } - ) - ->offsetSet( - '/pull', - function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { - if (!OSFunctions::legacyShellAvailable()) { - return HttpResponse::plaintext('Legacy maintenance is unavailable in Windows/portable mode.')->withStatus(HttpResponse::STATUS_SERVICE_UNAVAILABLE); - } - OSFunctions::execInBackground('git pull'); - $message = 'Updating code from GitHub...'; - if (isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - $this->civ13->sendMessage($channel, $message); - } - - return HttpResponse::plaintext($message); - }, - true - ) - ->offsetSet( - '/update', - function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { - if (!OSFunctions::legacyShellAvailable()) { - return HttpResponse::plaintext('Legacy maintenance is unavailable in Windows/portable mode.')->withStatus(HttpResponse::STATUS_SERVICE_UNAVAILABLE); - } - OSFunctions::execInBackground('composer update'); - $message = 'Updating dependencies...'; - if (isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - $this->civ13->sendMessage($channel, $message); - } - - return HttpResponse::plaintext($message); - }, - true - ) - ->offsetSet( - '/restart', - function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { - if (!OSFunctions::legacyShellAvailable()) { - return HttpResponse::plaintext('Legacy maintenance is unavailable in Windows/portable mode.')->withStatus(HttpResponse::STATUS_SERVICE_UNAVAILABLE); - } - $message = 'Manually Restarting...'; - if (isset($this->civ13->restart_message) && $this->civ13->restart_message instanceof Message) { - $this->civ13->restart_message->edit(Civ13::createBuilder()->setContent('Manually Restarting...'))->then(fn () => $this->civ13->restart()); - - return HttpResponse::plaintext($message); - } - if (isset($this->civ13->channel_ids['staff_bot']) && $channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - $this->civ13->sendMessage($channel, $message)->then(fn () => $this->civ13->restart()); - } - - return HttpResponse::plaintext($message); - }, - true - ) - ->offsetSet( - '/kill', - function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { - if (!OSFunctions::legacyShellAvailable()) { - return HttpResponse::plaintext('Legacy maintenance is unavailable in Windows/portable mode.')->withStatus(HttpResponse::STATUS_SERVICE_UNAVAILABLE); - } - $message = 'Shutting down...'; - $this->discord->getLoop()->addTimer(3, fn () => $this->civ13->restart()); - - return HttpResponse::plaintext($message); - }, - true - ) - ->offsetSet( - '/clearenv', - function (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse { - if (!OSFunctions::legacyShellAvailable()) { - return HttpResponse::plaintext('Legacy maintenance is unavailable in Windows/portable mode.')->withStatus(HttpResponse::STATUS_SERVICE_UNAVAILABLE); - } - $message = 'Clearing .env...'; - if (file_exists($env = getcwd().'/.env')) { - file_put_contents($env, ''); - } - - return HttpResponse::plaintext($message); - }, - true + static fn (ServerRequestInterface $request, string $endpoint, bool $whitelisted): HttpResponse => + HttpResponse::plaintext('Bot self-maintenance is retired. Use the operator-managed deployment procedure or service supervisor.')->withStatus(HttpResponse::STATUS_GONE) ) ->offsetSet( '/updateadmins', diff --git a/src/Civ13/Local/LauncherManagement.php b/src/Civ13/Local/LauncherManagement.php index f29a5874..d0cfa8ec 100644 --- a/src/Civ13/Local/LauncherManagement.php +++ b/src/Civ13/Local/LauncherManagement.php @@ -52,7 +52,7 @@ public function handle(string $actor, string $guild, string $channel, string $in $action = $confirm ? ($parts[1] ?? '') : ($parts[0] ?? ''); if ($action === 'acknowledge' && count($parts) === ($confirm ? 3 : 1)) { return resolve($this->acknowledge($key, $confirm ? $parts[2] : null, $now)); } if (!in_array($action, $this->policy['actions'], true) || count($parts) !== ($confirm ? 3 : 1)) { return resolve('Unsupported or disabled action. Use manage help; arbitrary arguments are not supported.'); } - if ($this->busy || ($this->uncertain && $action !== 'status')) { return resolve('Management is busy or an earlier outcome is unknown. Inspect the host receipt locally, then clear the block with {$this->command} acknowledge; no automatic retry will occur.'); } + if ($this->busy || ($this->uncertain && $action !== 'status')) { return resolve("Management is busy or an earlier outcome is unknown. Inspect the host receipt locally, then clear the block with {$this->command} acknowledge; no automatic retry will occur."); } if ($action !== 'status') { if (!$confirm) { $token = bin2hex(random_bytes(12)); @@ -103,7 +103,8 @@ private function acknowledge(string $key, ?string $token, int $now): string private function unknown(string $action): string { $this->busy = false; - if ($action !== 'status') { $this->uncertain = true; } + if ($action === 'status') { return 'No verified host status. This does not mean the world stopped.'; } + $this->uncertain = true; return "No verified host result. Outcome may be unknown; inspect the local host receipt before retrying. New mutations are blocked until an operator runs {$this->command} acknowledge. No raw logs are disclosed."; } @@ -114,6 +115,7 @@ private function answer(string $action, array $result): string if (!is_array($data) || !is_bool($data['ok'] ?? null)) { throw new \UnexpectedValueException('Invalid host envelope'); } // Host prechecks refuse before acting, except force-restart: it can kill the world and then have its start refused. if (!$data['ok']) { + ShardRegionControl::regionRefusal($data, $this->region); if ($action === 'force-restart') { $this->uncertain = true; return "Host refused the request after it may have stopped the world. Inspect the local receipt and status, then clear the block with {$this->command} acknowledge."; @@ -122,25 +124,26 @@ private function answer(string $action, array $result): string } if ($result['exit_code'] !== 0) { throw new \UnexpectedValueException('Inconsistent exit'); } if ($action === 'status') { - $own = $data['regions'][$this->region] ?? null; - if (!is_array($own)) { throw new \UnexpectedValueException('Missing region'); } + $own = ShardRegionControl::singleRegionRecord($data['regions'] ?? null, $this->region); $state = in_array($own['state'] ?? '', ['awake', 'asleep', 'cold', 'stopped', 'frozen', 'running'], true) ? $own['state'] : 'unknown'; - $clients = $own['world']['clients'] ?? null; - $players = is_int($clients) && $clients >= 0 ? (string)$clients : 'unknown'; - $phase = $own['operation']['phase'] ?? null; - $phase = in_array($phase, ['accepted', 'done', 'failed', 'starting', 'started', 'stopping', 'stopped', 'building', 'fetching', 'saving', 'compiling', 'compiled', 'pulling', 'checking save', 'backing up', 'switching', 'rolling back', 'checking out', 'handed over'], true) ? $phase : 'unknown'; - $stage = $own['stage']['phase'] ?? null; - $stage = in_array($stage, ['accepted', 'checking for updates', 'current', 'ready', 'preparing', 'compiling', 'failed'], true) ? $stage : 'unknown'; + $world = $own['world'] ?? null; + $clients = $world['clients'] ?? null; + $players = in_array($state, ['awake', 'running'], true) && empty($world['error']) && is_int($clients) && $clients >= 0 ? (string)$clients : 'unknown'; + $phase = ShardRegionControl::phaseLabel($own['operation']['phase'] ?? null); + $stage = ShardRegionControl::phaseLabel($own['stage']['phase'] ?? null, true); $pending = is_bool($own['stage']['pending'] ?? null) ? ($own['stage']['pending'] ? 'yes' : 'no') : 'unknown'; - $busy = is_bool($own['busy'] ?? null) ? ($own['busy'] ? 'yes' : 'no') : 'unknown'; + $busy = $state !== 'unknown' && is_bool($own['busy'] ?? null) ? ($own['busy'] ? 'yes' : 'no') : 'unknown'; return "Region {$this->region}: state {$state}; players {$players}; busy {$busy}; lifecycle phase {$phase}; stage phase {$stage}, pending {$pending}. Status is not proof of deployment acceptance."; } $synchronous = in_array($action, ['kill', 'freeze', 'thaw'], true); - $own = $data[$synchronous ? 'done' : 'accepted'][$this->region] ?? null; - if (!is_array($own) || isset($data['refused'][$this->region])) { throw new \UnexpectedValueException('Missing/contradictory region receipt'); } + $own = ShardRegionControl::mutationReceipt($data, $synchronous ? 'done' : 'accepted', $this->region); if ($synchronous && ($own[match ($action) { 'kill' => 'killed', 'freeze' => 'frozen', default => 'thawed' }] ?? null) === true) { return "Region {$this->region}: host reports {$action} completed. Gameplay has not been verified."; } + if (ShardRegionControl::isFrozenUpdateStage($action, $own)) { + $stage = ($own['already_staging'] ?? false) ? 'an existing staged build' : 'a staged build'; + return "Region {$this->region}: update accepted via {$stage}, not completed. The world was asleep. Check status and the host receipt before assuming it is ready."; + } $expected = $action === 'force-restart' || $action === 'thaw' ? 'start' : $action; if (($own['accepted'] ?? null) !== true || ($own['action'] ?? null) !== $expected || ($action === 'thaw' && ($own['cold_start'] ?? null) !== true)) { throw new \UnexpectedValueException('Mismatched receipt'); } return "Region {$this->region}: {$action} accepted, not completed. Check status and the host receipt before assuming the world is ready."; diff --git a/src/Civ13/Local/ShardRegionControl.php b/src/Civ13/Local/ShardRegionControl.php index 38f46c46..c56b0b2a 100644 --- a/src/Civ13/Local/ShardRegionControl.php +++ b/src/Civ13/Local/ShardRegionControl.php @@ -48,38 +48,107 @@ public function request(string $action): PromiseInterface $data = json_decode(trim($result['stdout']), true, 32); if (!is_array($data) || !is_bool($data['ok'] ?? null)) { throw new \UnexpectedValueException('shard_group gave no JSON answer (exit '.$result['exit_code'].')'); } if (!$data['ok']) { - $refused = $data['refused'] ?? $data['error'] ?? 'unknown reason'; - if (is_array($refused)) { $refused = $refused[$region] ?? reset($refused) ?: 'unknown reason'; } + $refused = self::regionRefusal($data, $region); throw new \RuntimeException('Refused: '.substr(is_string($refused) ? $refused : 'unknown reason', 0, 300)); } if ($result['exit_code'] !== 0) { throw new \UnexpectedValueException('shard_group exit '.$result['exit_code'].' with ok=true'); } if ($action === 'status') { return self::regionStatus($data, $region); } // kill answers under "done"; the others under "accepted". Each maps region id => that region's answer. - $answers = $action === 'kill' ? ($data['done'] ?? null) : ($data['accepted'] ?? null); - $answer = is_array($answers) ? ($answers[$region] ?? null) : null; - if (!is_array($answer)) { - $refused = is_array($data['refused'] ?? null) ? ($data['refused'][$region] ?? null) : null; - if (is_string($refused)) { throw new \RuntimeException('Refused: '.substr($refused, 0, 300)); } - throw new \UnexpectedValueException('shard_group did not accept '.$action.' for '.$region); - } + $answer = self::mutationReceipt($data, $action === 'kill' ? 'done' : 'accepted', $region); if ($action === 'kill') { if (($answer['killed'] ?? null) !== true) { throw new \UnexpectedValueException('shard_group did not kill '.$region); } return ['accepted' => true, 'action' => 'kill', 'region' => $region] + $answer; } - if (($answer['accepted'] ?? null) !== true || ($answer['action'] ?? null) !== $action) { throw new \UnexpectedValueException('shard_group did not accept '.$action); } - return $answer + ['region' => $region]; + if (($answer['accepted'] ?? null) !== true || (($answer['action'] ?? null) !== $action && !self::isFrozenUpdateStage($action, $answer))) { + throw new \UnexpectedValueException('shard_group did not accept '.$action); + } + return ['region' => $region] + $answer; }); } + /** A definitive refusal must be scoped to this command, with no effects in the envelope. */ + public static function regionRefusal(array $data, string $region): string + { + foreach (['accepted', 'done'] as $key) { + if (array_key_exists($key, $data) && $data[$key] !== []) { + throw new \UnexpectedValueException('Contradictory region refusal'); + } + } + $refused = $data['refused'] ?? $data['error'] ?? null; + if (is_array($refused)) { + $refused = count($refused) === 1 ? ($refused[$region] ?? null) : null; + } + if (!is_string($refused) || $refused === '') { throw new \UnexpectedValueException('Missing or mismatched region refusal'); } + return $refused; + } + + /** A region-scoped command must not claim effects or refusals for other regions. */ + public static function mutationReceipt(array $data, string $bucket, string $region): array + { + $other = $bucket === 'done' ? 'accepted' : 'done'; + foreach (['refused', $other] as $key) { + if (array_key_exists($key, $data) && $data[$key] !== []) { + throw new \UnexpectedValueException('Contradictory region receipt'); + } + } + return self::singleRegionRecord($data[$bucket] ?? null, $region); + } + + public static function singleRegionRecord(mixed $records, string $region): array + { + $own = is_array($records) && count($records) === 1 ? ($records[$region] ?? null) : null; + if (!is_array($own) || (array_key_exists('region', $own) && $own['region'] !== $region)) { + throw new \UnexpectedValueException('Missing or mismatched region '.$region); + } + return $own; + } + + /** The coordinator may queue or reuse a staged build instead of updating a frozen region immediately. */ + public static function isFrozenUpdateStage(string $requested, array $receipt): bool + { + if ($requested !== 'update' || ($receipt['accepted'] ?? null) !== true + || ($receipt['action'] ?? null) !== 'stage' || ($receipt['state'] ?? null) !== 'asleep') { + return false; + } + if (array_key_exists('already_staging', $receipt)) { + return $receipt['already_staging'] === true && !array_key_exists('operation', $receipt); + } + return is_string($receipt['operation'] ?? null) && preg_match('/^[a-f0-9]{32}$/D', $receipt['operation']) === 1; + } + /** This region's host status in gaia_host's shape. */ private static function regionStatus(array $data, string $region): array { - $own = is_array($data['regions'] ?? null) ? ($data['regions'][$region] ?? null) : null; - if (!is_array($own)) { throw new \UnexpectedValueException('shard_group status has no region '.$region); } + $own = self::singleRegionRecord($data['regions'] ?? null, $region); unset($own['regions']); return $own; } + /** Status text may reach Discord: keep labels allowlisted, never echo arbitrary host output. */ + public static function phaseLabel(mixed $phase, bool $stage = false): string + { + $labels = $stage ? [ + 'accepted', 'checking for updates', 'current', 'ready', 'preparing', 'compiling', 'failed', + 'waiting for a requested build of another region', "waiting for another region's compile", + ] : [ + 'accepted', 'done', 'failed', 'killed', 'starting', 'started', 'stopping', 'stopped', 'building', + 'fetching', 'saving', 'compiling', 'compiled', 'pulling', 'checking save', 'backing up', 'switching', + 'rolling back', 'checking out', 'handed over', 'checking for updates', 'already on the latest build', + 'build is current', 'building the update beside the running world', 'waiting for the server to exit', + 'restarted onto the staged build', 'copying the staged build', 'booting the standby', 'loading the standby', + 'finishing the backup', 'installing the staged build', 'stopping without saving', + 'backing up the last completed save', 'stopped without saving', "waiting for another region's handover", + 'the running build predates handovers; saving, stopping and starting instead', + 'compiling (the compiler stopped without a result; trying again)', + ]; + if (in_array($phase, $labels, true)) { return $phase; } + if (!$stage && is_string($phase)) { + if (preg_match('/^warning players \([0-9]{1,9} s\), then saving$/D', $phase) === 1) { return $phase; } + if (preg_match('/^[a-z-]{1,32} got no reply in time \(/D', $phase) === 1) { return 'waiting for the world to answer'; } + } + return 'unknown'; + } + /** One line for Discord from a status answer, led by the region's name. */ public static function describe(array $status): string { @@ -87,7 +156,29 @@ public static function describe(array $status): string $name = is_string($status['name'] ?? null) ? preg_replace('/^(.{0,64}).*$/us', '$1', preg_replace('/[^\p{L}\p{M}\p{N} \-\'().]/u', '', $status['name']) ?? '') ?? '' : ''; - $line = GaiaHostControl::describe($status); + $state = $status['state'] ?? null; + $listening = $status['listening'] ?? null; + $parts = [match (true) { + $state === 'asleep' || $state === 'cold' => GaiaHostControl::describe(['state' => $state]), + $state === 'unknown' || !is_bool($listening) => 'Server status is unknown.', + $listening => 'Server port is open.', + default => 'Server port is closed.', + }]; + $world = $status['world'] ?? null; + if (is_array($world) && $state !== 'unknown' && $listening === true && $state !== 'asleep') { + $parts[] = match ($world['ready'] ?? null) { + true => 'World ready.', + false => 'World not ready.', + default => 'World readiness unknown.', + }; + if (empty($world['error']) && is_int($world['clients'] ?? null) && $world['clients'] >= 0) { $parts[] = "{$world['clients']} players."; } + } + $operation = $status['operation'] ?? null; + $action = $operation['action'] ?? null; + if (is_string($action) && preg_match('/^[a-z][a-z-]{0,31}$/D', $action) === 1) { + $parts[] = 'Last action: '.$action.' ('.self::phaseLabel($operation['phase'] ?? null).').'; + } + $line = implode(' ', $parts); $map = is_string($status['region_view']['map'] ?? null) ? preg_replace('/[^\p{L}\p{M}\p{N} \-\'().]/u', '', substr($status['region_view']['map'], 0, 64)) : ''; if ($map !== '' && $map !== null) { $line .= " Map: {$map}."; } return $name === '' ? $line : "{$name}: {$line}"; diff --git a/src/Civ13/Local/TdmGroupConfiguration.php b/src/Civ13/Local/TdmGroupConfiguration.php new file mode 100644 index 00000000..16695345 --- /dev/null +++ b/src/Civ13/Local/TdmGroupConfiguration.php @@ -0,0 +1,144 @@ + + */ + public static function profiles(string $file, array $legacy): array + { + $legacy['retire_legacy_lifecycle'] = true; + clearstatcache(true, $file); + $info = @lstat($file); + if ($info === false) { + $siblings = @scandir(dirname($file)); + if ($siblings === false || in_array(basename($file), $siblings, true)) { + throw new \UnexpectedValueException('Cannot determine whether the TDM group config is present.'); + } + return ['tdm' => $legacy]; + } + // Match ShardRegionControl's rejection of symlinked config paths. + if (($info['mode'] & 0170000) !== 0100000) { + throw new \UnexpectedValueException('The TDM group config must be a regular, non-symlinked file.'); + } + $raw = @file_get_contents($file, false, null, 0, self::MAX_CONFIG_BYTES + 1); + if ($raw === false || strlen($raw) > self::MAX_CONFIG_BYTES) { + throw new \UnexpectedValueException('The TDM group config is unreadable or too large.'); + } + try { + $group = json_decode(str_starts_with($raw, "\xEF\xBB\xBF") ? substr($raw, 3) : $raw, true, 32, JSON_THROW_ON_ERROR); + } catch (\JsonException $error) { + throw new \UnexpectedValueException('The TDM group config is not valid JSON.', 0, $error); + } + if (!is_array($group) || ($group['group'] ?? null) !== 'tdm' + || !is_array($group['regions'] ?? null) || !array_is_list($group['regions']) || $group['regions'] === []) { + throw new \UnexpectedValueException('Expected a TDM group and its region list.'); + } + $repo = self::directory($group['repository'] ?? null, 'repository'); + $root = self::directory($group['root'] ?? null, 'region root'); + // Do not install updates into a directory this bot merely assumed was a checkout. + $script = $repo.'/scripts/shard-group/shard_group.py'; + if (!is_file($script) || !is_readable($script) || is_link($script)) { + throw new \UnexpectedValueException('The configured TDM repository has no readable shard controller.'); + } + + $regions = $ports = $barracks = $battles = $gateways = []; + foreach ($group['regions'] as $region) { + $id = is_array($region) ? ($region['id'] ?? null) : null; + $kind = is_array($region) ? ($region['kind'] ?? null) : null; + $port = is_array($region) ? ($region['port'] ?? null) : null; + if (!is_string($id) || !preg_match('/^[a-z0-9_-]{1,32}$/D', $id) || $id === 'front-door' + || isset($regions[$id]) || !is_string($kind) || !preg_match('/^[A-Z_]+$/D', $kind) + || !self::validPort($port) || isset($ports[$port])) { + throw new \UnexpectedValueException('The TDM group must contain unique valid region IDs and gameplay ports.'); + } + $regions[$id] = $region; + $ports[$port] = true; + if ($kind === 'BARRACKS') { $barracks[] = $id; } + if ($kind === 'BATTLE') { $battles[] = $id; } + if ($kind === 'GATEWAY') { $gateways[] = $id; } + } + if (count($barracks) !== 1 || count($battles) !== 1 || count($gateways) > 1) { + throw new \UnexpectedValueException('The TDM group needs one BARRACKS and one BATTLE and permits at most one GATEWAY.'); + } + + // Match shard_group.py: the relay uses gate, otherwise use mainland. + $mainland = array_key_exists('mainland', $group) ? $group['mainland'] : $group['regions'][0]['id']; + if (!is_string($mainland) || !isset($regions[$mainland]) + || in_array($regions[$mainland]['kind'], ['BATTLE', 'GATEWAY', 'RAID', 'EVENT', 'ORBIT', 'TUTORIAL', 'EXPEDITION'], true)) { + throw new \UnexpectedValueException('The configured TDM mainland is not an eligible region.'); + } + $relay = array_key_exists('relay_port', $group) ? $group['relay_port'] : 0; + if ($relay !== 0 && (!self::validPort($relay) || isset($ports[$relay]))) { + throw new \UnexpectedValueException('The TDM relay needs an assigned port distinct from gameplay ports.'); + } + if ($relay === 0 && $gateways !== []) { + throw new \UnexpectedValueException('A TDM gateway requires the routing relay.'); + } + $frontId = $relay !== 0 && array_key_exists('gate', $group) ? $group['gate'] : $mainland; + if (!is_string($frontId) || !isset($regions[$frontId]) + || in_array($regions[$frontId]['kind'], ['BATTLE', 'RAID', 'EVENT', 'TUTORIAL', 'EXPEDITION'], true)) { + throw new \UnexpectedValueException('The configured TDM front door is not an eligible region.'); + } + + $battleId = $battles[0]; + foreach (array_unique([$frontId, $battleId, $barracks[0]]) as $id) { + self::directory($root.'/'.$id, 'region directory'); + } + $forRegion = static fn (string $id): array => [ + 'enabled' => true, + 'python' => '/usr/bin/python3', + 'script' => $script, + 'config' => $file, + 'region' => $id, + 'kill' => 'stop', + ]; + unset($legacy['systemd']); + $front = array_replace($legacy, [ + 'basedir' => $root.'/'.$frontId, + 'port' => (string) $regions[$frontId]['port'], + 'shard_group' => $forRegion($frontId), + 'region_group' => $file, // The front-door entry counts the whole group. + ]); + $sharedAdmins = $root.'/front-door/SQL/admins.txt'; + if (is_file($sharedAdmins)) { + $front['admin_file'] = $sharedAdmins; + } + $battle = array_replace($front, [ + 'supported' => false, // No public Battle entry; Play still points to TDM. + 'name' => 'TDM Battle', + 'basedir' => $root.'/'.$battleId, + 'port' => (string) $regions[$battleId]['port'], + 'shard_group' => $forRegion($battleId), + 'shard_of' => 'tdm', + ]); + unset($battle['region_group']); + return ['tdm' => $front, 'tdmbattle' => $battle]; + } + + private static function validPort(mixed $port): bool + { + return is_int($port) && $port >= 1024 && $port <= 65535; + } + + private static function directory(mixed $path, string $label): string + { + if (!PortableProfile::absoluteAdminFile($path) || !is_dir($path) || !is_readable($path)) { + throw new \UnexpectedValueException("The configured TDM {$label} must be an existing readable absolute directory."); + } + return rtrim($path, '/\\'); + } +} diff --git a/src/Civ13/MessageCommand/Commands/Civ13GameServerListMedals.php b/src/Civ13/MessageCommand/Commands/Civ13GameServerListMedals.php index 447d6a9a..d1ec0421 100644 --- a/src/Civ13/MessageCommand/Commands/Civ13GameServerListMedals.php +++ b/src/Civ13/MessageCommand/Commands/Civ13GameServerListMedals.php @@ -31,8 +31,9 @@ class Civ13GameServerListMedals extends Civ13GameServerMessageCommand */ public function __invoke(Message $message, string $command, array $message_filtered): PromiseInterface { - if (! @touch($awardsPath = $this->gameserver->basedir.Civ13::awards)) { - return reject(new MissingSystemPermissionException("Unable to access `{$awardsPath}`")); + $awardsPath = $this->gameserver->basedir.Civ13::awards; + if (! is_file($awardsPath) || ! is_readable($awardsPath)) { + return reject(new MissingSystemPermissionException('No readable awards source is configured for this world.')); } return $message->reply( diff --git a/src/Civ13/MessageCommand/Commands/Civ13GameServerRank.php b/src/Civ13/MessageCommand/Commands/Civ13GameServerRank.php index d1d491ec..bf457f22 100644 --- a/src/Civ13/MessageCommand/Commands/Civ13GameServerRank.php +++ b/src/Civ13/MessageCommand/Commands/Civ13GameServerRank.php @@ -35,14 +35,9 @@ public function __invoke(Message $message, string $command, array $message_filte return $this->civ13->reply($message, 'No ckey found for your Discord ID. Please verify your account first.'); } } - if (! $this->gameserver->recalculateRanking()) { - return $this->civ13->reply($message, 'There was an error trying to recalculate ranking! The bot may be misconfigured.'); - } - if (! $msg = $this->gameserver->getRank($ckey)) { - return $this->civ13->reply($message, 'There was an error trying to get your ranking!'); - } - - return $this->civ13->sendMessage($message->channel, $msg, 'rank.txt'); - // return $this->civ13->reply($message, "Your ranking is too long to display."); + return $this->gameserver->recalculateRanking()->then( + fn () => $this->civ13->sendMessage($message->channel, $this->gameserver->getRank($ckey), 'rank.txt'), + fn () => $this->civ13->reply($message, 'Ranking is unavailable. Check which world owns the awards.') + ); } } diff --git a/src/Civ13/MessageCommand/Commands/Civ13GameServerUpdate.php b/src/Civ13/MessageCommand/Commands/Civ13GameServerUpdate.php index 93f33d8d..46d61338 100644 --- a/src/Civ13/MessageCommand/Commands/Civ13GameServerUpdate.php +++ b/src/Civ13/MessageCommand/Commands/Civ13GameServerUpdate.php @@ -28,7 +28,12 @@ class Civ13GameServerUpdate extends Civ13GameServerMessageCommand public function __invoke(Message $message, string $command, array $message_filtered): PromiseInterface { return $message->react('⏱️')->then(fn () => $this->gameserver->Update($message))->then( - null, + function (mixed $receipt) use ($message): PromiseInterface|null { + if (is_array($receipt) && ($receipt['action'] ?? null) === 'stage') { + return $this->civ13->reply($message, 'Build staging accepted for the sleeping region. The running version has not changed.'); + } + return null; + }, fn (\Throwable $error): PromiseInterface => $this->civ13->reply($message, $error->getMessage()) ); } diff --git a/src/Civ13/MessageCommand/Commands/PullCivRepository.php b/src/Civ13/MessageCommand/Commands/PullCivRepository.php index e0ad9c4f..0740ca7d 100644 --- a/src/Civ13/MessageCommand/Commands/PullCivRepository.php +++ b/src/Civ13/MessageCommand/Commands/PullCivRepository.php @@ -14,7 +14,6 @@ namespace Civ13\MessageCommand\Commands; use Civ13\MessageCommand\Civ13MessageCommand; -use Civ13\OSFunctions; use Discord\Parts\Channel\Message; use React\Promise\PromiseInterface; @@ -28,13 +27,6 @@ class PullCivRepository extends Civ13MessageCommand */ public function __invoke(Message $message, string $command, array $message_filtered): PromiseInterface { - if (!OSFunctions::legacyShellAvailable()) { - return $message->reply('This maintenance command is unavailable in Windows/portable mode.'); - } - return $message->react( - (is_dir($fp = $this->civ13->gitdir) && OSFunctions::execInBackground("git -C {$fp} pull")) - ? '👍' - : '🔥' - ); + return $message->reply('Shared game-repository pulls are retired in Discord. Use the host operator runbook or service supervisor.'); } } diff --git a/src/Civ13/MessageCommand/Commands/Stop.php b/src/Civ13/MessageCommand/Commands/Stop.php index e97b4459..459c982f 100644 --- a/src/Civ13/MessageCommand/Commands/Stop.php +++ b/src/Civ13/MessageCommand/Commands/Stop.php @@ -24,7 +24,6 @@ class Stop extends Civ13MessageCommand */ public function __invoke(Message $message, string $command, array $message_filtered): PromiseInterface { - return $message->react('🛑') - ->then(fn () => $this->civ13->stop()); + return $message->reply('Bot self-maintenance is retired. Use the operator-managed deployment procedure or service supervisor.'); } } diff --git a/src/Civ13/MessageCommand/Commands/TypeSpess.php b/src/Civ13/MessageCommand/Commands/TypeSpess.php index 724b7562..f212afa7 100644 --- a/src/Civ13/MessageCommand/Commands/TypeSpess.php +++ b/src/Civ13/MessageCommand/Commands/TypeSpess.php @@ -14,7 +14,6 @@ namespace Civ13\MessageCommand\Commands; use Civ13\MessageCommand\Civ13MessageCommand; -use Civ13\OSFunctions; use Discord\Parts\Channel\Message; use React\Promise\PromiseInterface; @@ -28,24 +27,6 @@ class TypeSpess extends Civ13MessageCommand */ public function __invoke(Message $message, string $command, array $message_filtered): PromiseInterface { - if (!OSFunctions::legacyShellAvailable()) { - return $message->reply('This maintenance command is unavailable in Windows/portable mode.'); - } - if (! $state = trim(substr($message_filtered['message_content_lower'], strlen($command)))) { - return $this->civ13->reply($message, 'Wrong format. Please try `ts on` or `ts off`.'); - } - if (! in_array($state, ['on', 'off'])) { - return $this->civ13->reply($message, 'Wrong format. Please try `ts on` or `ts off`.'); - } - if ($state === 'on') { - OSFunctions::execInBackground("cd {$this->civ13->folders['typespess_path']}"); - OSFunctions::execInBackground('git pull'); - OSFunctions::execInBackground("sh {$this->civ13->files['typespess_launch_server_path']}&"); - - return $this->civ13->reply($message, '**TypeSpess Civ13** test server is now **on**: http://civ13.com/ts'); - } - OSFunctions::execInBackground('killall index.js'); - - return $this->civ13->reply($message, '**TypeSpess Civ13** test server is now **offline**.'); + return $message->reply('TypeSpess chat controls are retired. Use the TypeSpess host operator’s service supervisor.'); } } diff --git a/src/Civ13/MessageCommand/Commands/UpdateDependencies.php b/src/Civ13/MessageCommand/Commands/UpdateDependencies.php index 985cd6bb..bbc121c6 100644 --- a/src/Civ13/MessageCommand/Commands/UpdateDependencies.php +++ b/src/Civ13/MessageCommand/Commands/UpdateDependencies.php @@ -14,7 +14,6 @@ namespace Civ13\MessageCommand\Commands; use Civ13\MessageCommand\Civ13MessageCommand; -use Civ13\OSFunctions; use Discord\Parts\Channel\Message; use React\Promise\PromiseInterface; @@ -28,13 +27,6 @@ class UpdateDependencies extends Civ13MessageCommand */ public function __invoke(Message $message, string $command, array $message_filtered): PromiseInterface { - if (!OSFunctions::legacyShellAvailable()) { - return $message->reply('This maintenance command is unavailable in Windows/portable mode.'); - } - return $message->react( - OSFunctions::execInBackground('composer update') - ? '👍' - : '🔥' - ); + return $message->reply('Bot self-maintenance is retired. Use the operator-managed deployment procedure or service supervisor.'); } } diff --git a/src/Civ13/Panels.php b/src/Civ13/Panels.php index 7779c61a..fc3685c4 100644 --- a/src/Civ13/Panels.php +++ b/src/Civ13/Panels.php @@ -40,7 +40,7 @@ * shouldn't. * * Staff: host / restart / kill each game server, panic bunker, ban & admin list - * refreshes, log cleanup, `git pull` / `composer update`. + * refreshes and log cleanup. Bot deployment is operator-owned. * Player: verification status + a "Verify" modal, role resync, personal rank and * ban lookup, live server status, campaign faction join. * @@ -177,12 +177,7 @@ private function staffPanel(): MessageBuilder }, 'Log cleanup queued.')), $this->staffButton(Button::primary(), '↻ Refresh', 'sp_refresh', fn (Interaction $i) => $i->updateMessage($this->staffPanel())), ]); - if (OSFunctions::legacyShellAvailable()) { - $components[] = ActionRow::new()->addComponents([ - $this->staffButton(Button::secondary(), '⬇️ Git Pull', 'sp_pull', fn (Interaction $i) => $this->bg($i, fn () => OSFunctions::execInBackground('git pull'), 'Pulling latest code…')), - $this->staffButton(Button::secondary(), '📦 Composer Update', 'sp_composer', fn (Interaction $i) => $this->bg($i, fn () => OSFunctions::execInBackground('composer update'), 'Updating dependencies…')), - ]); - } + $components[] = TextDisplay::new('-# Bot self-maintenance is retired. Use the operator-managed deployment procedure or service supervisor.'); $components[] = Separator::new(); $components[] = TextDisplay::new('-# Destructive actions run immediately. Every button re-checks your permission.'); diff --git a/src/Civ13/Slash.php b/src/Civ13/Slash.php index e9d18165..d78ae6d9 100644 --- a/src/Civ13/Slash.php +++ b/src/Civ13/Slash.php @@ -173,22 +173,10 @@ private function __updateCommands(): void if ($command = $commands->get('name', 'pull')) { $commands->delete($command); } - /*if (! $commands->get('name', 'pull')) $this->save($commands, new Command($this->discord, [ - 'name' => 'pull', - 'description' => "Update the bot's code", - 'contexts' => [Interaction::CONTEXT_TYPE_GUILD], - 'default_member_permissions' => (string) new RolePermission($this->discord, ['view_audit_log' => true]), - ]));*/ if ($command = $commands->get('name', 'update')) { $commands->delete($command); } - /*if (! $commands->get('name', 'update')) $this->save($commands, new Command($this->discord, [ - 'name' => 'update', - 'description' => "Update the bot's dependencies", - 'contexts' => [Interaction::CONTEXT_TYPE_GUILD], - 'default_member_permissions' => (string) new RolePermission($this->discord, ['view_audit_log' => true]), - ]));*/ if ($command = $commands->get('name', 'stats')) { $commands->delete($command); @@ -586,40 +574,14 @@ private function __updateGuildCommands(): void } }); } - /** Registers every `listenCommand` handler for the interaction commands (git pull, verify, etc.). */ + /** Registers handlers for current interaction commands and refusal of retired commands. */ private function __declareListeners(): void { - $this->discord->listenCommand('pull', function (Interaction $interaction): PromiseInterface { - if (!OSFunctions::legacyShellAvailable()) { - return $this->respondWithMessage($interaction, 'This maintenance command is unavailable in Windows/portable mode.', true); - } - $this->logger->info('[GIT PULL]'); - OSFunctions::execInBackground('git pull'); - $this->civ13->loop->addTimer(5, function () { - if ($channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - $this->civ13->sendMessage($channel, 'Forcefully moving the HEAD back to origin/main... (2/3)'); - } - OSFunctions::execInBackground('git reset --hard origin/main'); - }); - $this->civ13->loop->addTimer(10, function () { - if ($channel = $this->discord->getChannel($this->civ13->channel_ids['staff_bot'])) { - $this->civ13->sendMessage($channel, 'Updating code from GitHub... (3/3)'); - } - OSFunctions::execInBackground('git pull'); - }); - - return $this->respondWithMessage($interaction, 'Updating code from GitHub...'); - }); - - $this->discord->listenCommand('update', function (Interaction $interaction): PromiseInterface { - if (!OSFunctions::legacyShellAvailable()) { - return $this->respondWithMessage($interaction, 'This maintenance command is unavailable in Windows/portable mode.', true); - } - $this->logger->info('[COMPOSER UPDATE]'); - OSFunctions::execInBackground('composer update'); - - return $this->respondWithMessage($interaction, 'Updating dependencies...'); - }); + foreach (['pull', 'update'] as $retired) { + $this->discord->listenCommand($retired, fn (Interaction $interaction): PromiseInterface => + $this->respondWithMessage($interaction, 'Bot self-maintenance is retired. Use the operator-managed deployment procedure or service supervisor.', true) + ); + } $this->discord->listenCommand('restart_server', function (Interaction $interaction): PromiseInterface { if (! isset($interaction->data->options['server'])) { return $this->respondWithMessage($interaction, Civ13::createBuilder()->setContent('No server specified')); diff --git a/tests/local/launcher-management.php b/tests/local/launcher-management.php index 6d8f0350..a7a7e64d 100644 --- a/tests/local/launcher-management.php +++ b/tests/local/launcher-management.php @@ -41,6 +41,38 @@ function confirm(LauncherManagement $manager, string $action): string { check($calls[array_key_last($calls)][1]===($action==='force-restart'?210:60),'bounded timeout'); check(str_contains(line($m->handle('11','22','33',$confirmation)),'invalid'),'no replay'); } +$frozenStage = ['accepted'=>true,'action'=>'stage','state'=>'asleep','operation'=>str_repeat('a',32)]; +$alreadyStaging = ['accepted'=>true,'action'=>'stage','state'=>'asleep','already_staging'=>true]; +foreach ([$frozenStage, $alreadyStaging] as $own) { + $m=$make(); $c=confirm($m,'update'); $response=['ok'=>true,'accepted'=>['gaia'=>$own],'refused'=>[]]; + $text=line($m->handle('11','22','33',$c)); + check(str_contains($text,'staged build, not completed') && str_contains($text,'asleep'),'frozen update correctly reports pending stage'); + check(str_contains(line($m->handle('11','22','33','start')),'Confirm with'),'validated stage does not latch unknown'); +} +foreach ([ + ['accepted'=>['gaia'=>array_replace($frozenStage,['state'=>'awake'])]], + ['accepted'=>['gaia'=>array_replace($frozenStage,['operation'=>'oops'])]], + ['accepted'=>['gaia'=>$frozenStage+['already_staging'=>true]]], + ['accepted'=>['other'=>$frozenStage]], + ['accepted'=>['gaia'=>$frozenStage+['region'=>'other']]], + ['accepted'=>['gaia'=>$frozenStage,'other'=>$frozenStage]], + ['accepted'=>['gaia'=>$frozenStage],'refused'=>['gaia'=>null]], + ['accepted'=>['gaia'=>$frozenStage],'done'=>['gaia'=>['killed'=>true]]], +] as $bad) { + $m=$make(); $c=confirm($m,'update'); $response=['ok'=>true]+$bad; + check(str_contains(line($m->handle('11','22','33',$c)),'No verified host result'),'malformed/contradictory update not accepted'); + check(str_contains(line($m->handle('11','22','33','start')),'gaiamanage acknowledge'),'bad update latches region and provides recovery command'); +} +$m=$make(); $c=confirm($m,'restart'); $response=['ok'=>true,'accepted'=>['gaia'=>$frozenStage]]; +check(str_contains(line($m->handle('11','22','33',$c)),'No verified host result'),'stage cannot substitute for restart'); +foreach (['warning players (20 s), then saving', 'waiting for the server to exit', 'building the update beside the running world'] as $phase) { + $response=['ok'=>true,'regions'=>['gaia'=>['state'=>'awake','operation'=>['phase'=>$phase],'stage'=>['phase'=>"waiting for another region's compile"]]]]; + $text=line($make()->handle('11','22','33','status')); + check(str_contains($text,'lifecycle phase '.$phase) && str_contains($text,"stage phase waiting for another region's compile"),'real bounded phases are visible'); +} +$response=['ok'=>true,'regions'=>['gaia'=>['state'=>'unknown','busy'=>false,'world'=>['clients'=>0],'operation'=>['phase'=>'SECRET /private/path']]]]; +$text=line($make()->handle('11','22','33','status')); +check(str_contains($text,'state unknown; players unknown; busy unknown; lifecycle phase unknown') && !str_contains($text,'SECRET'),'unknown host status stays unknown and unsafe phase text is not shown'); $m = $make(); $c = confirm($m,'thaw'); $response=['ok'=>true,'done'=>['gaia'=>['accepted'=>true,'action'=>'start','cold_start'=>true]]]; check(str_contains(line($m->handle('11','22','33',$c)),'accepted, not completed'),'cold thaw is asynchronous'); $m=$make(); $c=confirm($m,'stop'); $now+=60; diff --git a/tests/local/server-compatibility.php b/tests/local/server-compatibility.php index e4e9cb94..9dbc6008 100644 --- a/tests/local/server-compatibility.php +++ b/tests/local/server-compatibility.php @@ -41,6 +41,38 @@ public function updateFilesFromMemberRoles(callable $callback,array $file_paths, try { $server=(new ReflectionClass(\Civ13\GameServer::class))->newInstanceWithoutConstructor(); $server->civ13=(new ReflectionClass(StatusCivFixture::class))->newInstanceWithoutConstructor(); + // The TDM gate, slash helper, and staff panel all use the same GameServer + // paths. A configured backend must still receive zero mutating calls. + $tdm=(new ReflectionClass(\Civ13\GameServer::class))->newInstanceWithoutConstructor(); + $tdm->engine='byond'; + (new ReflectionProperty($tdm,'key'))->setValue($tdm,'tdm'); + (new ReflectionProperty($tdm,'retireLegacyLifecycle'))->setValue($tdm,true); + $fakeScript=$root.'/fake-controller'; + file_put_contents($fakeScript,'not executed'); + $commands=[]; + $control=new \Civ13\Local\ShardRegionControl($fakeScript,$fakeScript,$fakeScript,'gateway', + function(array $argv,int $timeout)use(&$commands) { + $commands[]=$argv; + return resolve(['exit_code'=>0,'stdout'=>json_encode(['ok'=>true,'regions'=>['gateway'=>['name'=>'Gateway','listening'=>true]]])]); + }); + (new ReflectionProperty($tdm,'gaiaHost'))->setValue($tdm,$control); + foreach(['Host'=>[], 'Kill'=>[], 'Restart'=>[], 'Update'=>[], 'MapSwap'=>['TEST','synthetic-admin']] as $method=>$args) { + $rejected=false; + $tdm->$method(...$args)->then(null,function(Throwable $error)use(&$rejected){$rejected=str_contains($error->getMessage(),'retired');}); + check($rejected, "Managed TDM unexpectedly accepted {$method}"); + } + check($commands===[], 'A retired TDM command contacted a controller'); + $tdm->HostStatus()->then(function($status){check(str_contains($status,'Gateway'), 'Status went to the wrong region');}); + check(count($commands)===1 && $commands[0][6]==='status' && $commands[0][7]==='--region=gateway', 'Read-only status did not reach the bound gateway'); + unlink($fakeScript); + $standalone=(new ReflectionClass(\Civ13\GameServer::class))->newInstanceWithoutConstructor(); + $standalone->engine='byond'; + foreach(['Host'=>[], 'Kill'=>[], 'Restart'=>[], 'Update'=>[], 'MapSwap'=>['TEST','synthetic-admin']] as $method=>$args) { + $rejected=false; + $standalone->$method(...$args)->then(null,function()use(&$rejected){$rejected=true;}); + check($rejected, "Control without a supervised backend unexpectedly accepted {$method}"); + } + foreach (['name'=>'Fixture','ip'=>'127.0.0.1','port'=>'18452','host'=>'Local','basedir'=>$root.'/'] as $property=>$value) {(new ReflectionProperty($server,$property))->setValue($server,$value);} $server->players=['player']; foreach (['byond','opendream'] as $engine) { @@ -56,6 +88,15 @@ public function updateFilesFromMemberRoles(callable $callback,array $file_paths, check($server->DirectMessage('hello','admin','player'),'production DM'); check(!$server->DirectMessage("bad\nrecord",'admin','player'),'production IPC injection'); $server->enabled=false; check(!$server->OOCMessage('hello','admin'),'disabled server write'); + $rankingFile=$root.\Civ13\Civ13::ranking_path; + $awardsFile=$root.\Civ13\Civ13::awards; + $unavailable=0; + $server->getRanking()->then(null,function()use(&$unavailable){$unavailable++;}); + $server->recalculateRanking()->then(null,function()use(&$unavailable){$unavailable++;}); + check($unavailable===2&&!file_exists($rankingFile)&&!file_exists($awardsFile),'missing awards/rank created placeholder files'); + file_put_contents($rankingFile,'5;historic'); + $server->recalculateRanking()->then(null,function()use(&$unavailable){$unavailable++;}); + check($unavailable===3&&file_get_contents($rankingFile)==='5;historic','missing awards overwrote existing ranking'); file_put_contents($root.\Civ13\Civ13::awards,"player;date;long service medal\nleader;date;iron cross 2nd class\nplayer;date;wounded badge\n"); $ranked=false;$server->recalculateRanking()->then(function()use(&$ranked){$ranked=true;}); check($ranked&&file_get_contents($root.\Civ13\Civ13::ranking_path)==="5;leader".PHP_EOL."1;player",'production medal scoring/sorting'); diff --git a/tests/local/shard-region.php b/tests/local/shard-region.php index 880a7a4e..e15e8273 100644 --- a/tests/local/shard-region.php +++ b/tests/local/shard-region.php @@ -2,7 +2,8 @@ declare(strict_types=1); // ShardRegionControl with the real AsyncProcess worker and a stand-in script // that answers like Civ13's scripts/shard-group/shard_group.py. No game, no Discord. -require $argv[1] ?? __DIR__.'/../../vendor/autoload.php'; +$loader = require $argv[1] ?? __DIR__.'/../../vendor/autoload.php'; +$loader->addPsr4('Civ13\\', __DIR__.'/../../src/Civ13/', true); require_once __DIR__.'/../../src/Civ13/Local/AsyncProcess.php'; require_once __DIR__.'/../../src/Civ13/Local/GaiaHostControl.php'; require_once __DIR__.'/../../src/Civ13/Local/ShardRegionControl.php'; @@ -71,6 +72,29 @@ function shardCheck(bool $ok, string $what): void { if (!$ok) { throw new Runtim shardCheck($error === null && $value['accepted'] === true && $value['action'] === 'kill' && $value['pid'] === 4242, 'forced stop'); [$value, $error] = $run($battle, 'update'); shardCheck($error instanceof UnexpectedValueException, 'acceptance for another region is not this region\'s'); + $stage = ['accepted'=>true,'action'=>'stage','state'=>'asleep','operation'=>$operation]; + foreach ([$stage, ['accepted'=>true,'action'=>'stage','state'=>'asleep','already_staging'=>true]] as $receipt) { + $answers['update:battle'] = json_encode(['ok'=>true,'accepted'=>['battle'=>$receipt],'refused'=>[]]); + file_put_contents($config, json_encode($answers)); + [$value, $error] = $run($battle,'update'); + shardCheck($error === null && $value === ['region'=>'battle']+$receipt, 'preserve accepted frozen stage outcome'); + } + foreach ([ + ['accepted'=>['battle'=>array_replace($stage,['state'=>'awake'])]], + ['accepted'=>['battle'=>array_replace($stage,['operation'=>false])]], + ['accepted'=>['battle'=>$stage+['region'=>'barracks']]], + ['accepted'=>['battle'=>$stage,'barracks'=>$stage]], + ['accepted'=>['battle'=>$stage],'refused'=>['battle'=>null]], + ] as $bad) { + $answers['update:battle'] = json_encode(['ok'=>true]+$bad); + file_put_contents($config, json_encode($answers)); + [$value, $error] = $run($battle,'update'); + shardCheck($value === null && $error instanceof UnexpectedValueException,'malformed/contradictory stage not accepted'); + } + $line = ShardRegionControl::describe(['name'=>'Battle','state'=>'unknown','world'=>['clients'=>0]]); + shardCheck($line === 'Battle: Server status is unknown.', 'unknown status is not reported as stopped: '.$line); + $line = ShardRegionControl::describe(['state'=>'awake','listening'=>true,'world'=>[], 'operation'=>['action'=>'stop','phase'=>'waiting for the server to exit']]); + shardCheck($line === 'Server port is open. World readiness unknown. Last action: stop (waiting for the server to exit).','typed phase and readiness: '.$line); [$value, $error] = $run($barracks, 'restart'); shardCheck($error instanceof UnexpectedValueException && str_contains($error->getMessage(), 'no JSON'), 'garbage output'); $log = file($config.'.log', FILE_IGNORE_NEW_LINES); diff --git a/tests/local/tdm-group-configuration.php b/tests/local/tdm-group-configuration.php new file mode 100644 index 00000000..e2770168 --- /dev/null +++ b/tests/local/tdm-group-configuration.php @@ -0,0 +1,126 @@ + $tmp.'/old-status', 'port' => '1714', 'ip' => '192.0.2.10', + 'enabled' => true, 'supported' => true, 'name' => 'TDM', 'systemd' => ['unit' => 'civ13-tdm.service'], + 'play' => ['url' => 'https://civ13.com/tdm/']]; + $group = ['group' => 'tdm', 'repository' => $repo, 'root' => $root, 'persistent' => false, + 'mainland' => 'briefing', 'relay_port' => 18200, 'gate' => 'join_here', 'regions' => [ + ['id' => 'briefing', 'kind' => 'BARRACKS', 'port' => 18201], + ['id' => 'rounds', 'kind' => 'BATTLE', 'port' => 18202], + ['id' => 'join_here', 'kind' => 'GATEWAY', 'port' => 18203], + ]]; + $absent = TdmGroupConfiguration::profiles($file, $legacy); + expect(array_keys($absent) === ['tdm'] && $absent['tdm']['systemd'] === $legacy['systemd'], 'Genuinely absent config retains legacy status only'); + expect($absent['tdm']['retire_legacy_lifecycle'] === true, 'Absent-file status profile is also read-only'); + $resolve = static function (array $config) use ($file, $legacy): array { + file_put_contents($file, json_encode($config, JSON_THROW_ON_ERROR)); + return TdmGroupConfiguration::profiles($file, $legacy); + }; + + $profiles = $resolve($group); + expect(array_keys($profiles) === ['tdm', 'tdmbattle'], 'Two bot entries from one group snapshot'); + [$front, $battle] = array_values($profiles); + expect($front['basedir'] === $root.'/join_here' && $front['port'] === '18203', 'Routed public front follows exact configured directory and port'); + expect($battle['basedir'] === $root.'/rounds' && $battle['port'] === '18202', 'Battle uses BATTLE kind, not a hardcoded port or directory'); + expect($front['shard_group']['region'] === 'join_here' && $battle['shard_group']['region'] === 'rounds', 'Targets cannot diverge from the selected profiles'); + expect($front['shard_group']['script'] === $script && $battle['shard_group']['script'] === $script + && $front['shard_group']['config'] === $file && $battle['shard_group']['config'] === $file, 'Both controllers derive from one configured root'); + expect($front['admin_file'] === $admins && $battle['admin_file'] === $admins, 'Shared admin path stays attached to TDM'); + expect(!isset($front['systemd']) && !isset($battle['systemd']), 'Configured group cannot reach the legacy unit'); + expect($front['retire_legacy_lifecycle'] === true && $battle['retire_legacy_lifecycle'] === true, 'Both controlled TDM keys retire legacy lifecycle operations'); + expect($front['play'] === $legacy['play'] && $battle['play'] === $legacy['play'], 'Battle Play link still enters through the public TDM door'); + expect($front['region_group'] === $file && !isset($battle['region_group']) + && $battle['shard_of'] === 'tdm' && $battle['supported'] === false, 'Battle is not a second aggregate Play entry'); + + $direct = $group; + unset($direct['mainland'], $direct['gate'], $direct['relay_port'], $direct['regions'][2]); + expect($resolve($direct)['tdm']['shard_group']['region'] === 'briefing', 'Without relay, the coordinator default mainland is the first region'); + $routedMainland = $group; + unset($routedMainland['gate']); + expect($resolve($routedMainland)['tdm']['shard_group']['region'] === 'briefing', 'A relay without explicit gate uses mainland'); + file_put_contents($file, "\xEF\xBB\xBF".json_encode($group, JSON_THROW_ON_ERROR)); + expect(TdmGroupConfiguration::profiles($file, $legacy) === $profiles, 'BOM composes with one valid snapshot'); + + $invalid = [ + array_replace($group, ['group' => 'other']), + array_replace($group, ['repository' => 'relative']), + array_replace($group, ['root' => $tmp.'/missing-root']), + array_replace($group, ['gate' => 'missing']), + array_replace($group, ['gate' => 'rounds']), + array_replace($group, ['mainland' => 'missing']), + array_replace($group, ['relay_port' => 'auto']), + array_replace($group, ['relay_port' => 18201]), + array_replace($group, ['relay_port' => 0]), + array_replace($group, ['regions' => [$group['regions'][0], $group['regions'][2]]]), + array_replace($group, ['regions' => [...$group['regions'], $group['regions'][1]]]), + array_replace($group, ['regions' => [...$group['regions'], ['id' => 'more-battle', 'kind' => 'BATTLE', 'port' => 18204]]]), + array_replace($group, ['regions' => [$group['regions'][0], [...$group['regions'][1], 'port' => '18202'], $group['regions'][2]]]), + array_replace($group, ['regions' => [$group['regions'][0], [...$group['regions'][1], 'port' => 18201], $group['regions'][2]]]), + array_replace($group, ['regions' => [$group['regions'][0], [...$group['regions'][1], 'id' => 'unset-battle-dir'], $group['regions'][2]]]), + array_replace($group, ['regions' => [$group['regions'][0], [...$group['regions'][1], 'id' => '../old-status'], $group['regions'][2]]]), + ]; + foreach ($invalid as $index => $candidate) { rejects(fn () => $resolve($candidate), "Invalid configured group #$index fails closed"); } + file_put_contents($file, '{not-json'); + rejects(fn () => TdmGroupConfiguration::profiles($file, $legacy), 'Malformed JSON cannot reenable legacy'); + file_put_contents($file, str_repeat(' ', 1048577)); + rejects(fn () => TdmGroupConfiguration::profiles($file, $legacy), 'Oversized config fails closed'); + rejects(fn () => TdmGroupConfiguration::profiles($tmp.'/missing-parent/tdm.json', $legacy), 'Uninspectable location cannot be called absent'); + unlink($file); + mkdir($file); + rejects(fn () => TdmGroupConfiguration::profiles($file, $legacy), 'A directory in place of the config is not absence'); + rmdir($file); + if (PHP_OS_FAMILY !== 'Windows') { + symlink($tmp.'/missing-target', $file); + rejects(fn () => TdmGroupConfiguration::profiles($file, $legacy), 'A dangling config symlink is not absence'); + unlink($file); + } + unlink($script); + rejects(fn () => $resolve($group), 'Missing coordinator in selected repository fails closed'); + + echo "TDM group configuration contracts passed: $count assertions\n"; +} finally { + cleanFixture($tmp); +} diff --git a/tests/windows/ready.php b/tests/windows/ready.php index c3709362..06cee265 100644 --- a/tests/windows/ready.php +++ b/tests/windows/ready.php @@ -213,9 +213,14 @@ function check(bool $condition, string $message): void { if (!$condition) { thro $timerCount = count($loop->timers); $callback = (new ReflectionProperty(Discord\Helpers\RegisteredCommand::class, 'callback'))->getValue($discord->commands()[$name]); $callback($interaction); - check(count($interaction->responses) === 1 && str_contains($interaction->responses[0][0], 'unavailable') && $interaction->responses[0][1], 'Maintenance command did not fail closed: '.$name); + check(count($interaction->responses) === 1 && str_contains($interaction->responses[0][0], 'operator-managed') && $interaction->responses[0][1], 'Maintenance command did not fail closed: '.$name); check(count($loop->timers) === $timerCount, 'Maintenance command scheduled background work: '.$name); } + // Render the actual bot staff panel without invoking or sending its interactions. + $panel = (new ReflectionMethod(Civ13\Panels::class, 'staffPanel'))->invoke($bot->panels); + $panelJson = json_encode($panel->getComponents(), JSON_THROW_ON_ERROR); + check(!str_contains($panelJson, '"sp_pull"') && !str_contains($panelJson, '"sp_composer"'), 'Retired maintenance buttons rendered'); + check(str_contains($panelJson, 'operator-managed') && str_contains($panelJson, '"sp_refresh"'), 'Staff panel no longer provides guidance or preserves current controls'); (new ReflectionMethod(Civ13\HttpServiceManager::class, '__generateEndpoints'))->invoke($bot->httpServiceManager); if ($hosted) { check(isset($discord->globalCommands->saved['refreshverification'], $discord->commands()['refreshverification']), 'Missing refresh command/listener'); @@ -249,20 +254,44 @@ function check(bool $condition, string $message): void { if (!$condition) { thro $sentinel = "OFFLINE_TEST_SENTINEL=keep-me\n"; file_put_contents($dir.'/.env', $sentinel); $bot->timers['restart_pending'] = $loop->addTimer(99, static function (): void { throw new RuntimeException('Unexpected restart'); }); - foreach (['/reset', '/githubupdated', '/pull', '/update', '/restart', '/kill', '/clearenv', '/cancelupdaterestart'] as $endpoint) { + foreach (['/reset', '/pull', '/update', '/restart', '/kill', '/clearenv', '/cancelupdaterestart'] as $endpoint) { $timersBefore = $loop->timers; $botTimersBefore = $bot->timers; $lookupsBefore = $discord->channelLookups; $handler = $bot->httpServiceManager->httpHandler->offsetGet($endpoint, 'handlers'); check(is_callable($handler), 'Missing maintenance endpoint: '.$endpoint); $response = $handler(new React\Http\Message\ServerRequest('POST', 'http://127.0.0.1'.$endpoint), $endpoint, true); - check($response->getStatusCode() === 503 && str_contains((string) $response->getBody(), 'unavailable'), 'Maintenance endpoint reported success: '.$endpoint); + check($response->getStatusCode() === 410 && str_contains((string) $response->getBody(), 'operator-managed'), 'Maintenance endpoint reported success: '.$endpoint); check($loop->timers === $timersBefore && $bot->timers === $botTimersBefore, 'Maintenance endpoint changed timers: '.$endpoint); check($discord->channelLookups === $lookupsBefore, 'Maintenance endpoint attempted Discord notification: '.$endpoint); check(file_get_contents($dir.'/.env') === $sentinel, 'Maintenance endpoint changed synthetic environment file: '.$endpoint); } + // Call the real HTTP router with inert input so both whitelist and signature admission are exercised. + $router = $bot->httpServiceManager->httpHandler; + $request = static fn (string $endpoint, array $headers = [], string $body = '', string $ip = '203.0.113.8'): React\Http\Message\ServerRequest => + new React\Http\Message\ServerRequest('POST', 'http://127.0.0.1'.$endpoint, $headers, $body, '1.1', ['REMOTE_ADDR' => $ip]); + check($router->handle($request('/reset'))->getStatusCode() === 403, 'Legacy whitelist admission broadened'); + $timersBefore = $loop->timers; + $botTimersBefore = $bot->timers; + $lookupsBefore = $discord->channelLookups; + $body = '{"fixture":true}'; + // A synthetic secret in this subprocess only. No environment file or real signing material is loaded. + putenv('github_secret=offline-maintenance-fixture'); + try { + check($router->handle($request('/githubupdated', [], $body, '203.0.113.9'))->getStatusCode() === 401, 'Unsigned maintenance webhook admitted'); + $signature = 'sha256='.hash_hmac('sha256', $body, 'offline-maintenance-fixture'); + $headers = ['X-Hub-Signature-256' => $signature]; + check($router->handle($request('/githubupdated', $headers, $body.' ', '203.0.113.10'))->getStatusCode() === 401, 'Changed bytes admitted'); + $response = $router->handle($request('/githubupdated', $headers, $body, '203.0.113.11')); + check($response->getStatusCode() === 410 && str_contains((string)$response->getBody(), 'operator-managed'), 'Valid signed webhook did not formally retire'); + } finally { + putenv('github_secret'); + } + check($loop->timers === $timersBefore && $bot->timers === $botTimersBefore, 'Webhook altered timers'); + check($discord->channelLookups === $lookupsBefore, 'Webhook attempted a Discord channel lookup'); + check($router->handle($request('/ping', [], '', '203.0.113.12'))->getStatusCode() === 200, 'Unrelated read-only endpoint changed'); check(!$rejections, 'Bootstrap promise rejected: '.($rejections ? (string) $rejections[0] : '')); - echo ($unconfigured ? "UNCONFIGURED " : "CONFIGURED ")."PASS real init and delayed Slash/Panels bootstrap; global/guild commands and listeners; eight HTTP maintenance guards; no network or loop run\n"; + echo ($unconfigured ? "UNCONFIGURED " : "CONFIGURED ")."PASS real init and delayed Slash/Panels bootstrap; global/guild commands and listeners; legacy HTTP retirement and admission; no network or loop run\n"; } finally { putenv($oldProfile === false ? 'CIVILIZATIONBOT_PROFILE' : 'CIVILIZATIONBOT_PROFILE='.$oldProfile); restore_error_handler(); diff --git a/tests/windows/shell-guard.php b/tests/windows/shell-guard.php index bf19f4ba..04f83dad 100644 --- a/tests/windows/shell-guard.php +++ b/tests/windows/shell-guard.php @@ -9,7 +9,8 @@ function exec(...$args): never { throw new \LogicException('Unexpected legacy ex function proc_get_status(...$args): never { throw new \LogicException('Unexpected legacy process inspection'); } } namespace { - require __DIR__.'/../../vendor/autoload.php'; + $loader = require ($argv[1] ?? __DIR__.'/../../vendor/autoload.php'); + $loader->addPsr4('Civ13\\', __DIR__.'/../../src/Civ13/', true); use Civ13\OSFunctions; final class OfflineMaintenanceMessage extends Discord\Parts\Channel\Message { public array $replies = []; @@ -19,10 +20,26 @@ public function react($emoticon): React\Promise\PromiseInterface { throw new Log } $previous = getenv('CIVILIZATIONBOT_PROFILE'); $expected = 'Legacy shell operations are disabled in Windows/portable mode'; + $bot = (new ReflectionClass(Civ13\Civ13::class))->newInstanceWithoutConstructor(); try { // Native Windows is protected even without a profile; Unix default remains enabled. putenv('CIVILIZATIONBOT_PROFILE'); if (OSFunctions::legacyShellAvailable() !== (PHP_OS_FAMILY !== 'Windows')) { throw new RuntimeException('Default platform policy changed'); } + // Test retired commands with and without a portable profile; the legacy Unix guard + // being enabled must not permit them to spawn, claim success or stop the bot. + foreach (['', 'synthetic-profile'] as $profile) { + $profile === '' ? putenv('CIVILIZATIONBOT_PROFILE') : putenv('CIVILIZATIONBOT_PROFILE='.$profile); + foreach (['UpdateDependencies' => 'updatedeps', 'Stop' => 'stop', 'TypeSpess' => 'ts', 'PullCivRepository' => 'pullrepo'] as $name => $command) { + $class = 'Civ13\\MessageCommand\\Commands\\'.$name; + foreach ($command === 'ts' ? [' on', ' off'] : [''] as $suffix) { + $message = new OfflineMaintenanceMessage(); + (new $class($bot))($message, $command, ['message_content_lower' => $command.$suffix]); + if (count($message->replies) !== 1 || !str_contains($message->replies[0], 'retired') || !str_contains($message->replies[0], 'supervisor')) { + throw new RuntimeException('Did not refuse retired maintenance command: '.$name.$suffix); + } + } + } + } foreach (PHP_OS_FAMILY === 'Windows' ? ['', 'synthetic-profile'] : ['synthetic-profile'] as $profile) { putenv('CIVILIZATIONBOT_PROFILE='.$profile); foreach (['spawnChildProcess', 'execInBackground', 'restart'] as $method) { @@ -33,8 +50,7 @@ static function (Throwable $error) use (&$rejection): void { $rejection = $error ); if (!$rejection instanceof RuntimeException || $rejection->getMessage() !== $expected) { throw new RuntimeException('Missing legacy promise rejection: '.$method); } } - $bot = (new ReflectionClass(Civ13\Civ13::class))->newInstanceWithoutConstructor(); - foreach (['UpdateDependencies', 'PullCivRepository', 'TypeSpess', 'Civ14Host'] as $name) { + foreach (['Civ14Host'] as $name) { $class = 'Civ13\\MessageCommand\\Commands\\'.$name; $message = new OfflineMaintenanceMessage(); (new $class($bot))($message, 'fixture', []);