From 1e2f8aba601e71d7b7943ef2a547ea8745845176 Mon Sep 17 00:00:00 2001 From: admin Date: Tue, 29 Sep 2026 19:07:41 +0800 Subject: [PATCH] feat: refresh admin UI and manage Telegram settings --- docs/PRUNING_REPORT.md | 2 +- .../Controllers/Admin/TelegramController.php | 100 +- web/app/Services/TicketTelegramConfig.php | 460 +++++++++ .../TicketTelegramCredentialCipher.php | 80 ++ web/app/Services/TicketTelegramNotifier.php | 89 +- web/config/.config.php.example | 8 - web/config/routes.php | 2 + web/public/cloud/admin.css | 869 +++++++++++++++++- web/public/cloud/admin.js | 9 +- .../views/venix/admin/cloud/instances.tpl | 43 +- .../views/venix/admin/cloud/orders.tpl | 48 +- .../views/venix/admin/cloud/rescue.tpl | 72 +- .../views/venix/admin/cloud/templates.tpl | 118 ++- .../views/venix/admin/hosts/index.tpl | 171 +++- .../views/venix/admin/telegram/index.tpl | 182 +++- web/resources/views/venix/admin/update.tpl | 81 +- web/resources/views/venix/layout_assets.tpl | 2 +- web/tests/PrunedProjectContractTest.php | 2 +- web/tests/TicketTelegramBoundaryTest.php | 17 +- .../TicketTelegramNotifierSecurityTest.php | 237 ++++- 20 files changed, 2375 insertions(+), 217 deletions(-) create mode 100644 web/app/Services/TicketTelegramConfig.php create mode 100644 web/app/Services/TicketTelegramCredentialCipher.php diff --git a/docs/PRUNING_REPORT.md b/docs/PRUNING_REPORT.md index 942ae4c6..6bdb6432 100644 --- a/docs/PRUNING_REPORT.md +++ b/docs/PRUNING_REPORT.md @@ -26,7 +26,7 @@ - 加密备份保存在 `storage/backups`,不自动删除历史。恢复加密支付设置还需另行保管原应用密钥/环境密钥;仅 SQL 不能替代密钥保管。 - cron 为注释示例,不会在副本中启动自动任务。 -管理员 Telegram:配置示例中的 bot token 和 webhook secret 后,在 `/admin/telegram` 注册 webhook、生成五分钟一次性绑定码,再向机器人私聊发送 `/start 绑定码`。绑定码只存哈希、事务锁消费;Webhook 使用官方 [secret token 请求头](https://core.telegram.org/bots/api#setwebhook) 校验,不在 URL 中传 secret。当前通知仅绑定一个管理员接收方,后台可重新绑定或解绑。 +管理员 Telegram:在 `/admin/telegram` 配置开关、bot token 和独立 HTTPS 通信域名;token 与服务端生成的 webhook secret 使用 purpose-separated 密钥加密存储。升级时会尝试一次性导入旧 `config.php` 值,写入迁移标记后运行期只读数据库;示例配置已删除这些旧项。后台状态展示使用 60 秒 Redis 快照,其中 token 和 secret 始终保持密文,Redis 故障自动回退数据库,配置写入后立即失效快照;Webhook 校验、通知、注册和绑定等运行期凭据始终绕过缓存读取权威数据库。保存后注册 webhook、生成五分钟一次性绑定码,再向机器人私聊发送 `/start 绑定码`。绑定码只存哈希、事务锁消费;Webhook 使用官方 [secret token 请求头](https://core.telegram.org/bots/api#setwebhook) 校验,不在 URL 中传 secret。当前通知仅绑定一个管理员接收方,后台可重新绑定或解绑。 ## 验证及限制 diff --git a/web/app/Controllers/Admin/TelegramController.php b/web/app/Controllers/Admin/TelegramController.php index ae0845f0..b9e882ff 100644 --- a/web/app/Controllers/Admin/TelegramController.php +++ b/web/app/Controllers/Admin/TelegramController.php @@ -5,6 +5,7 @@ namespace App\Controllers\Admin; use App\Controllers\AdminController; use App\Services\AdminPermission; use App\Services\Auth; +use App\Services\TicketTelegramConfig; use App\Services\TicketTelegramNotifier; final class TelegramController extends AdminController @@ -12,14 +13,78 @@ final class TelegramController extends AdminController public function index($request, $response, $args) { $status = TicketTelegramNotifier::bindingStatus(); + try { + $config = TicketTelegramConfig::publicValues(); + } catch (\Throwable $exception) { + $config = [ + 'enabled' => false, + 'webhook_base_url' => '', + 'webhook_url' => '', + 'bot_token_configured' => false, + 'webhook_secret_configured' => false, + 'configured' => false, + 'configuration_error' => 'Telegram 配置读取失败,请检查数据库与 cloud_payload_key', + ]; + } return $this->view() - ->assign('telegram_enabled', TicketTelegramNotifier::enabled()) - ->assign('telegram_configured', TicketTelegramNotifier::configured()) + ->assign('telegram_config', $config) + ->assign('telegram_enabled', $config['enabled']) + ->assign('telegram_configured', $config['configured']) ->assign('telegram_bound', $status['bound']) ->assign('telegram_admin_id', $status['admin_id']) ->display('admin/telegram/index.tpl'); } + public function save($request, $response, $args) + { + if (!$this->canManageBinding()) { + return $response->withJson(['ret' => 0, 'msg' => '你没有权限'], 403); + } + try { + $payload = $this->payload($request); + $config = TicketTelegramConfig::save([ + 'enabled' => $payload['telegram_enabled'] ?? false, + 'webhook_base_url' => $this->scalar($payload, 'telegram_webhook_base_url'), + 'bot_token' => $this->scalar($payload, 'telegram_bot_token'), + 'rotate_secret' => $payload['telegram_rotate_webhook_secret'] ?? false, + ]); + return $response->withJson([ + 'ret' => 1, + 'msg' => 'Telegram 配置已保存;如配置有变化,请重新注册 Webhook', + 'config' => $config, + ]); + } catch (\InvalidArgumentException $exception) { + return $response->withJson(['ret' => 0, 'msg' => $exception->getMessage()], 422); + } catch (\RuntimeException $exception) { + return $response->withJson(['ret' => 0, 'msg' => $this->safeConfigurationMessage($exception)], 422); + } catch (\Throwable $exception) { + error_log('Administrator Telegram configuration save failed'); + return $response->withJson(['ret' => 0, 'msg' => 'Telegram 配置保存失败,请检查数据库日志'], 500); + } + } + + public function rotateSecret($request, $response, $args) + { + if (!$this->canManageBinding()) { + return $response->withJson(['ret' => 0, 'msg' => '你没有权限'], 403); + } + try { + $config = TicketTelegramConfig::rotateWebhookSecret(); + return $response->withJson([ + 'ret' => 1, + 'msg' => 'Webhook 密钥已轮换,请立即重新注册 Webhook', + 'config' => $config, + ]); + } catch (\InvalidArgumentException $exception) { + return $response->withJson(['ret' => 0, 'msg' => $exception->getMessage()], 422); + } catch (\RuntimeException $exception) { + return $response->withJson(['ret' => 0, 'msg' => $this->safeConfigurationMessage($exception)], 422); + } catch (\Throwable $exception) { + error_log('Administrator Telegram webhook secret rotation failed'); + return $response->withJson(['ret' => 0, 'msg' => 'Webhook 密钥轮换失败,请检查数据库日志'], 500); + } + } + public function bind($request, $response, $args) { if (!$this->canManageBinding()) { @@ -63,4 +128,35 @@ final class TelegramController extends AdminController return is_object($user) && !empty($user->is_admin) && (int) ($user->enable ?? 0) === 1 && AdminPermission::isSuperAdmin(); } + + private function payload($request): array + { + $payload = $request !== null && method_exists($request, 'getParsedBody') + ? $request->getParsedBody() + : []; + return is_array($payload) ? $payload : []; + } + + private function scalar(array $payload, string $key): string + { + if (!array_key_exists($key, $payload) || $payload[$key] === null) { + return ''; + } + if (!is_scalar($payload[$key])) { + throw new \InvalidArgumentException('Telegram 配置字段格式无效'); + } + return (string) $payload[$key]; + } + + private function safeConfigurationMessage(\RuntimeException $exception): string + { + $message = $exception->getMessage(); + foreach (['Telegram ', 'PHP sodium ', '请在管理员 Telegram '] as $safePrefix) { + if (str_starts_with($message, $safePrefix)) { + return $message; + } + } + return 'Telegram 配置操作失败,请检查数据库与服务器日志'; + } + } diff --git a/web/app/Services/TicketTelegramConfig.php b/web/app/Services/TicketTelegramConfig.php new file mode 100644 index 00000000..4921a114 --- /dev/null +++ b/web/app/Services/TicketTelegramConfig.php @@ -0,0 +1,460 @@ + $enabled, + 'webhook_base_url' => $baseUrl, + 'webhook_url' => $baseUrl === '' ? '' : $baseUrl . '/telegram_callback', + 'bot_token_configured' => $tokenConfigured, + 'webhook_secret_configured' => $secretConfigured, + 'configured' => $configured, + 'configuration_error' => $configurationError, + ]; + } + + public static function runtime(bool $requireEnabled = true): array + { + // Security-critical credential consumers always use the authoritative + // database. A stale cache must never revive a rotated webhook secret. + $rows = self::authoritativeRows(); + return self::runtimeFromRows($rows, $requireEnabled); + } + + private static function runtimeFromRows(array $rows, bool $requireEnabled): array + { + $enabled = self::truthy($rows[self::ENABLED] ?? 'false'); + if ($requireEnabled && !$enabled) { + throw new \RuntimeException('Telegram 工单提醒尚未启用'); + } + + $baseUrl = self::normalizeWebhookBaseUrl($rows[self::WEBHOOK_BASE_URL] ?? ''); + $token = TicketTelegramCredentialCipher::decrypt((string) ($rows[self::BOT_TOKEN] ?? ''), 'bot_token'); + $secret = TicketTelegramCredentialCipher::decrypt((string) ($rows[self::WEBHOOK_SECRET] ?? ''), 'webhook_secret'); + self::assertBotToken($token); + self::assertWebhookSecret($secret); + if ($baseUrl === '') { + throw new \RuntimeException('请在管理员 Telegram 页面配置独立 HTTPS 通信域名'); + } + + return [ + 'enabled' => $enabled, + 'webhook_base_url' => $baseUrl, + 'bot_token' => $token, + 'webhook_secret' => $secret, + ]; + } + + /** + * Save non-secret settings and optionally replace the bot token. + * An omitted or blank bot_token preserves the existing encrypted token. + */ + public static function save(array $input): array + { + self::migrateLegacyOnce(self::readRows(false)); + $enabled = self::normalizeEnabled($input['enabled'] ?? false); + $baseUrl = self::normalizeWebhookBaseUrl($input['webhook_base_url'] ?? ''); + $newToken = trim((string) ($input['bot_token'] ?? '')); + $rotateSecret = self::normalizeEnabled($input['rotate_secret'] ?? false); + if ($newToken !== '') { + self::assertBotToken($newToken); + } + + if ($enabled && $baseUrl === '') { + throw new \InvalidArgumentException('启用 Telegram 前必须配置独立 HTTPS 通信域名'); + } + + $connection = (new Configurations())->getConnection(); + $connection->transaction(function () use ($enabled, $baseUrl, $newToken, $rotateSecret): void { + // The marker is the serialization lock for configuration writes. + Configurations::where('name', self::MIGRATION_MARKER)->lockForUpdate()->firstOrFail(); + // Configuration writes must never depend on a stale Redis snapshot. + $rows = self::readRows(false); + $existingTokenCipher = trim((string) ($rows[self::BOT_TOKEN] ?? '')); + $tokenCipher = $existingTokenCipher; + $tokenChanged = false; + if ($newToken !== '') { + $oldToken = ''; + if ($existingTokenCipher !== '') { + try { + $oldToken = TicketTelegramCredentialCipher::decrypt($existingTokenCipher, 'bot_token'); + } catch (\Throwable $exception) { + // Supplying a replacement token must be able to repair unreadable legacy data. + $oldToken = ''; + } + } + $tokenChanged = $oldToken === '' || !hash_equals($oldToken, $newToken); + $tokenCipher = TicketTelegramCredentialCipher::encrypt($newToken, 'bot_token'); + } + if ($tokenCipher === '' && $enabled) { + throw new \InvalidArgumentException('启用 Telegram 前必须填写机器人 Token'); + } + if ($enabled) { + $finalToken = $newToken !== '' + ? $newToken + : TicketTelegramCredentialCipher::decrypt($tokenCipher, 'bot_token'); + self::assertBotToken($finalToken); + } + + $secretCipher = trim((string) ($rows[self::WEBHOOK_SECRET] ?? '')); + if ($secretCipher === '' || $rotateSecret) { + $secretCipher = TicketTelegramCredentialCipher::encrypt(self::generateWebhookSecret(), 'webhook_secret'); + } else { + // Refuse to preserve unreadable credentials and report the key problem before writing anything. + self::assertWebhookSecret(TicketTelegramCredentialCipher::decrypt($secretCipher, 'webhook_secret')); + } + self::set(self::ENABLED, $enabled ? 'true' : 'false'); + self::set(self::WEBHOOK_BASE_URL, $baseUrl); + self::set(self::BOT_TOKEN, $tokenCipher); + self::set(self::WEBHOOK_SECRET, $secretCipher); + self::set(self::MIGRATION_MARKER, '1'); + if ($tokenChanged) { + Configurations::where('name', self::BINDING)->delete(); + } + }); + self::invalidateCache(); + + return self::publicValues(); + } + + public static function rotateWebhookSecret(): array + { + self::migrateLegacyOnce(self::readRows(false)); + $cipher = TicketTelegramCredentialCipher::encrypt(self::generateWebhookSecret(), 'webhook_secret'); + $connection = (new Configurations())->getConnection(); + $connection->transaction(function () use ($cipher): void { + Configurations::where('name', self::MIGRATION_MARKER)->lockForUpdate()->firstOrFail(); + self::set(self::WEBHOOK_SECRET, $cipher); + self::set(self::MIGRATION_MARKER, '1'); + }); + self::invalidateCache(); + return self::publicValues(); + } + + private static function migrateLegacyOnce(array $knownRows): void + { + if (($knownRows[self::MIGRATION_MARKER] ?? '') === '1') { + return; + } + self::ensureRow(self::MIGRATION_MARKER, '0'); + $connection = (new Configurations())->getConnection(); + $connection->transaction(function (): void { + $marker = Configurations::where('name', self::MIGRATION_MARKER)->lockForUpdate()->firstOrFail(); + if ((string) $marker->value === '1') { + return; + } + + // Migration and every transaction deliberately bypass Redis. + $existing = self::settingsOnly(self::readRows(false)); + if ($existing === []) { + $enabled = self::truthy(Config::get('enable_telegram', 'false')); + $legacyToken = trim((string) Config::get('telegram_token', '')); + $legacySecret = trim((string) Config::get('telegram_request_token', '')); + $legacyUrl = trim((string) Config::get('tgUrl', '')); + $hasLegacy = $enabled || $legacyToken !== '' || $legacySecret !== '' || $legacyUrl !== ''; + if ($hasLegacy && $legacyUrl === '') { + $legacyUrl = trim((string) Config::get('baseUrl', '')); + } + + $tokenCipher = ''; + $secretCipher = ''; + if ($hasLegacy && self::validBotToken($legacyToken)) { + $tokenCipher = TicketTelegramCredentialCipher::encrypt($legacyToken, 'bot_token'); + } + if ($hasLegacy && !self::validWebhookSecret($legacySecret)) { + $legacySecret = self::generateWebhookSecret(); + } + if ($hasLegacy) { + $secretCipher = TicketTelegramCredentialCipher::encrypt($legacySecret, 'webhook_secret'); + } + $baseUrl = ''; + if ($hasLegacy) { + try { + $baseUrl = self::normalizeWebhookBaseUrl($legacyUrl); + } catch (\InvalidArgumentException $exception) { + // Invalid legacy values must not prevent the administrator from repairing settings. + $baseUrl = ''; + } + } + + self::set(self::ENABLED, $enabled ? 'true' : 'false'); + self::set(self::WEBHOOK_BASE_URL, $baseUrl); + self::set(self::BOT_TOKEN, $tokenCipher); + self::set(self::WEBHOOK_SECRET, $secretCipher); + } + $marker->value = '1'; + $marker->save(); + }); + self::invalidateCache(); + } + + private static function configurationRows(): array + { + $rows = self::readRows(); + if (($rows[self::MIGRATION_MARKER] ?? '') !== '1') { + self::migrateLegacyOnce($rows); + $rows = self::readRows(); + } + return $rows; + } + + private static function authoritativeRows(): array + { + $rows = self::readRows(false); + if (($rows[self::MIGRATION_MARKER] ?? '') !== '1') { + self::migrateLegacyOnce($rows); + $rows = self::readRows(false); + } + return $rows; + } + + /** + * Load only raw database values. Secret values remain encrypted in Redis. + * Passing false is mandatory inside configuration write transactions. + */ + private static function readRows(bool $allowCache = true): array + { + $redis = null; + if ($allowCache) { + try { + $redis = new RedisClient(); + $cached = $redis->getClient()->get(self::CACHE_KEY); + $snapshot = self::decodeCachedSnapshot($cached); + if ($snapshot !== null) { + return $snapshot; + } + } catch (\Throwable $exception) { + // Redis is an optimization only; the database remains authoritative. + } + } + + $rows = self::readDatabaseRows(); + if ($allowCache && self::cacheableSnapshot($rows)) { + try { + $redis = $redis ?? new RedisClient(); + $redis->setex( + self::CACHE_KEY, + self::CACHE_TTL, + json_encode($rows, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES) + ); + } catch (\Throwable $exception) { + // A cache write failure must not make Telegram configuration unavailable. + } + } + return $rows; + } + + private static function readDatabaseRows(): array + { + $rows = []; + foreach (Configurations::whereIn('name', self::SNAPSHOT_KEYS)->get(['name', 'value']) as $row) { + $rows[(string) $row->name] = (string) $row->value; + } + return $rows; + } + + private static function decodeCachedSnapshot($encoded): ?array + { + if (!is_string($encoded) || $encoded === '') { + return null; + } + try { + $rows = json_decode($encoded, true, 16, JSON_THROW_ON_ERROR); + } catch (\Throwable $exception) { + return null; + } + return is_array($rows) && self::cacheableSnapshot($rows) ? $rows : null; + } + + private static function cacheableSnapshot(array $rows): bool + { + foreach (self::SNAPSHOT_KEYS as $key) { + if (!array_key_exists($key, $rows) || !is_string($rows[$key])) { + return false; + } + } + return $rows[self::MIGRATION_MARKER] === '1' + && TicketTelegramCredentialCipher::isCiphertext($rows[self::BOT_TOKEN]) + && TicketTelegramCredentialCipher::isCiphertext($rows[self::WEBHOOK_SECRET]); + } + + private static function settingsOnly(array $rows): array + { + return array_intersect_key($rows, array_fill_keys(self::KEYS, true)); + } + + private static function invalidateCache(): void + { + try { + (new RedisClient())->del(self::CACHE_KEY); + } catch (\Throwable $exception) { + // Redis failure cannot roll back a committed database configuration write. + } + } + + private static function set(string $name, string $value): void + { + $row = Configurations::where('name', $name)->first(); + if ($row === null) { + $row = new Configurations(); + $row->name = $name; + } + $row->value = $value; + $row->save(); + } + + /** Create a configuration row without Eloquent mass assignment. */ + private static function ensureRow(string $name, string $value): void + { + if (Configurations::where('name', $name)->first() !== null) { + return; + } + $row = new Configurations(); + $row->name = $name; + $row->value = $value; + try { + $row->save(); + } catch (\Throwable $exception) { + // A concurrent first request may have inserted the uniquely named row. + if (Configurations::where('name', $name)->first() === null) { + throw $exception; + } + } + } + + private static function normalizeEnabled($value): bool + { + if (is_bool($value)) { + return $value; + } + if (!is_scalar($value) && $value !== null) { + throw new \InvalidArgumentException('Telegram 配置字段格式无效'); + } + $value = strtolower(trim((string) $value)); + if (in_array($value, ['1', 'true', 'yes', 'on'], true)) { + return true; + } + if (in_array($value, ['', '0', 'false', 'no', 'off'], true)) { + return false; + } + throw new \InvalidArgumentException('Telegram 通知开关值无效'); + } + + private static function truthy($value): bool + { + return in_array(strtolower(trim((string) $value)), ['1', 'true', 'yes', 'on'], true); + } + + private static function normalizeWebhookBaseUrl($value): string + { + $value = trim((string) $value); + if ($value === '') { + return ''; + } + if (strlen($value) > 255) { + throw new \InvalidArgumentException('Telegram 通信域名不能超过 255 个字符'); + } + if (filter_var($value, FILTER_VALIDATE_URL) === false) { + throw new \InvalidArgumentException('Telegram 通信域名必须是有效的 HTTPS 地址'); + } + $parts = parse_url($value); + if (!is_array($parts) || strtolower((string) ($parts['scheme'] ?? '')) !== 'https' + || empty($parts['host']) || isset($parts['user']) || isset($parts['pass']) + || isset($parts['query']) || isset($parts['fragment']) + || (!empty($parts['path']) && $parts['path'] !== '/')) { + throw new \InvalidArgumentException('Telegram 通信域名仅支持 https://域名[:端口],不要填写路径、账号或参数'); + } + $host = strtolower((string) $parts['host']); + if (filter_var($host, FILTER_VALIDATE_DOMAIN, FILTER_FLAG_HOSTNAME) === false) { + throw new \InvalidArgumentException('Telegram 通信域名中的主机名无效'); + } + $port = isset($parts['port']) ? ':' . (int) $parts['port'] : ''; + return 'https://' . $host . $port; + } + + private static function assertBotToken(string $token): void + { + if (!self::validBotToken($token)) { + throw new \InvalidArgumentException('Telegram 机器人 Token 格式无效'); + } + } + + private static function validBotToken(string $token): bool + { + return preg_match('/^[1-9][0-9]{4,19}:[A-Za-z0-9_-]{20,128}$/D', $token) === 1; + } + + private static function assertWebhookSecret(string $secret): void + { + if (!self::validWebhookSecret($secret)) { + throw new \InvalidArgumentException('Telegram Webhook 密钥格式无效'); + } + } + + private static function validWebhookSecret(string $secret): bool + { + return preg_match('/^[A-Za-z0-9_-]{16,256}$/D', $secret) === 1; + } + + private static function generateWebhookSecret(): string + { + return rtrim(strtr(base64_encode(random_bytes(32)), '+/', '-_'), '='); + } + + private static function safeConfigurationError(\Throwable $exception): string + { + if (str_contains($exception->getMessage(), 'cloud_payload_key')) { + return 'Telegram 凭据无法解密,请检查 cloud_payload_key 配置'; + } + return 'Telegram 配置无效,请在管理员页面重新保存'; + } +} diff --git a/web/app/Services/TicketTelegramCredentialCipher.php b/web/app/Services/TicketTelegramCredentialCipher.php new file mode 100644 index 00000000..37203a93 --- /dev/null +++ b/web/app/Services/TicketTelegramCredentialCipher.php @@ -0,0 +1,80 @@ + self::KEY], ['value' => '{}']); + self::ensureBindingRow(); (new Configurations())->getConnection()->transaction(function () use ($adminId, $code) { $row = Configurations::where('name', self::KEY)->lockForUpdate()->firstOrFail(); $state = self::readState($row); @@ -63,6 +72,25 @@ final class TicketTelegramNotifier Configurations::where('name', self::KEY)->delete(); } + /** Create the binding state without relying on mass-assignable model attributes. */ + private static function ensureBindingRow(): void + { + if (Configurations::where('name', self::KEY)->first() !== null) { + return; + } + $row = new Configurations(); + $row->name = self::KEY; + $row->value = '{}'; + try { + $row->save(); + } catch (\Throwable $exception) { + // Another request may have created the uniquely named binding row. + if (Configurations::where('name', self::KEY)->first() === null) { + throw $exception; + } + } + } + public static function bindingCommand(array $update): ?array { $message = $update['message'] ?? null; @@ -104,10 +132,8 @@ final class TicketTelegramNotifier public static function notify(string $event, int $ticketId, string $title, string $content): bool { - if (!self::enabled() || !self::configured()) { - return false; - } try { + $config = TicketTelegramConfig::runtime(true); $state = self::readState(Configurations::where('name', self::KEY)->first()); $chatId = $state['chat_id'] ?? null; if ((!is_string($chatId) && !is_int($chatId)) @@ -118,7 +144,7 @@ final class TicketTelegramNotifier $label = in_array($event, ['created', '新工单'], true) ? '新工单' : '工单更新'; $plain = strip_tags($title . "\n" . $content); $text = $label . ' #' . $ticketId . "\n" . mb_substr($plain, 0, 3000, 'UTF-8'); - (new BotApi((string) Config::get('telegram_token')))->call('sendMessage', [ + (new BotApi($config['bot_token']))->call('sendMessage', [ 'chat_id' => (string) $chatId, 'text' => $text, 'disable_web_page_preview' => 'true', @@ -133,17 +159,15 @@ final class TicketTelegramNotifier public static function registerWebhook(): bool { - $baseUrl = rtrim((string) Config::get('baseUrl', ''), '/'); - $parts = parse_url($baseUrl); - if (!self::enabled() || !self::configured() || !is_array($parts) - || ($parts['scheme'] ?? '') !== 'https' || empty($parts['host']) - || isset($parts['user']) || isset($parts['pass']) || isset($parts['query']) || isset($parts['fragment'])) { - throw new \RuntimeException('请检查 Telegram 配置与网站 HTTPS baseUrl'); + try { + $config = TicketTelegramConfig::runtime(true); + } catch (\Throwable $exception) { + throw new \RuntimeException(self::safeConfigurationMessage($exception)); } try { - $result = (new BotApi((string) Config::get('telegram_token')))->call('setWebhook', [ - 'url' => $baseUrl . '/telegram_callback', - 'secret_token' => (string) Config::get('telegram_request_token'), + $result = (new BotApi($config['bot_token']))->call('setWebhook', [ + 'url' => $config['webhook_base_url'] . '/telegram_callback', + 'secret_token' => $config['webhook_secret'], 'allowed_updates' => '["message"]', ], 10); if ($result !== true) { @@ -161,6 +185,25 @@ final class TicketTelegramNotifier return is_array($state) ? $state : []; } + private static function safeConfigurationMessage(\Throwable $exception): string + { + $message = $exception->getMessage(); + foreach ([ + 'Telegram 工单提醒', + 'Telegram 凭据', + 'Telegram 机器人 Token', + 'Telegram Webhook 密钥', + 'Telegram 通信域名', + 'PHP sodium ', + '请在管理员 Telegram ', + ] as $safePrefix) { + if (str_starts_with($message, $safePrefix)) { + return $message; + } + } + return 'Telegram 配置读取失败,请检查数据库与服务器日志'; + } + private static function eligibleAdmin(int $adminId): bool { $allowed = array_map('intval', explode(',', (string) Config::get('super_admin', ''))); diff --git a/web/config/.config.php.example b/web/config/.config.php.example index 2b4cd268..d2d6bab2 100644 --- a/web/config/.config.php.example +++ b/web/config/.config.php.example @@ -91,14 +91,6 @@ $System_Config['notify_limit_value'] = '10000'; //当上一项为per时,此 $System_Config['notify_url']='https://xxx.com/paytaro/callback'; -#---------------------Telegram------------------------ -#telegram bot,是否启用 -$System_Config['enable_telegram']='false'; -#telegram bot,bot 的 token ,跟 father bot 申请 -$System_Config['telegram_token']=''; -#仅管理员工单通知。Webhook secret:16–256 位大小写英文、数字、下划线或短横线;在管理员 Telegram 页绑定。 -$System_Config['telegram_request_token']=''; - #---------------------网站基础配置------------------------ // !!! 修改此key为随机字符串确保网站安全 !!! $System_Config['key'] = ''; diff --git a/web/config/routes.php b/web/config/routes.php index 582cd59a..4b979e8c 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -166,6 +166,8 @@ $app->group('/admin', function () { $this->get('/cloud/orders', 'App\Controllers\Admin\CloudPageController:orders'); $this->get('/update', 'App\Controllers\Admin\CloudPageController:update')->add(new SuperAdmin()); $this->get('/telegram', 'App\Controllers\Admin\TelegramController:index'); + $this->post('/telegram/config', 'App\Controllers\Admin\TelegramController:save')->add(new SuperAdmin()); + $this->post('/telegram/secret/rotate', 'App\Controllers\Admin\TelegramController:rotateSecret')->add(new SuperAdmin()); $this->post('/telegram/bind', 'App\Controllers\Admin\TelegramController:bind')->add(new SuperAdmin()); $this->post('/telegram/unbind', 'App\Controllers\Admin\TelegramController:unbind')->add(new SuperAdmin()); $this->post('/telegram/webhook', 'App\Controllers\Admin\TelegramController:webhook')->add(new SuperAdmin()); diff --git a/web/public/cloud/admin.css b/web/public/cloud/admin.css index 118d6d76..f7060fae 100644 --- a/web/public/cloud/admin.css +++ b/web/public/cloud/admin.css @@ -1,17 +1,852 @@ -/* Scoped to cloud admin page content. Never load client styles in venix. */ -.cloud-admin { margin: 24px 0; } -.cloud-admin .cloud-admin-grid { display: grid; grid-template-columns: minmax(240px, 1fr) minmax(320px, 1.5fr); gap: 24px; } -.cloud-admin .cloud-admin-imports { display: grid; gap: 24px; align-content: start; } -.cloud-admin .cloud-admin-form-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; } -.cloud-admin .cloud-admin-full { grid-column: 1 / -1; } -.cloud-admin .cloud-admin-host { display: block; width: 100%; text-align: left; margin: 8px 0; } -.cloud-admin .cloud-admin-row { display: flex; align-items: center; flex-wrap: wrap; gap: 12px; border-bottom: 1px solid #dce3ed; padding: 16px 0; } -.cloud-admin .cloud-admin-row input { flex: 1; min-width: 180px; } -.cloud-admin .cloud-admin-row .cloud-admin-meta { flex-basis: 100%; overflow-wrap: anywhere; color: #7b8795; } -.cloud-admin .cloud-admin-notice { white-space: pre-wrap; overflow-wrap: anywhere; } -.cloud-admin table td { overflow-wrap: anywhere; max-width: 300px; } -.cloud-update .cloud-update-details { display: grid; gap: 10px; margin-bottom: 18px; } -.cloud-update .cloud-update-details > div { display: grid; grid-template-columns: minmax(110px, .45fr) minmax(0, 1.55fr); gap: 14px; } -.cloud-update .cloud-update-details dt { color: #7b8795; font-weight: 500; } -.cloud-update .cloud-update-details dd { margin: 0; overflow-wrap: anywhere; font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; } -@media (max-width: 900px) { .cloud-admin .cloud-admin-grid, .cloud-admin .cloud-admin-form-grid { grid-template-columns: 1fr; } } +/* Venix administrator theme extensions for virtualization pages. */ +.cloud-admin { + padding-bottom: 24px; + color: #1d2939; +} + +.cloud-admin *, +.cloud-admin *::before, +.cloud-admin *::after { + box-sizing: border-box; +} + +.cloud-admin-page-head { + gap: 20px; +} + +.cloud-admin-page-head > .flex-grow-1 { + min-width: 0; +} + +.cloud-admin-page-head h4, +.cloud-admin-card-head h5, +.cloud-admin-section-title h6 { + color: #00081a; +} + +.cloud-admin-page-head .text-muted, +.cloud-admin-card-head .text-muted { + max-width: 840px; + line-height: 1.6; +} + +.cloud-admin-actions { + display: flex; + align-items: center; + justify-content: flex-end; + flex-wrap: wrap; + gap: 10px; +} + +.cloud-admin-notice { + min-height: 38px; + display: inline-flex; + align-items: center; + max-width: min(620px, 100%); + margin: 0; + padding: 8px 12px; + border: 0; + border-radius: 8px; + font-weight: 800; + line-height: 1.4; + text-align: left; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.cloud-admin-notice.alert-info { + color: #7a4a00; + background: rgba(239, 177, 0, 0.16); +} + +.cloud-admin-notice.alert-success { + color: #08785b; + background: rgba(93, 216, 158, 0.16); +} + +.cloud-admin-notice.alert-warning { + color: #7a4a00; + background: rgba(239, 177, 0, 0.18); +} + +.cloud-admin-notice.alert-danger { + color: #b42318; + background: rgba(251, 44, 54, 0.12); +} + +.cloud-admin .card { + border: 1px solid #e5ebf2; + border-radius: 10px; + box-shadow: 0 8px 28px rgba(0, 8, 26, 0.045); +} + +.cloud-admin .card-body { + padding: 22px; +} + +.cloud-admin-grid { + display: grid; + grid-template-columns: minmax(280px, 0.92fr) minmax(420px, 1.35fr); + gap: 18px; + align-items: start; +} + +.cloud-admin-host-layout { + grid-template-columns: minmax(260px, 0.68fr) minmax(540px, 1.5fr); +} + +.cloud-admin-catalog-layout { + grid-template-columns: minmax(360px, 0.95fr) minmax(440px, 1.2fr); +} + +.cloud-admin-rescue-layout, +.cloud-update-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); +} + +.cloud-admin-imports, +.cloud-admin-side, +.cloud-admin-fields { + display: grid; + gap: 16px; +} + +.cloud-admin-side { + position: sticky; + top: 92px; +} + +.cloud-admin-card-head { + min-width: 0; + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 18px; + margin-bottom: 20px; +} + +.cloud-admin-card-head > div { + min-width: 0; +} + +.cloud-admin-card-head-compact { + align-items: center; + margin-bottom: 0; +} + +.cloud-admin-card-icon { + width: 50px; + height: 50px; + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + border-radius: 9px; + color: #08785b; + background: rgba(93, 216, 158, 0.16); + font-size: 24px; +} + +.cloud-admin-card-icon.is-warning { + color: #9a5d00; + background: rgba(239, 177, 0, 0.18); +} + +.cloud-admin-guidance { + display: flex; + align-items: flex-start; + gap: 12px; + margin-bottom: 18px; + padding: 14px 16px; + border: 1px solid rgba(93, 216, 158, 0.3); + border-radius: 9px; + color: #315a50; + background: rgba(93, 216, 158, 0.09); + line-height: 1.6; +} + +.cloud-admin-guidance.alert-warning { + border-color: rgba(239, 177, 0, 0.36); + color: #6e4b0b; + background: rgba(239, 177, 0, 0.11); +} + +.cloud-admin-guidance > i { + flex: 0 0 auto; + margin-top: 1px; + font-size: 21px; +} + +.cloud-admin-feature-copy { + min-width: 0; + display: flex; + align-items: center; + gap: 14px; +} + +.cloud-admin-feature-actions { + display: flex; + align-items: center; + justify-content: flex-end; + flex-wrap: wrap; + gap: 14px; +} + +.cloud-admin-switch { + display: inline-flex; + align-items: center; + gap: 9px; + margin: 0; + color: #344054; + font-weight: 800; + cursor: pointer; +} + +.cloud-admin-switch input { + position: absolute; + width: 1px; + height: 1px; + opacity: 0; +} + +.cloud-admin-switch > span { + position: relative; + width: 42px; + height: 24px; + flex: 0 0 auto; + border-radius: 999px; + background: #cbd5e1; + transition: background 0.18s ease; +} + +.cloud-admin-switch > span::after { + content: ""; + position: absolute; + top: 3px; + left: 3px; + width: 18px; + height: 18px; + border-radius: 50%; + background: #fff; + box-shadow: 0 1px 4px rgba(0, 8, 26, 0.22); + transition: transform 0.18s ease; +} + +.cloud-admin-switch input:checked + span { + background: #18a87f; +} + +.cloud-admin-switch input:checked + span::after { + transform: translateX(18px); +} + +.cloud-admin-switch input:focus-visible + span { + outline: 3px solid rgba(24, 168, 127, 0.2); + outline-offset: 2px; +} + +.cloud-admin-switch input:disabled ~ * { + opacity: 0.58; + cursor: not-allowed; +} + +.cloud-admin-host-list, +.cloud-admin-catalog-list { + display: grid; + gap: 10px; +} + +.cloud-admin-host-list { + max-height: 520px; + overflow-y: auto; + padding-right: 3px; +} + +.cloud-admin .cloud-admin-host { + position: relative; + width: 100%; + min-height: 64px; + display: block; + margin: 0; + padding: 12px 42px 12px 14px; + border: 1px solid #dce5ef; + border-radius: 8px; + color: #00081a; + background: #fbfcfe; + text-align: left; + transition: border-color 0.18s ease, background 0.18s ease, transform 0.18s ease; +} + +.cloud-admin .cloud-admin-host::after { + content: "\F0142"; + position: absolute; + top: 50%; + right: 14px; + color: #8a99aa; + font-family: "Material Design Icons"; + font-size: 20px; + transform: translateY(-50%); +} + +.cloud-admin .cloud-admin-host:hover, +.cloud-admin .cloud-admin-host:focus-visible { + border-color: rgba(93, 216, 158, 0.62); + color: #08785b; + background: rgba(93, 216, 158, 0.08); + transform: translateY(-1px); +} + +.cloud-admin .cloud-admin-host strong { + display: block; + margin-bottom: 3px; + font-weight: 900; +} + +.cloud-admin .cloud-admin-host .text-muted { + font-size: 13px; + font-weight: 700; +} + +.cloud-admin-guide-card { + background: linear-gradient(145deg, rgba(93, 216, 158, 0.09), #fff 68%); +} + +.cloud-admin-form-section { + padding: 20px 0; + border-top: 1px solid #e8eef5; +} + +.cloud-admin-form-section:first-of-type { + padding-top: 2px; + border-top: 0; +} + +.cloud-admin-section-title { + display: grid; + grid-template-columns: 42px minmax(0, 1fr); + gap: 12px; + align-items: center; + margin-bottom: 16px; +} + +.cloud-admin-section-title > span { + width: 42px; + height: 42px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 8px; + color: #08785b; + background: rgba(93, 216, 158, 0.14); + font-size: 21px; +} + +.cloud-admin-section-title h6, +.cloud-admin-section-title p { + margin: 0; +} + +.cloud-admin-section-title h6 { + font-size: 15px; + font-weight: 900; +} + +.cloud-admin-section-title p { + margin-top: 3px; + color: #7c8ba0; + font-size: 13px; + font-weight: 700; +} + +.cloud-admin-form-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; +} + +.cloud-admin-full { + grid-column: 1 / -1; +} + +.cloud-admin .form-label { + margin-bottom: 7px; + color: #344054; + font-weight: 800; +} + +.cloud-admin .form-control, +.cloud-admin .form-select { + min-height: 44px; + border-color: #dce5ef; + border-radius: 8px; + color: #1d2939; + background-color: #fff; +} + +.cloud-admin textarea.form-control { + min-height: 112px; + line-height: 1.55; + resize: vertical; +} + +.cloud-admin .form-control:focus, +.cloud-admin .form-select:focus { + border-color: rgba(24, 168, 127, 0.62); + box-shadow: 0 0 0 3px rgba(24, 168, 127, 0.1); +} + +.cloud-admin .form-text { + margin-top: 7px; + color: #7c8ba0; + line-height: 1.5; +} + +.cloud-admin-fingerprint-box { + padding: 14px; + border: 1px solid #dce5ef; + border-radius: 8px; + background: #fbfcfe; +} + +.cloud-admin-fingerprint { + min-height: 0; + margin: 12px 0; + color: #08785b; + font-size: 13px; + white-space: pre-wrap; + overflow-wrap: anywhere; +} + +.cloud-admin-fingerprint:empty { + display: none; +} + +.cloud-admin-form-footer, +.cloud-admin-submit, +.cloud-admin-form-actions, +.cloud-update-actions { + display: flex; + align-items: center; + justify-content: space-between; + flex-wrap: wrap; + gap: 12px; +} + +.cloud-admin-form-footer { + padding-top: 18px; + border-top: 1px solid #e8eef5; +} + +.cloud-admin-submit, +.cloud-admin-form-actions, +.cloud-update-actions { + justify-content: flex-end; +} + +.cloud-admin-form-actions { + margin-top: 20px; +} + +.cloud-admin-submit #host-form-error { + max-width: 420px; + font-weight: 700; + overflow-wrap: anywhere; +} + +.cloud-admin-filter-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 24px; +} + +.cloud-admin-select-wrap { + position: relative; + width: min(420px, 100%); + flex: 0 1 420px; +} + +.cloud-admin-select-wrap > i { + position: absolute; + top: 50%; + left: 14px; + z-index: 2; + color: #08785b; + font-size: 20px; + pointer-events: none; + transform: translateY(-50%); +} + +.cloud-admin-select-wrap .form-select { + padding-left: 44px; + font-weight: 800; +} + +.cloud-admin-catalog-card { + position: sticky; + top: 92px; +} + +.cloud-admin-row { + display: grid; + grid-template-columns: minmax(180px, 1fr) auto auto; + gap: 9px; + align-items: center; + padding: 13px; + border: 1px solid #dce5ef; + border-radius: 8px; + background: #fbfcfe; +} + +.cloud-admin-row:hover { + border-color: rgba(93, 216, 158, 0.55); + background: rgba(93, 216, 158, 0.06); +} + +.cloud-admin-row .cloud-admin-meta { + grid-column: 1 / -1; + color: #7c8ba0; + font-size: 13px; + font-weight: 700; + overflow-wrap: anywhere; +} + +.cloud-admin-catalog-list > .text-muted { + margin: 0; + padding: 24px; + border: 1px dashed #dce5ef; + border-radius: 8px; + background: #fbfcfe; + text-align: center; + font-weight: 800; +} + +.cloud-admin-support-note, +.cloud-update-warning { + display: flex; + align-items: flex-start; + gap: 9px; + margin: 18px 0 0; + padding: 12px 14px; + border-radius: 8px; + color: #526579; + background: #f4f7fa; + font-size: 13px; + font-weight: 700; + line-height: 1.55; +} + +.cloud-admin-support-note i, +.cloud-update-warning i { + flex: 0 0 auto; + color: #08785b; + font-size: 19px; +} + +.cloud-admin-table-card .card-body { + padding: 0; +} + +.cloud-admin-table-card .cloud-admin-card-head { + margin: 0; + padding: 22px; + border-bottom: 1px solid #e8eef5; +} + +.cloud-admin-table-wrap { + overflow-x: auto; + -webkit-overflow-scrolling: touch; +} + +.cloud-admin-table { + min-width: 820px; +} + +.cloud-admin-table thead th { + padding: 13px 16px; + border-bottom: 1px solid #e2e9f0; + color: #718096; + background: #f7f9fc; + font-size: 12px; + font-weight: 900; + letter-spacing: 0.02em; + text-transform: uppercase; + white-space: nowrap; +} + +.cloud-admin-table td { + max-width: 320px; + padding: 15px 16px; + border-color: #edf1f5; + color: #344054; + font-weight: 700; + line-height: 1.55; + overflow-wrap: anywhere; +} + +.cloud-admin-table tbody tr:last-child td { + border-bottom: 0; +} + +.cloud-admin-placeholder td { + padding: 32px; + color: #7c8ba0; + text-align: center; +} + +.cloud-update-details { + display: grid; + gap: 0; + margin: 0 0 20px; + border: 1px solid #e5ebf2; + border-radius: 8px; + overflow: hidden; +} + +.cloud-update-details > div { + display: grid; + grid-template-columns: minmax(112px, 0.42fr) minmax(0, 1.58fr); + gap: 14px; + padding: 12px 14px; + border-bottom: 1px solid #e8eef5; + background: #fbfcfe; +} + +.cloud-update-details > div:last-child { + border-bottom: 0; +} + +.cloud-update-details dt { + color: #7b8795; + font-weight: 800; +} + +.cloud-update-details dd { + min-width: 0; + margin: 0; + color: #172033; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 13px; + font-weight: 700; + overflow-wrap: anywhere; +} + +.cloud-update-credential { + padding: 16px; + border: 1px solid #e5ebf2; + border-radius: 8px; + background: #fff; +} + +.cloud-update-job-details { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 1px; + border: 0; + background: #e8eef5; +} + +.cloud-update-job-details > div { + grid-template-columns: minmax(90px, 0.38fr) minmax(0, 1fr); + border: 0; +} + +.cloud-update-warning { + color: #6e4b0b; + background: rgba(239, 177, 0, 0.11); +} + +.cloud-update-warning i { + color: #9a5d00; +} + +@media (max-width: 1199.98px) { + .cloud-admin-host-layout, + .cloud-admin-catalog-layout { + grid-template-columns: minmax(240px, 0.72fr) minmax(430px, 1.28fr); + } + + .cloud-admin-feature-card .cloud-admin-card-head { + align-items: flex-start; + } +} + +@media (max-width: 991.98px) { + .cloud-admin-grid, + .cloud-admin-host-layout, + .cloud-admin-catalog-layout, + .cloud-admin-rescue-layout, + .cloud-update-grid { + grid-template-columns: minmax(0, 1fr); + } + + .cloud-admin-side, + .cloud-admin-catalog-card { + position: static; + } + + .cloud-admin-host-list { + max-height: none; + } + + .cloud-update-job-details { + grid-template-columns: minmax(0, 1fr); + } +} + +@media (max-width: 767.98px) { + .cloud-admin-page-head { + align-items: stretch !important; + flex-direction: column !important; + } + + .cloud-admin-actions, + .cloud-admin-notice { + width: 100%; + } + + .cloud-admin-actions .btn { + flex: 1 1 auto; + } + + .cloud-admin .card-body, + .cloud-admin-table-card .cloud-admin-card-head { + padding: 18px; + } + + .cloud-admin-feature-card .cloud-admin-card-head, + .cloud-admin-feature-actions, + .cloud-admin-filter-row { + align-items: stretch; + flex-direction: column; + } + + .cloud-admin-feature-actions, + .cloud-admin-feature-actions .btn, + .cloud-admin-select-wrap { + width: 100%; + } + + .cloud-admin-form-grid { + grid-template-columns: minmax(0, 1fr); + } + + .cloud-admin-full { + grid-column: auto; + } + + .cloud-admin-table-wrap { + padding: 12px; + overflow-x: visible; + } + + .cloud-admin-table, + .cloud-admin-table tbody, + .cloud-admin-table tr, + .cloud-admin-table td { + display: block; + width: 100%; + } + + .cloud-admin-table { + min-width: 0; + } + + .cloud-admin-table thead { + display: none; + } + + .cloud-admin-table tr { + margin-bottom: 12px; + padding: 12px 14px; + border: 1px solid #dce5ef; + border-radius: 8px; + background: #fff; + } + + .cloud-admin-table tr:last-child { + margin-bottom: 0; + } + + .cloud-admin-table td { + max-width: none; + display: grid; + grid-template-columns: minmax(92px, 0.36fr) minmax(0, 1fr); + gap: 12px; + padding: 8px 0; + border: 0; + } + + .cloud-admin-table td::before { + content: attr(data-label); + color: #718096; + font-size: 12px; + font-weight: 900; + text-transform: uppercase; + } + + .cloud-admin-placeholder td { + display: block; + padding: 22px 0; + text-align: center; + } + + .cloud-admin-placeholder td::before { + content: none; + } + + .cloud-update-details > div, + .cloud-update-job-details > div { + grid-template-columns: minmax(0, 1fr); + gap: 4px; + } +} + +@media (max-width: 575.98px) { + .cloud-admin-card-head:not(.cloud-admin-card-head-compact) { + align-items: flex-start; + } + + .cloud-admin-card-icon { + width: 44px; + height: 44px; + font-size: 21px; + } + + .cloud-admin-row { + grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + } + + .cloud-admin-row .form-control, + .cloud-admin-row .cloud-admin-meta { + grid-column: 1 / -1; + } + + .cloud-admin-row .btn { + width: 100%; + } + + .cloud-admin-form-footer, + .cloud-admin-submit, + .cloud-admin-form-actions, + .cloud-update-actions { + align-items: stretch; + flex-direction: column; + } + + .cloud-admin-form-footer .btn, + .cloud-admin-submit, + .cloud-admin-submit .btn, + .cloud-admin-form-actions .btn, + .cloud-update-actions .btn { + width: 100%; + } + + .cloud-admin-feature-copy { + align-items: flex-start; + } + + .cloud-admin-table td { + grid-template-columns: minmax(0, 1fr); + gap: 3px; + } +} diff --git a/web/public/cloud/admin.js b/web/public/cloud/admin.js index d398dbc1..4e887007 100644 --- a/web/public/cloud/admin.js +++ b/web/public/cloud/admin.js @@ -235,6 +235,9 @@ async function records() { const tbody = byId('admin-records'); tbody.replaceChildren(); for (const record of entries) { const row = element('tr'); + const labels = kind === 'instances' + ? ['实例', '用户', '宿主机', '状态', '公网 IP', '配置'] + : ['任务', '用户', '套餐', '金额', '状态', '实例 / 引擎任务', '时间 / 错误']; const fields = kind === 'instances' ? [record.name || record.id, record.owner_email || record.user_email || record.owner_user_id || record.user_id, record.host_name || record.host_id, record.state || record.status, @@ -244,7 +247,11 @@ async function records() { record.amount || record.price, orderStatus(record.status), `${record.instance_id ? `实例 #${record.instance_id}` : '实例 —'} / ${record.job_id ? `任务 #${record.job_id}` : '任务 —'}${Number(record.attempts) > 0 ? ` · 尝试 ${record.attempts}` : ''}`, `${unixTime(record.updated_at || record.created_at)}${record.error ? ' · ' + record.error : ''}`]; - for (const field of fields) row.append(element('td', '', field ?? '—')); + fields.forEach((field, index) => { + const cell = element('td', '', field ?? '—'); + cell.dataset.label = labels[index]; + row.append(cell); + }); tbody.append(row); } notice(`已加载 ${entries.length} 条记录。`); diff --git a/web/resources/views/venix/admin/cloud/instances.tpl b/web/resources/views/venix/admin/cloud/instances.tpl index 3211edd7..0514a689 100644 --- a/web/resources/views/venix/admin/cloud/instances.tpl +++ b/web/resources/views/venix/admin/cloud/instances.tpl @@ -1,2 +1,41 @@ -{assign var=admin_title value='虚拟机实例'}{assign var=admin_active value='cloud_instances'}{include file='admin/static_header.tpl'} -

虚拟机实例

跨宿主机查看已关联的实例和所属用户。客户的资源与操作权限由后台校验。

正在加载…

实例用户宿主机状态公网 IP配置
{include file='admin/static_footer.tpl'} +{assign var=admin_title value='虚拟机实例'} +{assign var=admin_active value='cloud-instances'} +{include file='admin/static_header.tpl'} + + +
+
+
+

Compute

+

虚拟机实例

+

跨宿主机查看已关联的实例、所属用户与资源配置。

+
+
+

正在加载…

+ +
+
+ +
+
+
+
+

Instances

+
实例目录
+

客户资源与操作权限仍由后台校验,此页面仅用于集中查看。

+
+ +
+
+ + + +
实例用户宿主机状态公网 IP配置
实例数据加载中
+
+
+
+
+ +{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/cloud/orders.tpl b/web/resources/views/venix/admin/cloud/orders.tpl index 3a3b99a2..dad764bf 100644 --- a/web/resources/views/venix/admin/cloud/orders.tpl +++ b/web/resources/views/venix/admin/cloud/orders.tpl @@ -1,2 +1,46 @@ -{assign var=admin_title value='开通任务'}{assign var=admin_active value='cloud-orders'}{include file='admin/static_header.tpl'} -

实例开通任务

用户提交部署后先生成开通账单,只有账单支付成功才会在此进入创建队列。失败或不确定的任务需核查实际宿主机状态,不要重复创建或扣款。

正在加载…

任务用户套餐金额状态实例 / 引擎任务时间 / 错误
{include file='admin/static_footer.tpl'} +{assign var=admin_title value='开通任务'} +{assign var=admin_active value='cloud-orders'} +{include file='admin/static_header.tpl'} + + +
+
+
+

Provisioning

+

实例开通任务

+

跟踪账单支付后的创建队列、引擎任务与异常结果。

+
+
+

正在加载…

+ +
+
+ +
+ + 失败或不确定的任务需先核查实际宿主机状态,避免重复创建实例或重复扣款。 +
+ +
+
+
+
+

Tasks

+
任务记录
+

只有账单支付成功后,部署请求才会进入创建队列。

+
+ +
+
+ + + +
任务用户套餐金额状态实例 / 引擎任务时间 / 错误
任务数据加载中
+
+
+
+
+ +{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/cloud/rescue.tpl b/web/resources/views/venix/admin/cloud/rescue.tpl index 7eb15eca..ab269418 100644 --- a/web/resources/views/venix/admin/cloud/rescue.tpl +++ b/web/resources/views/venix/admin/cloud/rescue.tpl @@ -1,4 +1,70 @@ -{assign var=admin_title value='救援模版'}{assign var=admin_active value='cloud_rescue'}{include file='admin/static_header.tpl'} - -

救援模版

只支持可启动 ISO,上传至所选宿主机的独立救援目录;不会混入普通安装 ISO 列表。救援系统自身决定登录方式。

正在加载…

上传救援 ISO

上传大小还受 PHP、Web 服务器及反代限制;完成前请勿关闭页面。

救援 ISO 列表
+{assign var=admin_title value='救援模版'} +{assign var=admin_active value='cloud-rescue'} +{include file='admin/static_header.tpl'} + + +
+
+
+

Recovery

+

救援模版

+

按宿主机维护独立的可启动救援 ISO。

+
+
+

正在加载…

+
+
+ +
+
+
+
+

Target host

+
选择宿主机
+

救援 ISO 只上传到当前选择的宿主机,不会混入普通安装 ISO。

+
+
+ + + +
+
+
+
+ +
+
+
+
+
+

Upload

+
上传救援 ISO
+

救援系统自身决定登录方式。

+
+ +
+
+
+
只支持可启动 ISO,上传大小还受 PHP、Web 服务器及反代限制;完成前请勿关闭页面。
+
+
+
+
+ +
+
+
+
+

Catalog

+
救援 ISO 列表
+

这里仅显示当前宿主机已经保存的救援介质。

+
+ +
+
+
+
+
+
+ {include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/cloud/templates.tpl b/web/resources/views/venix/admin/cloud/templates.tpl index 0fb1eb9d..36370083 100644 --- a/web/resources/views/venix/admin/cloud/templates.tpl +++ b/web/resources/views/venix/admin/cloud/templates.tpl @@ -1,46 +1,86 @@ -{assign var=admin_title value='云镜像模版'}{assign var=admin_active value='cloud_templates'}{include file='admin/static_header.tpl'} - +{assign var=admin_title value='云镜像模版'} +{assign var=admin_active value='cloud-templates'} +{include file='admin/static_header.tpl'} + +
-

云镜像模版

-

这里维护全局云镜像目录,普通用户在所有可售地区看到同一份镜像列表。宿主机副本由引擎按需准备。删除会同时退役全局源镜像并异步清理宿主机缓存;已创建实例使用独立克隆磁盘,不受影响。当前支持 AlmaLinux 8/9/10、Debian 11/12/13、CentOS Stream 9/10,以及 Ubuntu 20.04/22.04/24.04/25.04/25.10/26.04 x86_64 cloud-init 云镜像。升级前按宿主机导入的旧镜像不会自动进入全局目录,请重新导入一次。

-

正在加载…

-
-
-
-
-
从官方地址下载
- - - - -

请粘贴受支持发行版官方镜像站的 HTTPS 文件地址,不能是下载介绍页;引擎只会跟随由官方入口返回且通过公网地址安全校验的跳转链。文件名应为 .qcow2;Ubuntu 官方 .img 也可使用,但其实际内容必须是 qcow2。

- - -

留空时面板会计算并保存实际 SHA-256,不与外部校验值比对;填写后则会在导入前核对。

- +
+
+

Images

+

云镜像模版

+

维护所有可售地区共用的 cloud-init 系统镜像目录。

- -
-
-
从本机上传 QCOW2
- - - - - - -

只接受独立、未加密且不含 backing file 的 QCOW2,面板会自动计算并保存 SHA-256。系统及版本用于用户部署页分类,请务必与镜像内容一致。上传期间请勿关闭页面;大小还受 PHP、Web 服务器及反代配置限制。

- +
+

正在加载…

+
+
+ +
+ + 删除会退役全局源镜像并异步清理宿主机缓存;已经创建的实例使用独立克隆磁盘,不受影响。 +
+ +
+
+ +
+
+
+

Remote

+
从官方地址下载
+

由引擎安全下载并校验官方云镜像。

+
+ +
+
+
+
请填写镜像文件直链而非介绍页。仅允许受支持发行版的官方入口及通过公网安全校验的跳转链。
+
留空时保存实际校验值;填写后会在导入前严格核对。
+
+
+
+ + +
+
+
+
+

Upload

+
从本机上传 QCOW2
+

上传本地制作并完成清理的独立镜像。

+
+ +
+
+
+
+
只接受未加密且不含 backing file 的独立 QCOW2。系统版本必须与镜像内容一致,上传期间请勿关闭页面。
+
+
+
+
+
+ +
+
+
+
+

Catalog

+
已保存的模版
+

宿主机副本由引擎按需准备。

+
+ +
+
+

支持 AlmaLinux 8/9/10、Debian 11/12/13、CentOS Stream 9/10,以及 Ubuntu 20.04 至 26.04 的 x86_64 cloud-init 镜像。

+
-
-
已保存的模版
-
{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/hosts/index.tpl b/web/resources/views/venix/admin/hosts/index.tpl index 2d209d35..55e7ceba 100644 --- a/web/resources/views/venix/admin/hosts/index.tpl +++ b/web/resources/views/venix/admin/hosts/index.tpl @@ -1,39 +1,148 @@ {assign var=admin_title value='宿主机设置'} {assign var=admin_active value='hosts'} {include file='admin/static_header.tpl'} - + +
-

宿主机设置

SSH 使用宿主机已有的 root 账号和私钥。先扫描并核对 SSH 主机指纹,再保存。私钥和口令加密存储,不会回显;后台会持续采集虚拟机指标。

-

正在加载…

-
-
-
用户 ISO 功能
-

默认关闭。关闭后普通用户看不到 ISO 导航和页面,相关读取、导入、任务及删除接口也会拒绝访问。

- -
+
+
+

Infrastructure

+

宿主机设置

+

管理计算节点连接、存储目录和公网网络配置。

+
+
+

正在加载…

+
+
+ + +
+
+
+ +
+
用户 ISO 功能
+

关闭后普通用户看不到 ISO 导航,相关读取、导入、任务及删除接口也会拒绝访问。

+
+
+
+ + +
+
+
+ + +
+ + +
+
+
+
+

Configuration

+
添加宿主机
+

私钥和口令加密存储且不会回显,后台采样不依赖网页登录。

+
+ +
+ + +
+
+ +
基本信息

用于后台识别宿主机及其销售地区。

+
+
+
+
+
+
+
+ +
+
+ +
SSH 连接与凭据

先核对指纹,再通过 HTTPS 提交凭据。

+
+
+
+
+
+ +

+                            
+                        
+
仅通过 HTTPS 提交;请勿将密钥粘贴到工单或日志。
+
加密保存,面板重启后可自动连接。
+
+
+ +
+
+ +
存储目录

配置系统盘、用户 ISO 与救援 ISO 的独立存储位置。

+
+
+
+
个人镜像会同步到此目录,必须使用目录类型存储池。
+
+
+
+ +
+
+ +
网络配置

定义默认网桥、公网地址池、网关与 DNS。

+
+
+
+
只分配地址池内未使用的地址,后台会自动规范 CIDR。
+
可与地址池前缀不同,请按服务商路由要求设置。
+
+
+
网关、网络地址和广播地址自动排除;请额外排除外部虚拟机已占用的 IP。
+
+
+ + +
+
- -
-
添加宿主机
-
-
-
-
-
-
-
仅通过 HTTPS 提交;请勿将密钥粘贴到工单或日志。
-
加密保存,面板重启后可自动连接,后台采样不依赖网页登录。
-
-
开放用户 ISO 功能后,个人镜像会同步到此目录;必须使用目录类型存储池。
-
-
-
只分配该地址池内未使用的地址;可输入 .113/28,后台会规范为 .112/28。
-
可与地址池 /28 不同,按服务商路由要求设置。
-
-
-
网关、网络地址和广播地址自动排除。请额外排除已有外部虚拟机占用的 IP。
-
-
{include file='admin/static_footer.tpl'} diff --git a/web/resources/views/venix/admin/telegram/index.tpl b/web/resources/views/venix/admin/telegram/index.tpl index 2a575677..111785ae 100644 --- a/web/resources/views/venix/admin/telegram/index.tpl +++ b/web/resources/views/venix/admin/telegram/index.tpl @@ -2,69 +2,179 @@ {assign var=admin_active value='telegram'} {include file='admin/static_header.tpl'} -

Telegram 工单提醒

仅用于管理员接收工单通知。用户通过网站查看和回复工单,不使用 Telegram 登录、绑定或群组功能。

+
+
+

Telegram 工单提醒

+

配置工单机器人、独立通信域名和管理员私聊接收账号。用户仍只通过网站查看与回复工单。

+
+
+ + {if $telegram_enabled && $telegram_configured}通知服务已就绪{elseif $telegram_enabled}配置尚未完成{else}通知服务未启用{/if} + +
+
+ +{if $telegram_config.configuration_error|default:'' != ''} + +{/if} + +
+
+ +

通知开关

{if $telegram_enabled}已启用{else}未启用{/if}
+
+
+ +

Bot Token

{if $telegram_config.bot_token_configured}已加密保存{else}尚未配置{/if}
+
+
+ +

Webhook 密钥

{if $telegram_config.webhook_secret_configured}已安全生成{else}尚未生成{/if}
+
+
+ +

接收管理员

{if $telegram_bound}管理员 #{$telegram_admin_id|escape:'html'}{else}尚未绑定{/if}
+
+
+
-
-
服务状态
-
通知开关
{if $telegram_enabled}已开启{else}未开启{/if}
机器人配置
{if $telegram_configured}已配置{else}未配置{/if}
管理员绑定
{if $telegram_bound}已绑定管理员 #{$telegram_admin_id|escape:"html"}{else}未绑定{/if}
-

机器人 Token 和请求密钥由服务器配置提供,不会在网页展示或保存。请先配置机器人,再注册 Webhook。

- -
-
-
管理员私聊绑定
-

生成一次性绑定命令后,使用管理员自己的 Telegram 账号,在与机器人单独的私聊中发送该命令。群聊绑定无效。

-
- -

-
+
+
+
+

Bot Configuration

机器人与通信地址

配置保存到数据库;敏感项加密存储且永不回显。

+ +
+
+
+ + +
关闭后不会接收 Webhook,也不会发送工单通知;已保存配置和管理员绑定会保留。
+
+
+ + +
只填写 HTTPS 根地址,不含路径、查询参数或结尾斜杠。该域名需通过 DNS、TLS 与 Web 服务器指向本应用。
+
+
+ + +
Token 只在本次保存请求中发送。更换 Token 会自动解除旧管理员绑定,避免向错误机器人继续投递。
+
+
+ + +
首次保存会自动生成高强度密钥。主动轮换后旧 Webhook 请求立即失效,需要重新注册 Webhook。
+
+
+ + 保存成功后再执行右侧的 Webhook 注册。 +
+
+
+
+ +
+
+
+

Webhook

注册 Telegram 回调

把当前独立通信地址注册到 Telegram。

+ +
+ +
{$telegram_config.webhook_url|default:'尚未配置通信域名'|escape:'html'}
+ +
+ +
+
+

Private Binding

管理员私聊绑定

只接受管理员本人的 Telegram 私聊,群组和转发消息无效。

+ +
+
+ + +
+ +
+
+
等待操作
+ {literal} diff --git a/web/resources/views/venix/admin/update.tpl b/web/resources/views/venix/admin/update.tpl index f2230377..392b1934 100644 --- a/web/resources/views/venix/admin/update.tpl +++ b/web/resources/views/venix/admin/update.tpl @@ -1,61 +1,92 @@ {assign var=admin_title value='在线更新'} {assign var=admin_active value='update'} {include file='admin/static_header.tpl'} +
-
-

在线更新

-

只会快进更新系统固定的私有仓库与分支;不安装 Composer/Python 依赖、不准备依赖暂存区,也不改写 systemd unit。目标版本修改 engine/requirements.txt、web/composer.json、web/composer.lock 或 deploy/** 时会在停服和切换前拒绝,请按部署文档通过 SSH 升级。

+
+
+

System

+

在线更新

+

安全检查固定私有仓库与分支,并执行受约束的快进更新。

+
+
+

正在读取更新配置…

+
-

正在读取更新配置…

-
-
+
+ + 在线更新不会安装 Composer/Python 依赖,也不会改写 systemd unit。若目标版本修改依赖清单或 deploy/**,系统会在停服前拒绝,请改用 SSH 升级。 +
+ +
+
-
更新源与凭据
+
+
+

Repository

+
更新源与凭据
+

仓库与分支由服务器固定,网页只维护访问令牌。

+
+ +
固定仓库
正在读取…
固定分支
正在读取…
当前提交
正在读取…
检出状态
正在读取…
- - - 令牌只在保存请求中发送,不会回显或保存在浏览器中。 -
- - +
+ + +
令牌只在保存请求中发送,不会回显或保存在浏览器中。
+
- +
-
+
-
检查并执行
-

每次执行都必须先重新检查。检查得到的本地与远端提交会作为不可变条件提交,版本变化时引擎会拒绝更新。

- -
+
+
+

Deploy

+
检查并执行
+

每次执行前都必须重新检查并锁定本地与远端提交。

+
+ +
+
检查状态
尚未检查
已锁定本地提交
—
已锁定远端提交
—
- +
+ + +
-
+
-
更新任务
-

更新期间 PHP 和私有引擎会重启,短暂连接失败会自动重试。请保留本页面,勿重复提交执行请求。若任务进入 blocked,代码或数据库状态尚未确认,页面会保持维护锁并禁用变更操作;请通过 SSH 核查。如果中断发生在数据库迁移期间,仅回退源码不会解除维护锁,必须人工完成并验证迁移与服务兼容性。

-
+
+
+

Progress

+
更新任务
+

PHP 与私有引擎重启期间会自动只读恢复任务,请保留本页面且不要重复提交。

+
+ +
+
任务编号
—
任务状态
—
当前阶段
—
结果
—
+

若任务进入 blocked,维护锁会保持启用。数据库迁移中断时仅回退源码不会解除锁,必须通过 SSH 完成并验证恢复。

diff --git a/web/resources/views/venix/layout_assets.tpl b/web/resources/views/venix/layout_assets.tpl index 513dc452..e711cba4 100644 --- a/web/resources/views/venix/layout_assets.tpl +++ b/web/resources/views/venix/layout_assets.tpl @@ -1 +1 @@ -{assign var=venix_asset_version value='2026092902' scope='global'} +{assign var=venix_asset_version value='2026092903' scope='global'} diff --git a/web/tests/PrunedProjectContractTest.php b/web/tests/PrunedProjectContractTest.php index e62e76cd..e7fd3955 100644 --- a/web/tests/PrunedProjectContractTest.php +++ b/web/tests/PrunedProjectContractTest.php @@ -16,7 +16,7 @@ foreach (['/community', '/paid-registration', '/trafficlog', '/tcplog', '/tcpmon $assert(!is_dir($root . '/resources/views/material') && !is_dir($root . '/resources/views/codex'), 'Retired templates remain'); $assert(is_file($root . '/resources/views/venix/admin/hosts/index.tpl'), 'Host administration template missing'); $config = file_get_contents($root . '/config/.config.php.example'); -foreach (['user_try', 'reg_method', 'user_class_default', 'enable_class_expire_reset', 'auto_clean_', 'auto_backup_webroot', 'mu_suffix', 'mu_regex', 'checkinMin', 'enable_documents', 'subUrl', 'tgUrl', 'chatgpt_api'] as $key) { +foreach (['user_try', 'reg_method', 'user_class_default', 'enable_class_expire_reset', 'auto_clean_', 'auto_backup_webroot', 'mu_suffix', 'mu_regex', 'checkinMin', 'enable_documents', 'subUrl', 'tgUrl', 'enable_telegram', 'telegram_token', 'telegram_request_token', 'chatgpt_api'] as $key) { $assert(!str_contains($config, $key), 'Retired configuration remains: ' . $key); } foreach (['db_password', 'smtp_passsword', 'super_admin', 'auto_backup_passwd', 'enable_login_bind_ip', 'notify_limit_mode'] as $key) { diff --git a/web/tests/TicketTelegramBoundaryTest.php b/web/tests/TicketTelegramBoundaryTest.php index a7575b61..e163224b 100644 --- a/web/tests/TicketTelegramBoundaryTest.php +++ b/web/tests/TicketTelegramBoundaryTest.php @@ -1,6 +1,5 @@ 'true', 'telegram_token' => 'test-not-a-real-token', 'telegram_request_token' => '']; -check(!Notifications::authorizeWebhook(''), 'Empty webhook secret must fail closed'); -$System_Config['telegram_request_token'] = str_repeat('a', 32); -check(!Notifications::authorizeWebhook(str_repeat('b', 32)), 'Wrong secret accepted'); -check(Notifications::authorizeWebhook(str_repeat('a', 32)), 'Valid configured secret rejected'); -$System_Config['enable_telegram'] = 'false'; -check(!Notifications::authorizeWebhook(str_repeat('a', 32)), 'Disabled integration accepted'); - $message = ['chat' => ['type' => 'private', 'id' => 123], 'from' => ['id' => 123], 'text' => '/start ' . str_repeat('a', 48)]; check(Notifications::bindingCommand(['message' => $message]) !== null, 'Private one-time code command rejected'); foreach ([['text' => '/reply 1 hello'], ['chat' => ['type' => 'group', 'id' => 123]], ['from' => ['id' => 124]], ['forward_origin' => ['type' => 'user']], ['from' => ['id' => 123, 'is_bot' => true]], ['text' => '/start bad']] as $change) { check(Notifications::bindingCommand(['message' => array_replace($message, $change)]) === null, 'Unexpected bot capability accepted'); } -echo "Administrator-only Telegram boundaries passed.\n"; +$config = file_get_contents(dirname(__DIR__) . '/config/.config.php.example'); +foreach (['enable_telegram', 'telegram_token', 'telegram_request_token', 'tgUrl'] as $legacy) { + check(!str_contains($config, $legacy), 'Legacy Telegram config.php setting remains: ' . $legacy); +} +$service = file_get_contents(dirname(__DIR__) . '/app/Services/TicketTelegramConfig.php'); +check(str_contains($service, 'ticket_telegram_webhook_base_url'), 'Database Telegram communication origin is missing'); +echo "Administrator-only Telegram command and database configuration boundaries passed.\n"; diff --git a/web/tests/TicketTelegramNotifierSecurityTest.php b/web/tests/TicketTelegramNotifierSecurityTest.php index a7a388f9..0672d182 100644 --- a/web/tests/TicketTelegramNotifierSecurityTest.php +++ b/web/tests/TicketTelegramNotifierSecurityTest.php @@ -15,11 +15,20 @@ namespace App\Models { public static int $transactions = 0; public static int $locks = 0; public static int $writes = 0; + public static int $queries = 0; + public static bool $failQueries = false; public function __construct(public string $name = '', public string $value = '{}') {} - public static function where($key, $value) { return new \TelegramTestQuery($value); } - public static function firstOrCreate($match, $values) + public static function where($key, $value) { - return self::$rows[$match['name']] ??= new self($match['name'], $values['value']); + if (self::$failQueries) { throw new \RuntimeException('SQLSTATE synthetic-internal-detail'); } + self::$queries++; + return new \TelegramTestQuery($value); + } + public static function whereIn($key, $values) + { + if (self::$failQueries) { throw new \RuntimeException('SQLSTATE synthetic-internal-detail'); } + self::$queries++; + return new \TelegramTestWhereInQuery($values); } public function getConnection() { return new \TelegramTestConnection(); } public function save() @@ -37,6 +46,31 @@ namespace App\Services { public static $user; public static function getUser() { return self::$user; } } + + final class RedisClient + { + public static array $store = []; + public static array $ttls = []; + public static bool $fail = false; + public static int $gets = 0; + public static int $sets = 0; + public static int $deletes = 0; + public function __construct() + { + if (self::$fail) { throw new \RuntimeException('Redis unavailable'); } + } + public function getClient() { return new \TelegramTestRedisBackend(); } + public function setex($key, $ttl, $value) { return $this->getClient()->setex($key, $ttl, $value); } + public function del($key) { return $this->getClient()->del($key); } + } +} + +namespace App\Services\Cloud { + final class CloudSecrets + { + public static int $calls = 0; + public static function key(string $purpose): string { self::$calls++; return str_repeat("\x42", 32); } + } } namespace App\Controllers { @@ -65,6 +99,10 @@ namespace { use App\Models\Configurations; use App\Models\User; use App\Services\Auth; + use App\Services\Cloud\CloudSecrets; + use App\Services\RedisClient; + use App\Services\TicketTelegramConfig; + use App\Services\TicketTelegramCredentialCipher; use App\Services\TicketTelegramNotifier; use App\Controllers\Admin\TelegramController; use App\Controllers\TelegramWebhookController; @@ -79,6 +117,30 @@ namespace { finally { Configurations::$transactions--; } } } + final class TelegramTestRedisBackend + { + public function get($key) + { + if (RedisClient::$fail) { throw new RuntimeException('Redis unavailable'); } + RedisClient::$gets++; + return RedisClient::$store[$key] ?? null; + } + public function setex($key, $ttl, $value) + { + if (RedisClient::$fail) { throw new RuntimeException('Redis unavailable'); } + RedisClient::$sets++; + RedisClient::$ttls[$key] = (int) $ttl; + RedisClient::$store[$key] = (string) $value; + return true; + } + public function del($key) + { + if (RedisClient::$fail) { throw new RuntimeException('Redis unavailable'); } + RedisClient::$deletes++; + unset(RedisClient::$store[$key], RedisClient::$ttls[$key]); + return 1; + } + } final class TelegramTestQuery { public function __construct(private string $name) {} @@ -94,6 +156,17 @@ namespace { public function firstOrFail() { return $this->first() ?? throw new RuntimeException('Missing fixture.'); } public function delete() { unset(Configurations::$rows[$this->name]); } } + final class TelegramTestWhereInQuery + { + public function __construct(private array $names) {} + public function get($columns = ['*']) + { + return array_values(array_filter( + Configurations::$rows, + fn ($row) => in_array($row->name, $this->names, true) + )); + } + } final class TelegramTestResponse { public int $status = 200; @@ -117,13 +190,16 @@ namespace { } final class TelegramTestRequest { - public function __construct(private string $secret, public TelegramTestStream $stream) {} + public function __construct(private string $secret, public TelegramTestStream $stream, private array $payload = []) {} public function getHeaderLine($name) { return $this->secret; } public function getBody() { return $this->stream; } + public function getParsedBody() { return $this->payload; } } require dirname(__DIR__) . '/app/Services/Config.php'; require dirname(__DIR__) . '/app/Services/AdminPermission.php'; + require dirname(__DIR__) . '/app/Services/TicketTelegramCredentialCipher.php'; + require dirname(__DIR__) . '/app/Services/TicketTelegramConfig.php'; require dirname(__DIR__) . '/app/Services/TicketTelegramNotifier.php'; require dirname(__DIR__) . '/app/Controllers/Admin/TelegramController.php'; require dirname(__DIR__) . '/app/Controllers/TelegramWebhookController.php'; @@ -133,7 +209,7 @@ namespace { }; $expectRejected = function ($callback, $message) use ($assert) { $rejected = false; - try { $callback(); } catch (RuntimeException $exception) { $rejected = true; } + try { $callback(); } catch (Throwable $exception) { $rejected = true; } $assert($rejected, $message); }; $state = function () { @@ -142,11 +218,15 @@ namespace { $setState = function ($value) { Configurations::$rows['ticket_telegram_binding'] = new Configurations('ticket_telegram_binding', json_encode($value)); }; + $configCacheKey = 'ticket_telegram_config_snapshot:v1'; + $clearConfigCache = function () use ($configCacheKey) { + unset(RedisClient::$store[$configCacheKey], RedisClient::$ttls[$configCacheKey]); + }; $update = function ($code, $chatId = '123456') { return ['message' => ['chat' => ['id' => $chatId, 'type' => 'private'], 'from' => ['id' => $chatId, 'is_bot' => false], 'text' => '/start ' . $code]]; }; - $System_Config = ['enable_telegram' => true, 'telegram_token' => 'synthetic-bot-token', + $System_Config = ['enable_telegram' => true, 'telegram_token' => '123456789:' . str_repeat('A', 35), 'telegram_request_token' => 'synthetic-webhook-secret-123', 'super_admin' => '1,2', 'baseUrl' => 'https://example.invalid']; User::$users = [1 => new User(1, 1), 2 => new User(2, 0), 3 => new User(3, 1)]; @@ -154,6 +234,36 @@ namespace { $expectRejected(fn () => TicketTelegramNotifier::createBinding(2), 'Ordinary whitelisted user can issue binding codes.'); $expectRejected(fn () => TicketTelegramNotifier::createBinding(3), 'Non-super administrator can issue binding codes.'); $binding = TicketTelegramNotifier::createBinding(1); + $assert((string) Configurations::$rows[TicketTelegramConfig::MIGRATION_MARKER]->value === '1' + && !str_contains(Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value, $System_Config['telegram_token']) + && !str_contains(Configurations::$rows[TicketTelegramConfig::WEBHOOK_SECRET]->value, $System_Config['telegram_request_token']), + 'Legacy Telegram settings were not migrated once as encrypted database values.'); + TicketTelegramConfig::publicValues(); + $cachedSnapshot = json_decode(RedisClient::$store[$configCacheKey] ?? '', true); + $assert(is_array($cachedSnapshot) && (RedisClient::$ttls[$configCacheKey] ?? 0) === 60 + && str_starts_with($cachedSnapshot[TicketTelegramConfig::BOT_TOKEN] ?? '', 'sbox:telegram:v1:') + && str_starts_with($cachedSnapshot[TicketTelegramConfig::WEBHOOK_SECRET] ?? '', 'sbox:telegram:v1:') + && !str_contains(RedisClient::$store[$configCacheKey] ?? '', $System_Config['telegram_token']) + && !str_contains(RedisClient::$store[$configCacheKey] ?? '', $System_Config['telegram_request_token']), + 'Redis snapshot did not contain only encrypted raw Telegram configuration with a 60-second TTL.'); + $queriesBeforeCacheHit = Configurations::$queries; + $redisGetsBeforeCacheHit = RedisClient::$gets; + TicketTelegramConfig::publicValues(); + $assert(Configurations::$queries === $queriesBeforeCacheHit + && RedisClient::$gets === $redisGetsBeforeCacheHit + 1, + 'Warm Telegram configuration cache queried the database or loaded the snapshot more than once.'); + $clearConfigCache(); + RedisClient::$fail = true; + $queriesBeforeFallback = Configurations::$queries; + $assert(TicketTelegramConfig::publicValues()['configured'] + && Configurations::$queries > $queriesBeforeFallback, + 'Redis failure did not fall back to the Telegram configuration database rows.'); + RedisClient::$fail = false; + TicketTelegramConfig::publicValues(); + $expectRejected(fn () => TicketTelegramCredentialCipher::decrypt( + Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value, + 'webhook_secret' + ), 'Purpose-separated Telegram ciphertext was accepted as another credential type.'); $assert(preg_match('/^[a-f0-9]{48}$/D', $binding['code']) === 1 && $binding['expires_in'] === 300, 'Binding code entropy/TTL changed.'); $assert($state()['pending_hash'] === hash('sha256', $binding['code']) @@ -214,49 +324,140 @@ namespace { $assert(count(BotApi::$calls) === $calls, 'Rejected notification still invoked Telegram.'); $controller = new TelegramController(); + Auth::$user = User::$users[1]; + $secretBeforeAtomicSave = TicketTelegramConfig::runtime(true)['webhook_secret']; + $saveRequest = new TelegramTestRequest('', new TelegramTestStream(''), [ + 'telegram_enabled' => 'true', + 'telegram_webhook_base_url' => 'https://tg.example.invalid/', + 'telegram_bot_token' => '', + 'telegram_rotate_webhook_secret' => 'true', + ]); + $deletesBeforeSave = RedisClient::$deletes; + $saved = $controller->save($saveRequest, new TelegramTestResponse(), []); + $assert($saved->status === 200 && ($saved->payload['ret'] ?? 0) === 1 + && ($saved->payload['config']['webhook_url'] ?? '') === 'https://tg.example.invalid/telegram_callback' + && !str_contains(json_encode($saved->payload), $System_Config['telegram_token']) + && !str_contains(json_encode($saved->payload), $System_Config['telegram_request_token']) + && RedisClient::$deletes > $deletesBeforeSave + && TicketTelegramConfig::runtime(true)['webhook_secret'] !== $secretBeforeAtomicSave, + 'Administrator config save failed or returned Telegram secrets.'); + $validTokenCipher = Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value; + Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value = 'corrupt-ciphertext'; + $invalidSavedToken = $controller->save(new TelegramTestRequest('', new TelegramTestStream(''), [ + 'telegram_enabled' => 'true', + 'telegram_webhook_base_url' => 'https://tg.example.invalid', + 'telegram_bot_token' => '', + ]), new TelegramTestResponse(), []); + $assert($invalidSavedToken->status === 422 && ($invalidSavedToken->payload['ret'] ?? 1) === 0, + 'Enabled configuration accepted an unreadable stored bot token.'); + Configurations::$rows[TicketTelegramConfig::BOT_TOKEN]->value = $validTokenCipher; + $setState(['bound_admin_id' => 1, 'chat_id' => '123456']); + $replacementToken = '987654321:' . str_repeat('B', 35); + $replaced = $controller->save(new TelegramTestRequest('', new TelegramTestStream(''), [ + 'telegram_enabled' => 'true', + 'telegram_webhook_base_url' => 'https://tg.example.invalid', + 'telegram_bot_token' => $replacementToken, + ]), new TelegramTestResponse(), []); + $assert($replaced->status === 200 && !isset(Configurations::$rows[TicketTelegramConfig::BINDING]) + && !str_contains(json_encode($replaced->payload), $replacementToken) + && !str_contains(RedisClient::$store[$configCacheKey] ?? '', $replacementToken), + 'Replacing the bot token retained the old binding or exposed the new token.'); foreach ([User::$users[2], new User(1, 0), new User(1, 1, 0)] as $account) { Auth::$user = $account; - foreach (['bind', 'unbind', 'webhook'] as $action) { + foreach (['save', 'rotateSecret', 'bind', 'unbind', 'webhook'] as $action) { $result = $controller->$action(null, new TelegramTestResponse(), []); $assert($result->status === 403, 'Direct action bypass allows an ordinary/downgraded/disabled account: ' . $action); } } + Auth::$user = User::$users[1]; + $webhook = new TelegramWebhookController(); + $webhookSecret = TicketTelegramConfig::runtime(true)['webhook_secret']; $unauthorized = new TelegramTestRequest('incorrect-secret', new TelegramTestStream('{}')); $assert($webhook->handle($unauthorized, new TelegramTestResponse(), [])->status === 403 && $unauthorized->stream->bytesRequested === 0, 'Webhook secret rejection occurs after processing the body.'); foreach ([true, false] as $knownSize) { - $oversized = new TelegramTestRequest($System_Config['telegram_request_token'], new TelegramTestStream(str_repeat('x', 65537), $knownSize)); + $oversized = new TelegramTestRequest($webhookSecret, new TelegramTestStream(str_repeat('x', 65537), $knownSize)); $assert($webhook->handle($oversized, new TelegramTestResponse(), [])->status === 413, 'Oversized webhook body was accepted.'); $assert($oversized->stream->bytesRequested <= 65537, 'Unknown-length webhook body was read without a limit.'); } - $badJson = new TelegramTestRequest($System_Config['telegram_request_token'], new TelegramTestStream('{broken')); + $badJson = new TelegramTestRequest($webhookSecret, new TelegramTestStream('{broken')); $assert($webhook->handle($badJson, new TelegramTestResponse(), [])->status === 400, 'Malformed webhook JSON accepted.'); - $System_Config['enable_telegram'] = false; - $disabled = new TelegramTestRequest($System_Config['telegram_request_token'], new TelegramTestStream('{}')); + Configurations::$rows[TicketTelegramConfig::ENABLED]->value = 'false'; + $clearConfigCache(); + $disabled = new TelegramTestRequest($webhookSecret, new TelegramTestStream('{}')); $assert($webhook->handle($disabled, new TelegramTestResponse(), [])->status === 403, 'Disabled bot still accepts webhooks.'); - $System_Config['enable_telegram'] = true; + Configurations::$rows[TicketTelegramConfig::ENABLED]->value = 'true'; + $clearConfigCache(); $assert(TicketTelegramNotifier::registerWebhook(), 'Configured HTTPS webhook registration failed.'); $registration = BotApi::$calls[count(BotApi::$calls) - 1]; $assert($registration[0] === 'setWebhook' && $registration[2] === 10 - && $registration[1]['secret_token'] === $System_Config['telegram_request_token'] + && $registration[1]['url'] === 'https://tg.example.invalid/telegram_callback' + && $registration[1]['secret_token'] === $webhookSecret && $registration[1]['allowed_updates'] === '["message"]', 'Webhook registration lost its secret, timeout or message-only update boundary.'); - $System_Config['baseUrl'] = 'http://example.invalid'; - $expectRejected(fn () => TicketTelegramNotifier::registerWebhook(), 'Non-HTTPS webhook URL accepted.'); - $System_Config['baseUrl'] = 'https://example.invalid'; + $expectRejected(fn () => TicketTelegramConfig::save([ + 'enabled' => true, + 'webhook_base_url' => 'http://example.invalid', + ]), 'Non-HTTPS webhook URL accepted.'); + TicketTelegramConfig::publicValues(); + $preRotationSnapshot = RedisClient::$store[$configCacheKey] ?? ''; + $oldSecret = $webhookSecret; + $deletesBeforeRotate = RedisClient::$deletes; + $rotated = $controller->rotateSecret(null, new TelegramTestResponse(), []); + $webhookSecret = TicketTelegramConfig::runtime(true)['webhook_secret']; + // Simulate a cache-aside race repopulating the pre-rotation encrypted snapshot. + RedisClient::$store[$configCacheKey] = $preRotationSnapshot; + RedisClient::$ttls[$configCacheKey] = 60; + $queriesBeforeAuthoritativeChecks = Configurations::$queries; + $assert($rotated->status === 200 && $oldSecret !== $webhookSecret + && RedisClient::$deletes > $deletesBeforeRotate + && !TicketTelegramNotifier::authorizeWebhook($oldSecret) + && TicketTelegramNotifier::authorizeWebhook($webhookSecret) + && Configurations::$queries >= $queriesBeforeAuthoritativeChecks + 2, + 'Webhook secret rotation or authoritative runtime reads accepted a stale cached secret.'); BotApi::$fail = true; $failure = ''; try { TicketTelegramNotifier::registerWebhook(); } catch (RuntimeException $exception) { $failure = $exception->getMessage(); } - $assert($failure !== '' && !str_contains($failure, $System_Config['telegram_token']), + $assert($failure !== '' && !str_contains($failure, TicketTelegramConfig::runtime(true)['bot_token']), 'SDK failure leaked the Telegram bot token.'); BotApi::$fail = false; + $clearConfigCache(); + Configurations::$failQueries = true; + $failure = ''; + try { TicketTelegramNotifier::registerWebhook(); } + catch (RuntimeException $exception) { $failure = $exception->getMessage(); } + Configurations::$failQueries = false; + $assert($failure === 'Telegram 配置读取失败,请检查数据库与服务器日志' + && !str_contains($failure, 'SQLSTATE'), 'Database error details leaked through webhook registration.'); + + // Bad legacy values must be consumed once without trapping the administrator in a migration loop. + Configurations::$rows = []; + $clearConfigCache(); + $System_Config['enable_telegram'] = 'true'; + $System_Config['telegram_token'] = 'invalid legacy token'; + $System_Config['telegram_request_token'] = 'short'; + $System_Config['tgUrl'] = 'http://insecure.example.invalid/path'; + $legacy = TicketTelegramConfig::publicValues(); + $assert((string) Configurations::$rows[TicketTelegramConfig::MIGRATION_MARKER]->value === '1' + && !$legacy['bot_token_configured'] && $legacy['webhook_base_url'] === '' && !$legacy['configured'], + 'Invalid legacy Telegram values blocked or polluted the one-time migration.'); + + // A clean installation must not need the payload key until an administrator saves credentials. + Configurations::$rows = []; + $clearConfigCache(); + CloudSecrets::$calls = 0; + unset($System_Config['enable_telegram'], $System_Config['telegram_token'], + $System_Config['telegram_request_token'], $System_Config['tgUrl']); + $fresh = TicketTelegramConfig::publicValues(); + $assert(!$fresh['enabled'] && !$fresh['bot_token_configured'] && !$fresh['webhook_secret_configured'] + && CloudSecrets::$calls === 0, 'Fresh Telegram configuration unexpectedly required credential decryption.'); $routes = file_get_contents(dirname(__DIR__) . '/config/routes.php'); - foreach (['bind', 'unbind', 'webhook'] as $action) { + foreach (['config', 'secret/rotate', 'bind', 'unbind', 'webhook'] as $action) { $matches = array_filter(explode("\n", $routes), fn ($line) => str_contains($line, "'/telegram/" . $action . "'")); $assert(count($matches) === 1 && str_contains(reset($matches), 'new SuperAdmin()'), 'Administrator mutation route lost SuperAdmin/CSRF middleware: ' . $action);