feat: refresh admin UI and manage Telegram settings

dev
admin 2 months ago
parent 4c3e98cad7
commit 1e2f8aba60

@ -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。当前通知仅绑定一个管理员接收方,后台可重新绑定或解绑。
## 验证及限制

@ -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 配置操作失败,请检查数据库与服务器日志';
}
}

@ -0,0 +1,460 @@
<?php
namespace App\Services;
use App\Models\Configurations;
/** Database-backed configuration for the administrator ticket Telegram bot. */
final class TicketTelegramConfig
{
public const ENABLED = 'ticket_telegram_enabled';
public const WEBHOOK_BASE_URL = 'ticket_telegram_webhook_base_url';
public const BOT_TOKEN = 'ticket_telegram_bot_token_cipher';
public const WEBHOOK_SECRET = 'ticket_telegram_webhook_secret_cipher';
public const MIGRATION_MARKER = 'ticket_telegram_db_v1';
public const BINDING = 'ticket_telegram_binding';
private const CACHE_KEY = 'ticket_telegram_config_snapshot:v1';
private const CACHE_TTL = 60;
private const KEYS = [
self::ENABLED,
self::WEBHOOK_BASE_URL,
self::BOT_TOKEN,
self::WEBHOOK_SECRET,
];
private const SNAPSHOT_KEYS = [
self::MIGRATION_MARKER,
self::ENABLED,
self::WEBHOOK_BASE_URL,
self::BOT_TOKEN,
self::WEBHOOK_SECRET,
];
public static function publicValues(): array
{
$rows = self::configurationRows();
$enabled = self::truthy($rows[self::ENABLED] ?? 'false');
$baseUrl = trim((string) ($rows[self::WEBHOOK_BASE_URL] ?? ''));
$tokenConfigured = trim((string) ($rows[self::BOT_TOKEN] ?? '')) !== '';
$secretConfigured = trim((string) ($rows[self::WEBHOOK_SECRET] ?? '')) !== '';
$configured = false;
$configurationError = '';
if ($tokenConfigured && $secretConfigured && $baseUrl !== '') {
try {
self::runtimeFromRows($rows, false);
$configured = true;
} catch (\Throwable $exception) {
$configurationError = self::safeConfigurationError($exception);
}
}
return [
'enabled' => $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 配置无效,请在管理员页面重新保存';
}
}

@ -0,0 +1,80 @@
<?php
namespace App\Services;
use App\Services\Cloud\CloudSecrets;
/** Encrypts Telegram credentials with a purpose-separated cloud payload key. */
final class TicketTelegramCredentialCipher
{
private const PREFIX = 'sbox:telegram:v1:';
private const PURPOSES = ['bot_token', 'webhook_secret'];
public static function encrypt(string $plainText, string $purpose): string
{
self::assertPurpose($purpose);
if ($plainText === '') {
return '';
}
if (!function_exists('sodium_crypto_secretbox')) {
throw new \RuntimeException('PHP sodium 扩展未安装,无法加密 Telegram 凭据');
}
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipherText = sodium_crypto_secretbox($plainText, $nonce, self::key($purpose));
return self::PREFIX . base64_encode($nonce . $cipherText);
}
public static function decrypt(string $encoded, string $purpose): string
{
self::assertPurpose($purpose);
$encoded = trim($encoded);
if ($encoded === '') {
return '';
}
if (!str_starts_with($encoded, self::PREFIX)) {
throw new \RuntimeException('Telegram 凭据不是受支持的加密格式,请在后台重新保存');
}
if (!function_exists('sodium_crypto_secretbox_open')) {
throw new \RuntimeException('PHP sodium 扩展未安装,无法解密 Telegram 凭据');
}
$payload = base64_decode(substr($encoded, strlen(self::PREFIX)), true);
if ($payload === false || strlen($payload) <= SODIUM_CRYPTO_SECRETBOX_NONCEBYTES) {
throw new \RuntimeException('Telegram 凭据密文格式无效,请在后台重新保存');
}
$plainText = sodium_crypto_secretbox_open(
substr($payload, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES),
substr($payload, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES),
self::key($purpose)
);
if ($plainText === false) {
throw new \RuntimeException('Telegram 凭据解密失败,请检查 cloud_payload_key');
}
return $plainText;
}
public static function isCiphertext(string $value): bool
{
return $value === '' || str_starts_with($value, self::PREFIX);
}
private static function key(string $purpose): string
{
try {
$master = CloudSecrets::key('payload_key');
} catch (\Throwable $exception) {
throw new \RuntimeException(
'Telegram 凭据加密密钥不可用,请先配置有效的 cloud_payload_key 或 cloud_payload_key_file'
);
}
return hash_hkdf('sha256', $master, SODIUM_CRYPTO_SECRETBOX_KEYBYTES, 'virt-cloud:telegram:' . $purpose);
}
private static function assertPurpose(string $purpose): void
{
if (!in_array($purpose, self::PURPOSES, true)) {
throw new \InvalidArgumentException('不支持的 Telegram 凭据类型');
}
}
}

@ -9,24 +9,35 @@ use TelegramBot\Api\BotApi;
/** Administrator-only ticket alerts. No Telegram user login or ticket reply commands. */
final class TicketTelegramNotifier
{
private const KEY = 'ticket_telegram_binding';
private const KEY = TicketTelegramConfig::BINDING;
public const BINDING_TTL = 300;
public static function enabled(): bool
{
return in_array(Config::get('enable_telegram'), [true, 1, '1', 'true'], true);
try {
return (bool) TicketTelegramConfig::publicValues()['enabled'];
} catch (\Throwable $exception) {
return false;
}
}
public static function configured(): bool
{
return trim((string) Config::get('telegram_token', '')) !== ''
&& preg_match('/^[A-Za-z0-9_-]{16,256}$/D', (string) Config::get('telegram_request_token', '')) === 1;
try {
return (bool) TicketTelegramConfig::publicValues()['configured'];
} catch (\Throwable $exception) {
return false;
}
}
public static function authorizeWebhook(string $header): bool
{
$secret = (string) Config::get('telegram_request_token', '');
return self::enabled() && self::configured() && hash_equals($secret, $header);
try {
$config = TicketTelegramConfig::runtime(true);
return hash_equals($config['webhook_secret'], $header);
} catch (\Throwable $exception) {
return false;
}
}
public static function bindingStatus(): array
@ -38,14 +49,12 @@ final class TicketTelegramNotifier
public static function createBinding(int $adminId): array
{
if (!self::enabled() || !self::configured()) {
throw new \RuntimeException('请先启用 Telegram,并配置 bot token 和有效的 webhook secret');
}
TicketTelegramConfig::runtime(true);
if (!self::eligibleAdmin($adminId)) {
throw new \RuntimeException('只有超级管理员可以绑定工单通知');
}
$code = bin2hex(random_bytes(24));
Configurations::firstOrCreate(['name' => 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', '')));

@ -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'] = '';

@ -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());

@ -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;
}
}

@ -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} 条记录。`);

@ -1,2 +1,41 @@
{assign var=admin_title value='虚拟机实例'}{assign var=admin_active value='cloud_instances'}{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css"><section class="cloud-admin" data-cloud-admin="instances"><h4>虚拟机实例</h4><p class="text-muted">跨宿主机查看已关联的实例和所属用户。客户的资源与操作权限由后台校验。</p><p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p><button id="admin-records-refresh" class="btn btn-outline-primary mb-3" type="button">刷新</button><div class="card"><div class="card-body table-responsive"><table class="table"><thead><tr><th>实例</th><th>用户</th><th>宿主机</th><th>状态</th><th>公网 IP</th><th>配置</th></tr></thead><tbody id="admin-records"></tbody></table></div></div></section><script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>{include file='admin/static_footer.tpl'}
{assign var=admin_title value='虚拟机实例'}
{assign var=admin_active value='cloud-instances'}
{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
<section class="cloud-admin" data-cloud-admin="instances">
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
<div class="flex-grow-1">
<p class="admin-eyebrow mb-1">Compute</p>
<h4 class="fs-20 fw-semibold mb-1">虚拟机实例</h4>
<p class="text-muted mb-0">跨宿主机查看已关联的实例、所属用户与资源配置。</p>
</div>
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions">
<p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在加载…</p>
<button id="admin-records-refresh" class="btn btn-light" type="button">
<i class="mdi mdi-refresh me-1"></i>刷新
</button>
</div>
</div>
<div class="card cloud-admin-table-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Instances</p>
<h5 class="mb-1">实例目录</h5>
<p class="text-muted mb-0">客户资源与操作权限仍由后台校验,此页面仅用于集中查看。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-server-network"></i></span>
</div>
<div class="table-responsive cloud-admin-table-wrap">
<table class="table table-hover align-middle mb-0 cloud-admin-table">
<thead><tr><th>实例</th><th>用户</th><th>宿主机</th><th>状态</th><th>公网 IP</th><th>配置</th></tr></thead>
<tbody id="admin-records"><tr class="cloud-admin-placeholder"><td colspan="6">实例数据加载中</td></tr></tbody>
</table>
</div>
</div>
</div>
</section>
<script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -1,2 +1,46 @@
{assign var=admin_title value='开通任务'}{assign var=admin_active value='cloud-orders'}{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css"><section class="cloud-admin" data-cloud-admin="orders"><h4>实例开通任务</h4><p class="text-muted">用户提交部署后先生成开通账单,只有账单支付成功才会在此进入创建队列。失败或不确定的任务需核查实际宿主机状态,不要重复创建或扣款。</p><p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p><button id="admin-records-refresh" class="btn btn-outline-primary mb-3" type="button">刷新</button><div class="card"><div class="card-body table-responsive"><table class="table"><thead><tr><th>任务</th><th>用户</th><th>套餐</th><th>金额</th><th>状态</th><th>实例 / 引擎任务</th><th>时间 / 错误</th></tr></thead><tbody id="admin-records"></tbody></table></div></div></section><script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>{include file='admin/static_footer.tpl'}
{assign var=admin_title value='开通任务'}
{assign var=admin_active value='cloud-orders'}
{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
<section class="cloud-admin" data-cloud-admin="orders">
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
<div class="flex-grow-1">
<p class="admin-eyebrow mb-1">Provisioning</p>
<h4 class="fs-20 fw-semibold mb-1">实例开通任务</h4>
<p class="text-muted mb-0">跟踪账单支付后的创建队列、引擎任务与异常结果。</p>
</div>
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions">
<p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在加载…</p>
<button id="admin-records-refresh" class="btn btn-light" type="button">
<i class="mdi mdi-refresh me-1"></i>刷新
</button>
</div>
</div>
<div class="alert alert-warning cloud-admin-guidance" role="note">
<i class="mdi mdi-shield-alert-outline"></i>
<span>失败或不确定的任务需先核查实际宿主机状态,避免重复创建实例或重复扣款。</span>
</div>
<div class="card cloud-admin-table-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Tasks</p>
<h5 class="mb-1">任务记录</h5>
<p class="text-muted mb-0">只有账单支付成功后,部署请求才会进入创建队列。</p>
</div>
<span class="cloud-admin-card-icon is-warning"><i class="mdi mdi-progress-wrench"></i></span>
</div>
<div class="table-responsive cloud-admin-table-wrap">
<table class="table table-hover align-middle mb-0 cloud-admin-table">
<thead><tr><th>任务</th><th>用户</th><th>套餐</th><th>金额</th><th>状态</th><th>实例 / 引擎任务</th><th>时间 / 错误</th></tr></thead>
<tbody id="admin-records"><tr class="cloud-admin-placeholder"><td colspan="7">任务数据加载中</td></tr></tbody>
</table>
</div>
</div>
</div>
</section>
<script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -1,4 +1,70 @@
{assign var=admin_title value='救援模版'}{assign var=admin_active value='cloud_rescue'}{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css">
<section class="cloud-admin" data-cloud-admin="rescue"><h4>救援模版</h4><p class="text-muted">只支持可启动 ISO,上传至所选宿主机的独立救援目录;不会混入普通安装 ISO 列表。救援系统自身决定登录方式。</p><p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p><label for="catalog-host" class="form-label">宿主机</label><select id="catalog-host" class="form-select mb-3"></select><div class="cloud-admin-grid"><form id="rescue-upload" class="card"><div class="card-body"><h5>上传救援 ISO</h5><label for="rescue-name" class="form-label">模版名称</label><input id="rescue-name" class="form-control mb-3" maxlength="64" required><label for="rescue-file" class="form-label">救援 ISO(最大 8 GiB)</label><input id="rescue-file" class="form-control mb-3" type="file" accept=".iso,application/x-iso9660-image" required><p class="text-muted">上传大小还受 PHP、Web 服务器及反代限制;完成前请勿关闭页面。</p><button id="rescue-upload-button" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}>上传并导入</button></div></form><div class="card"><div class="card-body"><h5>救援 ISO 列表</h5><div id="catalog-list"></div></div></div></div></section><script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>
{assign var=admin_title value='救援模版'}
{assign var=admin_active value='cloud-rescue'}
{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
<section class="cloud-admin" data-cloud-admin="rescue">
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
<div class="flex-grow-1">
<p class="admin-eyebrow mb-1">Recovery</p>
<h4 class="fs-20 fw-semibold mb-1">救援模版</h4>
<p class="text-muted mb-0">按宿主机维护独立的可启动救援 ISO。</p>
</div>
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions">
<p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在加载…</p>
</div>
</div>
<div class="card cloud-admin-filter-card mb-3">
<div class="card-body">
<div class="cloud-admin-filter-row">
<div>
<p class="admin-eyebrow mb-1">Target host</p>
<h5 class="mb-1">选择宿主机</h5>
<p class="text-muted mb-0">救援 ISO 只上传到当前选择的宿主机,不会混入普通安装 ISO。</p>
</div>
<div class="cloud-admin-select-wrap">
<i class="mdi mdi-router-network"></i>
<label for="catalog-host" class="visually-hidden">宿主机</label>
<select id="catalog-host" class="form-select" aria-label="宿主机"></select>
</div>
</div>
</div>
</div>
<div class="cloud-admin-grid cloud-admin-rescue-layout">
<form id="rescue-upload" class="card cloud-admin-import-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Upload</p>
<h5 class="mb-1">上传救援 ISO</h5>
<p class="text-muted mb-0">救援系统自身决定登录方式。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-lifebuoy"></i></span>
</div>
<div class="cloud-admin-fields">
<div><label for="rescue-name" class="form-label">模版名称</label><input id="rescue-name" class="form-control" maxlength="64" required placeholder="例如 Debian Rescue"></div>
<div><label for="rescue-file" class="form-label">救援 ISO(最大 8 GiB)</label><input id="rescue-file" class="form-control" type="file" accept=".iso,application/x-iso9660-image" required><div class="form-text">只支持可启动 ISO,上传大小还受 PHP、Web 服务器及反代限制;完成前请勿关闭页面。</div></div>
</div>
<div class="cloud-admin-form-actions"><button id="rescue-upload-button" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-upload me-1"></i>上传并导入</button></div>
</div>
</form>
<div class="card cloud-admin-catalog-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Catalog</p>
<h5 class="mb-1">救援 ISO 列表</h5>
<p class="text-muted mb-0">这里仅显示当前宿主机已经保存的救援介质。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-folder-multiple-outline"></i></span>
</div>
<div id="catalog-list" class="cloud-admin-catalog-list"></div>
</div>
</div>
</div>
</section>
<script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -1,46 +1,86 @@
{assign var=admin_title value='云镜像模版'}{assign var=admin_active value='cloud_templates'}{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css">
{assign var=admin_title value='云镜像模版'}
{assign var=admin_active value='cloud-templates'}
{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
<section class="cloud-admin" data-cloud-admin="templates">
<h4>云镜像模版</h4>
<p class="text-muted">这里维护全局云镜像目录,普通用户在所有可售地区看到同一份镜像列表。宿主机副本由引擎按需准备。删除会同时退役全局源镜像并异步清理宿主机缓存;已创建实例使用独立克隆磁盘,不受影响。当前支持 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 云镜像。升级前按宿主机导入的旧镜像不会自动进入全局目录,请重新导入一次。</p>
<p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p>
<div class="cloud-admin-grid">
<div class="cloud-admin-imports">
<form id="template-import" class="card">
<div class="card-body">
<h5>从官方地址下载</h5>
<label for="template-name" class="form-label">模版名称</label>
<input id="template-name" class="form-control mb-3" maxlength="64" required placeholder="AlmaLinux 10.1">
<label for="template-url" class="form-label">官方 HTTPS 文件地址</label>
<input id="template-url" class="form-control mb-2" type="url" required placeholder="https://repo.almalinux.org/almalinux/8/cloud/x86_64/images/AlmaLinux-8-GenericCloud-latest.x86_64.qcow2">
<p class="text-muted">请粘贴受支持发行版官方镜像站的 HTTPS 文件地址,不能是下载介绍页;引擎只会跟随由官方入口返回且通过公网地址安全校验的跳转链。文件名应为 <code>.qcow2</code>;Ubuntu 官方 <code>.img</code> 也可使用,但其实际内容必须是 qcow2。</p>
<label for="template-sha256" class="form-label">SHA-256(可选)</label>
<input id="template-sha256" class="form-control mb-2" maxlength="64" spellcheck="false" autocomplete="off" placeholder="可留空;填写时必须为 64 位十六进制">
<p class="text-muted">留空时面板会计算并保存实际 SHA-256,不与外部校验值比对;填写后则会在导入前核对。</p>
<button id="template-import-button" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}>下载并导入</button>
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
<div class="flex-grow-1">
<p class="admin-eyebrow mb-1">Images</p>
<h4 class="fs-20 fw-semibold mb-1">云镜像模版</h4>
<p class="text-muted mb-0">维护所有可售地区共用的 cloud-init 系统镜像目录。</p>
</div>
</form>
<form id="template-upload" class="card">
<div class="card-body">
<h5>从本机上传 QCOW2</h5>
<label for="template-upload-name" class="form-label">模版名称</label>
<input id="template-upload-name" class="form-control mb-3" maxlength="64" required placeholder="Debian 12 修复版">
<label for="template-upload-system" class="form-label">系统及版本</label>
<select id="template-upload-system" class="form-select mb-3" required>
<optgroup label="AlmaLinux"><option value="AlmaLinux|8">AlmaLinux 8</option><option value="AlmaLinux|9">AlmaLinux 9</option><option value="AlmaLinux|10">AlmaLinux 10</option></optgroup>
<optgroup label="Debian"><option value="Debian|11">Debian 11</option><option value="Debian|12" selected>Debian 12</option><option value="Debian|13">Debian 13</option></optgroup>
<optgroup label="Ubuntu"><option value="Ubuntu|20.04">Ubuntu 20.04</option><option value="Ubuntu|22.04">Ubuntu 22.04</option><option value="Ubuntu|24.04">Ubuntu 24.04</option><option value="Ubuntu|25.04">Ubuntu 25.04</option><option value="Ubuntu|25.10">Ubuntu 25.10</option><option value="Ubuntu|26.04">Ubuntu 26.04</option></optgroup>
<optgroup label="CentOS Stream"><option value="CentOS Stream|9">CentOS Stream 9</option><option value="CentOS Stream|10">CentOS Stream 10</option></optgroup>
</select>
<label for="template-upload-file" class="form-label">QCOW2 文件(最大 4 GiB)</label>
<input id="template-upload-file" class="form-control mb-2" type="file" accept=".qcow2,application/octet-stream" required>
<p class="text-muted">只接受独立、未加密且不含 backing file 的 QCOW2,面板会自动计算并保存 SHA-256。系统及版本用于用户部署页分类,请务必与镜像内容一致。上传期间请勿关闭页面;大小还受 PHP、Web 服务器及反代配置限制。</p>
<button id="template-upload-button" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}>上传并导入</button>
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions">
<p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在加载…</p>
</div>
</div>
<div class="alert alert-info cloud-admin-guidance" role="note">
<i class="mdi mdi-information-outline"></i>
<span>删除会退役全局源镜像并异步清理宿主机缓存;已经创建的实例使用独立克隆磁盘,不受影响。</span>
</div>
<div class="cloud-admin-grid cloud-admin-catalog-layout">
<div class="cloud-admin-imports">
<form id="template-import" class="card cloud-admin-import-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Remote</p>
<h5 class="mb-1">从官方地址下载</h5>
<p class="text-muted mb-0">由引擎安全下载并校验官方云镜像。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-cloud-download-outline"></i></span>
</div>
<div class="cloud-admin-fields">
<div><label for="template-name" class="form-label">模版名称</label><input id="template-name" class="form-control" maxlength="64" required placeholder="AlmaLinux 10.1"></div>
<div><label for="template-url" class="form-label">官方 HTTPS 文件地址</label><input id="template-url" class="form-control admin-mono" type="url" required placeholder="https://repo.almalinux.org/.../image.qcow2"><div class="form-text">请填写镜像文件直链而非介绍页。仅允许受支持发行版的官方入口及通过公网安全校验的跳转链。</div></div>
<div><label for="template-sha256" class="form-label">SHA-256(可选)</label><input id="template-sha256" class="form-control admin-mono" maxlength="64" spellcheck="false" autocomplete="off" placeholder="64 位十六进制校验值"><div class="form-text">留空时保存实际校验值;填写后会在导入前严格核对。</div></div>
</div>
<div class="cloud-admin-form-actions"><button id="template-import-button" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-download me-1"></i>下载并导入</button></div>
</div>
</form>
<form id="template-upload" class="card cloud-admin-import-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Upload</p>
<h5 class="mb-1">从本机上传 QCOW2</h5>
<p class="text-muted mb-0">上传本地制作并完成清理的独立镜像。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-cloud-upload-outline"></i></span>
</div>
<div class="cloud-admin-fields">
<div><label for="template-upload-name" class="form-label">模版名称</label><input id="template-upload-name" class="form-control" maxlength="64" required placeholder="Debian 12 修复版"></div>
<div><label for="template-upload-system" class="form-label">系统及版本</label><select id="template-upload-system" class="form-select" required>
<optgroup label="AlmaLinux"><option value="AlmaLinux|8">AlmaLinux 8</option><option value="AlmaLinux|9">AlmaLinux 9</option><option value="AlmaLinux|10">AlmaLinux 10</option></optgroup>
<optgroup label="Debian"><option value="Debian|11">Debian 11</option><option value="Debian|12" selected>Debian 12</option><option value="Debian|13">Debian 13</option></optgroup>
<optgroup label="Ubuntu"><option value="Ubuntu|20.04">Ubuntu 20.04</option><option value="Ubuntu|22.04">Ubuntu 22.04</option><option value="Ubuntu|24.04">Ubuntu 24.04</option><option value="Ubuntu|25.04">Ubuntu 25.04</option><option value="Ubuntu|25.10">Ubuntu 25.10</option><option value="Ubuntu|26.04">Ubuntu 26.04</option></optgroup>
<optgroup label="CentOS Stream"><option value="CentOS Stream|9">CentOS Stream 9</option><option value="CentOS Stream|10">CentOS Stream 10</option></optgroup>
</select></div>
<div><label for="template-upload-file" class="form-label">QCOW2 文件(最大 4 GiB)</label><input id="template-upload-file" class="form-control" type="file" accept=".qcow2,application/octet-stream" required><div class="form-text">只接受未加密且不含 backing file 的独立 QCOW2。系统版本必须与镜像内容一致,上传期间请勿关闭页面。</div></div>
</div>
<div class="cloud-admin-form-actions"><button id="template-upload-button" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-upload me-1"></i>上传并导入</button></div>
</div>
</form>
</div>
<div class="card cloud-admin-catalog-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Catalog</p>
<h5 class="mb-1">已保存的模版</h5>
<p class="text-muted mb-0">宿主机副本由引擎按需准备。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-disc"></i></span>
</div>
<div id="catalog-list" class="cloud-admin-catalog-list"></div>
<p class="cloud-admin-support-note"><i class="mdi mdi-check-decagram-outline"></i><span>支持 AlmaLinux 8/9/10、Debian 11/12/13、CentOS Stream 9/10,以及 Ubuntu 20.04 至 26.04 的 x86_64 cloud-init 镜像。</span></p>
</div>
</div>
</form>
</div>
<div class="card"><div class="card-body"><h5>已保存的模版</h5><div id="catalog-list"></div></div></div>
</div>
</section>
<script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -1,39 +1,148 @@
{assign var=admin_title value='宿主机设置'}
{assign var=admin_active value='hosts'}
{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css">
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
<section class="cloud-admin" data-cloud-admin="hosts">
<div class="mb-3"><h4>宿主机设置</h4><p class="text-muted">SSH 使用宿主机已有的 root 账号和私钥。先扫描并核对 SSH 主机指纹,再保存。私钥和口令加密存储,不会回显;后台会持续采集虚拟机指标。</p></div>
<p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status">正在加载…</p>
<form id="user-iso-settings-form" class="card mb-3">
<div class="card-body">
<h5>用户 ISO 功能</h5>
<p class="text-muted">默认关闭。关闭后普通用户看不到 ISO 导航和页面,相关读取、导入、任务及删除接口也会拒绝访问。</p>
<label class="form-check-label" for="user-iso-enabled"><input id="user-iso-enabled" class="form-check-input me-2" type="checkbox" {if !$admin_can_manage|default:false}disabled{/if}> 向普通用户开放 ISO 管理</label>
<div><button id="user-iso-settings-save" class="btn btn-outline-primary mt-3" type="submit" {if !$admin_can_manage|default:false}disabled{/if}>保存 ISO 开关</button></div>
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
<div class="flex-grow-1">
<p class="admin-eyebrow mb-1">Infrastructure</p>
<h4 class="fs-20 fw-semibold mb-1">宿主机设置</h4>
<p class="text-muted mb-0">管理计算节点连接、存储目录和公网网络配置。</p>
</div>
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions">
<p id="cloud-admin-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在加载…</p>
</div>
</div>
<form id="user-iso-settings-form" class="card cloud-admin-feature-card mb-3">
<div class="card-body">
<div class="cloud-admin-card-head cloud-admin-card-head-compact">
<div class="cloud-admin-feature-copy">
<span class="cloud-admin-card-icon"><i class="mdi mdi-disc-player"></i></span>
<div>
<h5 class="mb-1">用户 ISO 功能</h5>
<p class="text-muted mb-0">关闭后普通用户看不到 ISO 导航,相关读取、导入、任务及删除接口也会拒绝访问。</p>
</div>
</div>
<div class="cloud-admin-feature-actions">
<label class="cloud-admin-switch" for="user-iso-enabled">
<input id="user-iso-enabled" type="checkbox" {if !$admin_can_manage|default:false}disabled{/if}>
<span aria-hidden="true"></span>
<strong>向普通用户开放</strong>
</label>
<button id="user-iso-settings-save" class="btn btn-outline-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}>
<i class="mdi mdi-content-save-outline me-1"></i>保存开关
</button>
</div>
</div>
</div>
</form>
<div class="cloud-admin-grid cloud-admin-host-layout">
<aside class="cloud-admin-side">
<div class="card">
<div class="card-body">
<div class="cloud-admin-card-head cloud-admin-card-head-compact">
<div>
<p class="admin-eyebrow mb-1">Hosts</p>
<h5 class="mb-0">宿主机列表</h5>
</div>
<button id="host-new" class="btn btn-primary" type="button" {if !$admin_can_manage|default:false}disabled{/if}>
<i class="mdi mdi-plus me-1"></i>添加
</button>
</div>
<div id="host-list" class="cloud-admin-host-list"></div>
</div>
</div>
<div class="card cloud-admin-guide-card">
<div class="card-body">
<p class="admin-eyebrow mb-1">Security</p>
<h5 class="mb-2">连接安全</h5>
<p class="text-muted mb-0">SSH 使用宿主机已有的 root 账号和私钥。保存前必须扫描,并通过可信渠道核对主机指纹。</p>
</div>
</div>
</aside>
<form id="host-form" class="card cloud-admin-form-card">
<div class="card-body">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Configuration</p>
<h5 id="host-form-title" class="mb-1">添加宿主机</h5>
<p class="text-muted mb-0">私钥和口令加密存储且不会回显,后台采样不依赖网页登录。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-router-network"></i></span>
</div>
<input id="host-id" type="hidden">
<section class="cloud-admin-form-section" aria-labelledby="host-basic-title">
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-card-account-details-outline"></i></span>
<div><h6 id="host-basic-title">基本信息</h6><p>用于后台识别宿主机及其销售地区。</p></div>
</div>
<div class="cloud-admin-form-grid">
<div><label for="host-name" class="form-label">名称</label><input id="host-name" class="form-control" required maxlength="80"></div>
<div><label for="host-country-code" class="form-label">国家</label><select id="host-country-code" class="form-select" required><option value="">请选择国家</option><option value="CN">🇨🇳 中国</option><option value="JP">🇯🇵 日本</option><option value="US">🇺🇸 美国</option><option value="SG">🇸🇬 新加坡</option></select></div>
<div class="cloud-admin-full"><label for="host-region" class="form-label">具体地区</label><input id="host-region" class="form-control" required maxlength="64" placeholder="例如 HongKong 或 Tokyo"></div>
</div>
</section>
<section class="cloud-admin-form-section" aria-labelledby="host-connection-title">
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-shield-key-outline"></i></span>
<div><h6 id="host-connection-title">SSH 连接与凭据</h6><p>先核对指纹,再通过 HTTPS 提交凭据。</p></div>
</div>
<div class="cloud-admin-form-grid">
<div><label for="host-address" class="form-label">SSH IP / 域名</label><input id="host-address" class="form-control admin-mono" required autocomplete="off"></div>
<div><label for="host-port" class="form-label">SSH 端口(root)</label><input id="host-port" class="form-control" type="number" min="1" max="65535" value="22" required></div>
<div class="cloud-admin-full cloud-admin-fingerprint-box">
<button id="host-scan" class="btn btn-outline-primary" type="button" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-radar me-1"></i>扫描 SSH 主机指纹</button>
<pre id="host-fingerprint" class="cloud-admin-fingerprint admin-mono"></pre>
<label class="form-check mb-0"><input id="host-fingerprint-confirm" class="form-check-input" type="checkbox"><span class="form-check-label">我已通过可信渠道核对该指纹</span></label>
</div>
<div class="cloud-admin-full"><label for="host-private-key" class="form-label">SSH 私钥</label><textarea id="host-private-key" class="form-control admin-mono" rows="5" maxlength="65536" autocomplete="off" spellcheck="false" placeholder="首次添加请粘贴现有私钥;编辑时留空保留原私钥"></textarea><div class="form-text">仅通过 HTTPS 提交;请勿将密钥粘贴到工单或日志。</div></div>
<div class="cloud-admin-full"><label for="host-passphrase" class="form-label">私钥解锁口令</label><input id="host-passphrase" class="form-control" type="password" maxlength="1024" autocomplete="new-password" placeholder="加密私钥填写;编辑时留空保留已保存口令"><div class="form-text">加密保存,面板重启后可自动连接。</div></div>
</div>
</section>
<section class="cloud-admin-form-section" aria-labelledby="host-storage-title">
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-database-outline"></i></span>
<div><h6 id="host-storage-title">存储目录</h6><p>配置系统盘、用户 ISO 与救援 ISO 的独立存储位置。</p></div>
</div>
<div class="cloud-admin-form-grid">
<div><label for="host-storage-pool" class="form-label">磁盘目录 / 存储池</label><input id="host-storage-pool" class="form-control admin-mono" value="/home/kvm" required></div>
<div><label for="host-iso-pool" class="form-label">安装 ISO 目录 / 池</label><input id="host-iso-pool" class="form-control admin-mono" value="/home/iso" required><div class="form-text">个人镜像会同步到此目录,必须使用目录类型存储池。</div></div>
<div class="cloud-admin-full"><label for="host-rescue-pool" class="form-label">独立救援 ISO 目录 / 池</label><input id="host-rescue-pool" class="form-control admin-mono" value="/home/rescue-iso"></div>
</div>
</section>
<section class="cloud-admin-form-section" aria-labelledby="host-network-title">
<div class="cloud-admin-section-title">
<span><i class="mdi mdi-access-point-network"></i></span>
<div><h6 id="host-network-title">网络配置</h6><p>定义默认网桥、公网地址池、网关与 DNS。</p></div>
</div>
<div class="cloud-admin-form-grid">
<div><label for="host-network" class="form-label">默认网桥 / 网络</label><input id="host-network" class="form-control admin-mono" value="bridge:br0" required></div>
<div><label for="host-public-pool" class="form-label">实际公网地址池 CIDR</label><input id="host-public-pool" class="form-control admin-mono" placeholder="123.123.123.112/28"><div class="form-text">只分配地址池内未使用的地址,后台会自动规范 CIDR。</div></div>
<div><label for="host-vm-prefix" class="form-label">客户机网络前缀</label><input id="host-vm-prefix" class="form-control" type="number" min="24" max="30" placeholder="例如 24"><div class="form-text">可与地址池前缀不同,请按服务商路由要求设置。</div></div>
<div><label for="host-gateway" class="form-label">公网网关</label><input id="host-gateway" class="form-control admin-mono" placeholder="123.123.123.113"></div>
<div class="cloud-admin-full"><label for="host-dns" class="form-label">DNS(逗号分隔)</label><input id="host-dns" class="form-control admin-mono" value="1.1.1.1, 8.8.8.8"></div>
<div class="cloud-admin-full"><label for="host-reserved" class="form-label">保留 / 禁用 IP(逗号分隔)</label><input id="host-reserved" class="form-control admin-mono" placeholder="已有虚拟机或宿主机占用的地址"><div class="form-text">网关、网络地址和广播地址自动排除;请额外排除外部虚拟机已占用的 IP。</div></div>
</div>
</section>
<div class="cloud-admin-form-footer">
<label class="form-check mb-0"><input id="host-enabled" class="form-check-input" type="checkbox" checked><span class="form-check-label">允许此宿主机提供套餐服务</span></label>
<div class="cloud-admin-submit">
<p id="host-form-error" class="text-danger mb-0" role="alert"></p>
<button id="host-save" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-connection me-1"></i>测试连接并保存</button>
</div>
</div>
</div>
</form>
</div>
</form>
<div class="cloud-admin-grid"><div class="card"><div class="card-body"><button id="host-new" class="btn btn-primary mb-3" type="button" {if !$admin_can_manage|default:false}disabled{/if}>添加宿主机</button><div id="host-list"></div></div></div>
<form id="host-form" class="card"><div class="card-body"><h5 id="host-form-title">添加宿主机</h5><input id="host-id" type="hidden"><div class="cloud-admin-form-grid">
<div><label for="host-name" class="form-label">名称</label><input id="host-name" class="form-control" required maxlength="80"></div>
<div><label for="host-country-code" class="form-label">国家</label><select id="host-country-code" class="form-select" required><option value="">请选择国家</option><option value="CN">🇨🇳 中国</option><option value="JP">🇯🇵 日本</option><option value="US">🇺🇸 美国</option><option value="SG">🇸🇬 新加坡</option></select></div>
<div><label for="host-region" class="form-label">具体地区</label><input id="host-region" class="form-control" required maxlength="64" placeholder="例如 HongKong 或 Tokyo"></div>
<div><label for="host-address" class="form-label">SSH IP / 域名</label><input id="host-address" class="form-control" required autocomplete="off"></div>
<div><label for="host-port" class="form-label">SSH 端口(root)</label><input id="host-port" class="form-control" type="number" min="1" max="65535" value="22" required></div>
<div class="cloud-admin-full"><button id="host-scan" class="btn btn-outline-primary" type="button" {if !$admin_can_manage|default:false}disabled{/if}>扫描 SSH 主机指纹</button><pre id="host-fingerprint" class="mt-2 cloud-admin-notice"></pre><label><input id="host-fingerprint-confirm" type="checkbox"> 我已通过可信渠道核对该指纹</label></div>
<div class="cloud-admin-full"><label for="host-private-key" class="form-label">SSH 私钥</label><textarea id="host-private-key" class="form-control" rows="5" maxlength="65536" autocomplete="off" spellcheck="false" placeholder="首次添加请粘贴现有私钥;编辑时留空保留原私钥"></textarea><small class="text-muted">仅通过 HTTPS 提交;请勿将密钥粘贴到工单或日志。</small></div>
<div class="cloud-admin-full"><label for="host-passphrase" class="form-label">私钥解锁口令</label><input id="host-passphrase" class="form-control" type="password" maxlength="1024" autocomplete="new-password" placeholder="加密私钥填写;编辑时留空保留已保存口令"><small class="text-muted">加密保存,面板重启后可自动连接,后台采样不依赖网页登录。</small></div>
<div><label for="host-storage-pool" class="form-label">磁盘目录 / 存储池</label><input id="host-storage-pool" class="form-control" value="/home/kvm" required></div>
<div><label for="host-iso-pool" class="form-label">安装 ISO 目录 / 池</label><input id="host-iso-pool" class="form-control" value="/home/iso" required><small class="text-muted">开放用户 ISO 功能后,个人镜像会同步到此目录;必须使用目录类型存储池。</small></div>
<div><label for="host-rescue-pool" class="form-label">独立救援 ISO 目录 / 池</label><input id="host-rescue-pool" class="form-control" value="/home/rescue-iso"></div>
<div><label for="host-network" class="form-label">默认网桥 / 网络</label><input id="host-network" class="form-control" value="bridge:br0" required></div>
<div><label for="host-public-pool" class="form-label">实际公网地址池 CIDR</label><input id="host-public-pool" class="form-control" placeholder="123.123.123.112/28"><small class="text-muted">只分配该地址池内未使用的地址;可输入 .113/28,后台会规范为 .112/28。</small></div>
<div><label for="host-vm-prefix" class="form-label">客户机网络前缀</label><input id="host-vm-prefix" class="form-control" type="number" min="24" max="30" placeholder="例如 24"><small class="text-muted">可与地址池 /28 不同,按服务商路由要求设置。</small></div>
<div><label for="host-gateway" class="form-label">公网网关</label><input id="host-gateway" class="form-control" placeholder="123.123.123.113"></div>
<div><label for="host-dns" class="form-label">DNS(逗号分隔)</label><input id="host-dns" class="form-control" value="1.1.1.1, 8.8.8.8"></div>
<div class="cloud-admin-full"><label for="host-reserved" class="form-label">保留 / 禁用 IP(逗号分隔)</label><input id="host-reserved" class="form-control" placeholder="已有虚拟机或宿主机占用的地址"><small class="text-muted">网关、网络地址和广播地址自动排除。请额外排除已有外部虚拟机占用的 IP。</small></div>
<div class="cloud-admin-full"><label><input id="host-enabled" type="checkbox" checked> 允许此宿主机提供套餐服务</label></div>
</div><p id="host-form-error" class="text-danger mt-3" role="alert"></p><button id="host-save" class="btn btn-primary" type="submit" {if !$admin_can_manage|default:false}disabled{/if}>测试连接并保存</button></div></form></div>
</section>
<script type="module" src="/cloud/admin.js?v={$venix_asset_version}"></script>
{include file='admin/static_footer.tpl'}

@ -2,69 +2,179 @@
{assign var=admin_active value='telegram'}
{include file='admin/static_header.tpl'}
<div class="py-3"><h4 class="fs-20 fw-semibold">Telegram 工单提醒</h4><p class="text-muted">仅用于管理员接收工单通知。用户通过网站查看和回复工单,不使用 Telegram 登录、绑定或群组功能。</p></div>
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column">
<div class="flex-grow-1">
<h4 class="fs-20 fw-semibold mb-1">Telegram 工单提醒</h4>
<p class="text-muted mb-0">配置工单机器人、独立通信域名和管理员私聊接收账号。用户仍只通过网站查看与回复工单。</p>
</div>
<div class="text-sm-end mt-3 mt-sm-0 admin-config-actions">
<span class="admin-config-status {if $telegram_enabled && $telegram_configured}is-success{else}is-loading{/if}" id="telegramPageStatus">
{if $telegram_enabled && $telegram_configured}通知服务已就绪{elseif $telegram_enabled}配置尚未完成{else}通知服务未启用{/if}
</span>
</div>
</div>
{if $telegram_config.configuration_error|default:'' != ''}
<div class="alert alert-danger" role="alert">
<i class="mdi mdi-alert-circle-outline me-1"></i>{$telegram_config.configuration_error|escape:'html'}
</div>
{/if}
<div class="row g-3 mb-3">
<div class="col-xl-3 col-md-6"><div class="card admin-ticket-stat h-100"><div class="card-body">
<span class="admin-ticket-stat-icon {if !$telegram_enabled}is-closed{/if}"><i class="mdi mdi-bell-ring-outline"></i></span>
<div><p class="text-muted mb-1">通知开关</p><h5 class="mb-0">{if $telegram_enabled}已启用{else}未启用{/if}</h5></div>
</div></div></div>
<div class="col-xl-3 col-md-6"><div class="card admin-ticket-stat h-100"><div class="card-body">
<span class="admin-ticket-stat-icon {if !$telegram_config.bot_token_configured}is-open{/if}"><i class="mdi mdi-robot-outline"></i></span>
<div><p class="text-muted mb-1">Bot Token</p><h5 class="mb-0">{if $telegram_config.bot_token_configured}已加密保存{else}尚未配置{/if}</h5></div>
</div></div></div>
<div class="col-xl-3 col-md-6"><div class="card admin-ticket-stat h-100"><div class="card-body">
<span class="admin-ticket-stat-icon {if !$telegram_config.webhook_secret_configured}is-open{/if}"><i class="mdi mdi-shield-key-outline"></i></span>
<div><p class="text-muted mb-1">Webhook 密钥</p><h5 class="mb-0">{if $telegram_config.webhook_secret_configured}已安全生成{else}尚未生成{/if}</h5></div>
</div></div></div>
<div class="col-xl-3 col-md-6"><div class="card admin-ticket-stat h-100"><div class="card-body">
<span class="admin-ticket-stat-icon {if !$telegram_bound}is-closed{/if}"><i class="mdi mdi-account-check-outline"></i></span>
<div><p class="text-muted mb-1">接收管理员</p><h5 class="mb-0">{if $telegram_bound}管理员 #{$telegram_admin_id|escape:'html'}{else}尚未绑定{/if}</h5></div>
</div></div></div>
</div>
<div class="row g-3">
<section class="col-lg-6"><div class="card"><div class="card-body">
<h5>服务状态</h5>
<dl class="row"><dt class="col-sm-5">通知开关</dt><dd class="col-sm-7">{if $telegram_enabled}已开启{else}未开启{/if}</dd><dt class="col-sm-5">机器人配置</dt><dd class="col-sm-7">{if $telegram_configured}已配置{else}未配置{/if}</dd><dt class="col-sm-5">管理员绑定</dt><dd class="col-sm-7">{if $telegram_bound}已绑定管理员 #{$telegram_admin_id|escape:"html"}{else}未绑定{/if}</dd></dl>
<p class="text-muted">机器人 Token 和请求密钥由服务器配置提供,不会在网页展示或保存。请先配置机器人,再注册 Webhook。</p>
<button class="btn btn-outline-primary" id="telegramWebhook" type="button" {if !$telegram_enabled || !$telegram_configured || !$admin_can_manage|default:false}disabled{/if}>注册 Webhook</button>
</div></div></section>
<section class="col-lg-6"><div class="card"><div class="card-body">
<h5>管理员私聊绑定</h5>
<p>生成一次性绑定命令后,使用管理员自己的 Telegram 账号,在与机器人单独的私聊中发送该命令。群聊绑定无效。</p>
<div class="d-flex flex-wrap gap-2"><button class="btn btn-primary" id="telegramBind" type="button" {if !$telegram_enabled || !$telegram_configured || !$admin_can_manage|default:false}disabled{/if}>生成绑定命令</button><button class="btn btn-outline-danger" id="telegramUnbind" type="button" {if !$telegram_bound || !$admin_can_manage|default:false}disabled{/if}>解除绑定</button></div>
<div class="alert alert-info mt-3" id="telegramBinding" hidden><code id="telegramCommand"></code><p class="mb-0 mt-2" id="telegramExpiry"></p><p class="mb-0">发送后刷新本页确认绑定状态。绑定命令仅在当前页面显示,请勿公开。</p></div>
<p class="mt-3" id="telegramStatus" role="status" aria-live="polite"></p>
</div></div></section>
<section class="col-xl-7">
<div class="card h-100"><div class="card-body">
<div class="d-flex align-items-start justify-content-between gap-3 mb-3">
<div><p class="admin-eyebrow mb-1">Bot Configuration</p><h5 class="card-title mb-1">机器人与通信地址</h5><p class="text-muted mb-0">配置保存到数据库;敏感项加密存储且永不回显。</p></div>
<span class="admin-ticket-stat-icon"><i class="mdi mdi-telegram"></i></span>
</div>
<form id="telegramConfigForm" autocomplete="off">
<div class="form-check form-switch mb-3">
<input class="form-check-input" id="telegramEnabled" name="telegram_enabled" type="checkbox" value="true" {if $telegram_enabled}checked{/if} {if !$admin_can_manage|default:false}disabled{/if}>
<label class="form-check-label fw-semibold" for="telegramEnabled">启用 Telegram 工单提醒</label>
<div class="form-text">关闭后不会接收 Webhook,也不会发送工单通知;已保存配置和管理员绑定会保留。</div>
</div>
<div class="mb-3">
<label class="form-label" for="telegramWebhookBaseUrl">独立 Telegram 通信域名</label>
<input class="form-control" id="telegramWebhookBaseUrl" name="telegram_webhook_base_url" type="url" value="{$telegram_config.webhook_base_url|default:''|escape:'html'}" maxlength="255" inputmode="url" placeholder="https://tg.example.com" {if !$admin_can_manage|default:false}disabled{/if}>
<div class="form-text">只填写 HTTPS 根地址,不含路径、查询参数或结尾斜杠。该域名需通过 DNS、TLS 与 Web 服务器指向本应用。</div>
</div>
<div class="mb-3">
<label class="form-label" for="telegramBotToken">Telegram Bot Token</label>
<input class="form-control admin-mono" id="telegramBotToken" name="telegram_bot_token" type="password" maxlength="256" autocomplete="new-password" spellcheck="false" placeholder="{if $telegram_config.bot_token_configured}已配置,留空保留现有 Token{else}请输入 BotFather 提供的 Token{/if}" {if !$admin_can_manage|default:false}disabled{/if}>
<div class="form-text">Token 只在本次保存请求中发送。更换 Token 会自动解除旧管理员绑定,避免向错误机器人继续投递。</div>
</div>
<div class="form-check mb-3">
<input class="form-check-input" id="telegramRotateSecret" name="telegram_rotate_webhook_secret" type="checkbox" value="true" {if !$admin_can_manage|default:false}disabled{/if}>
<label class="form-check-label" for="telegramRotateSecret">轮换 Webhook 请求密钥</label>
<div class="form-text">首次保存会自动生成高强度密钥。主动轮换后旧 Webhook 请求立即失效,需要重新注册 Webhook。</div>
</div>
<div class="d-flex align-items-center flex-wrap gap-2">
<button class="btn btn-primary" id="telegramConfigSave" type="submit" {if !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-content-save-outline me-1"></i>保存 Telegram 配置</button>
<span class="text-muted small">保存成功后再执行右侧的 Webhook 注册。</span>
</div>
</form>
</div></div>
</section>
<section class="col-xl-5">
<div class="card mb-3"><div class="card-body">
<div class="d-flex align-items-start justify-content-between gap-3 mb-3">
<div><p class="admin-eyebrow mb-1">Webhook</p><h5 class="card-title mb-1">注册 Telegram 回调</h5><p class="text-muted mb-0">把当前独立通信地址注册到 Telegram。</p></div>
<span class="admin-ticket-stat-icon is-open"><i class="mdi mdi-webhook"></i></span>
</div>
<label class="form-label">当前回调地址</label>
<div class="border rounded-2 bg-light px-3 py-2 mb-3 admin-mono text-break">{$telegram_config.webhook_url|default:'尚未配置通信域名'|escape:'html'}</div>
<button class="btn btn-light" id="telegramWebhook" type="button" {if !$telegram_enabled || !$telegram_configured || !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-cloud-sync-outline me-1"></i>注册当前 Webhook</button>
</div></div>
<div class="card"><div class="card-body">
<div class="d-flex align-items-start justify-content-between gap-3 mb-3">
<div><p class="admin-eyebrow mb-1">Private Binding</p><h5 class="card-title mb-1">管理员私聊绑定</h5><p class="text-muted mb-0">只接受管理员本人的 Telegram 私聊,群组和转发消息无效。</p></div>
<span class="admin-ticket-stat-icon"><i class="mdi mdi-account-lock-outline"></i></span>
</div>
<div class="d-flex flex-wrap gap-2">
<button class="btn btn-primary" id="telegramBind" type="button" {if !$telegram_enabled || !$telegram_configured || !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-link-variant-plus me-1"></i>生成绑定命令</button>
<button class="btn btn-outline-danger" id="telegramUnbind" type="button" {if !$telegram_bound || !$admin_can_manage|default:false}disabled{/if}><i class="mdi mdi-link-variant-off me-1"></i>解除绑定</button>
</div>
<div class="alert alert-info mt-3 mb-0" id="telegramBinding" hidden>
<div class="d-flex align-items-center justify-content-between gap-2 flex-wrap"><code class="text-break" id="telegramCommand"></code><button class="btn btn-sm btn-light" id="telegramCopyCommand" type="button"><i class="mdi mdi-content-copy me-1"></i>复制</button></div>
<p class="mb-0 mt-2" id="telegramExpiry"></p>
<p class="mb-0">请在机器人私聊中发送,成功后刷新本页确认绑定状态;不要公开这条一次性命令。</p>
</div>
</div></div>
</section>
</div>
<div class="mt-3 d-flex justify-content-end"><span class="admin-config-status" id="telegramStatus" role="status" aria-live="polite">等待操作</span></div>
{literal}
<script>
(function () {
'use strict';
var busy = false;
var timer = null;
var form = document.getElementById('telegramConfigForm');
var save = document.getElementById('telegramConfigSave');
var bind = document.getElementById('telegramBind');
var unbind = document.getElementById('telegramUnbind');
var webhook = document.getElementById('telegramWebhook');
var copy = document.getElementById('telegramCopyCommand');
var status = document.getElementById('telegramStatus');
var binding = document.getElementById('telegramBinding');
var command = document.getElementById('telegramCommand');
var expiry = document.getElementById('telegramExpiry');
var controls = [save, bind, unbind, webhook].filter(Boolean);
async function request(url) {
function showStatus(message, state) {
status.textContent = message;
status.className = 'admin-config-status' + (state ? ' is-' + state : '');
}
function encodeForm(source) {
var body = new URLSearchParams();
new FormData(source).forEach(function (value, key) { body.append(key, String(value)); });
return body.toString();
}
async function request(url, body) {
if (!window.ADMIN_CAN_MANAGE || busy) return null;
busy = true;
var original = [bind.disabled, unbind.disabled, webhook.disabled];
[bind, unbind, webhook].forEach(function (button) { button.disabled = true; });
status.textContent = '正在处理…';
var original = controls.map(function (button) { return button.disabled; });
controls.forEach(function (button) { button.disabled = true; });
showStatus('正在处理…', 'loading');
try {
var response = await fetch(url, {
method: 'POST', credentials: 'same-origin',
headers: {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'X-Admin-CSRF-Token': window.ADMIN_CSRF_TOKEN || ''},
body: ''
headers: {'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 'X-Requested-With': 'XMLHttpRequest', 'X-Admin-CSRF-Token': window.ADMIN_CSRF_TOKEN || ''},
body: body || ''
});
var data = await response.json();
if (!response.ok || data.ret === 0 || data.error) throw new Error(data.msg || data.error || '操作失败');
status.textContent = data.msg || '操作完成';
var text = await response.text();
var data;
try { data = JSON.parse(text); }
catch (error) { throw new Error('服务器未返回有效结果(HTTP ' + response.status + ')'); }
if (!response.ok || Number(data.ret) !== 1) throw new Error(data.msg || data.error || '操作失败');
showStatus(data.msg || '操作完成', 'success');
return data;
} catch (error) {
status.textContent = error.message || '请求失败';
showStatus(error.message || '请求失败', 'error');
return null;
} finally {
busy = false;
[bind, unbind, webhook].forEach(function (button, i) { button.disabled = original[i]; });
controls.forEach(function (button, index) { button.disabled = original[index]; });
}
}
form.addEventListener('submit', async function (event) {
event.preventDefault();
var data = await request('/admin/telegram/config', encodeForm(form));
if (!data) return;
document.getElementById('telegramBotToken').value = '';
document.getElementById('telegramRotateSecret').checked = false;
window.setTimeout(function () { window.location.reload(); }, 700);
});
bind.addEventListener('click', async function () {
var data = await request('/admin/telegram/bind');
var data = await request('/admin/telegram/bind', '');
if (!data) return;
var code = String(data.code || '');
var seconds = Number(data.expires_in);
if (!/^[A-Za-z0-9_-]{8,128}$/.test(code) || !Number.isFinite(seconds) || seconds <= 0) {
status.textContent = '绑定命令返回无效,请重试。'; return;
}
if (!/^[A-Za-z0-9_-]{8,128}$/.test(code) || !Number.isFinite(seconds) || seconds <= 0) { showStatus('绑定命令返回无效,请重试。', 'error'); return; }
if (timer) clearInterval(timer);
command.textContent = '/start ' + code;
binding.hidden = false;
@ -74,15 +184,21 @@
expiry.textContent = left ? '绑定命令将在 ' + left + ' 秒后失效。' : '命令已过期,请重新生成。';
if (!left) { command.textContent = ''; clearInterval(timer); timer = null; }
}
updateExpiry(); timer = setInterval(updateExpiry, 1000);
updateExpiry(); timer = window.setInterval(updateExpiry, 1000);
});
unbind.addEventListener('click', async function () {
if (!window.confirm('解除后将不再向当前 Telegram 账号发送工单提醒,确定解除?')) return;
if (await request('/admin/telegram/unbind')) window.location.reload();
if (await request('/admin/telegram/unbind', '')) window.location.reload();
});
webhook.addEventListener('click', async function () {
if (!window.confirm('确定为当前网站注册工单机器人 Webhook?')) return;
await request('/admin/telegram/webhook');
if (!window.confirm('确定把页面显示的回调地址注册到当前 Telegram Bot?')) return;
await request('/admin/telegram/webhook', '');
});
copy.addEventListener('click', async function () {
var value = command.textContent || '';
if (!value) return;
try { await navigator.clipboard.writeText(value); showStatus('绑定命令已复制。', 'success'); }
catch (error) { showStatus('自动复制失败,请手动选择绑定命令。', 'error'); }
});
})();
</script>

@ -1,61 +1,92 @@
{assign var=admin_title value='在线更新'}
{assign var=admin_active value='update'}
{include file='admin/static_header.tpl'}
<link rel="stylesheet" href="/cloud/admin.css?v={$venix_asset_version}">
<section class="cloud-admin cloud-update" aria-labelledby="update-page-title">
<div class="mb-3">
<h4 id="update-page-title">在线更新</h4>
<p class="text-muted">只会快进更新系统固定的私有仓库与分支;不安装 Composer/Python 依赖、不准备依赖暂存区,也不改写 systemd unit。目标版本修改 <code>engine/requirements.txt</code>、<code>web/composer.json</code>、<code>web/composer.lock</code> 或 <code>deploy/**</code> 时会在停服和切换前拒绝,请按部署文档通过 SSH 升级。</p>
<div class="py-3 d-flex align-items-sm-center flex-sm-row flex-column cloud-admin-page-head">
<div class="flex-grow-1">
<p class="admin-eyebrow mb-1">System</p>
<h4 id="update-page-title" class="fs-20 fw-semibold mb-1">在线更新</h4>
<p class="text-muted mb-0">安全检查固定私有仓库与分支,并执行受约束的快进更新。</p>
</div>
<div class="text-sm-end mt-3 mt-sm-0 cloud-admin-actions">
<p id="update-page-status" class="alert alert-info cloud-admin-notice" role="status" aria-live="polite">正在读取更新配置…</p>
</div>
</div>
<p id="update-page-status" class="alert alert-info cloud-admin-notice" role="status">正在读取更新配置…</p>
<div class="cloud-admin-grid">
<form id="update-settings-form" class="card" autocomplete="off">
<div class="alert alert-warning cloud-admin-guidance" role="note">
<i class="mdi mdi-alert-outline"></i>
<span>在线更新不会安装 Composer/Python 依赖,也不会改写 systemd unit。若目标版本修改依赖清单或 <code>deploy/**</code>,系统会在停服前拒绝,请改用 SSH 升级。</span>
</div>
<div class="cloud-admin-grid cloud-update-grid">
<form id="update-settings-form" class="card cloud-update-card" autocomplete="off">
<div class="card-body">
<h5>更新源与凭据</h5>
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Repository</p>
<h5 class="mb-1">更新源与凭据</h5>
<p class="text-muted mb-0">仓库与分支由服务器固定,网页只维护访问令牌。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-source-branch"></i></span>
</div>
<dl class="cloud-update-details">
<div><dt>固定仓库</dt><dd id="update-repository">正在读取…</dd></div>
<div><dt>固定分支</dt><dd id="update-branch">正在读取…</dd></div>
<div><dt>当前提交</dt><dd id="update-current-commit">正在读取…</dd></div>
<div><dt>检出状态</dt><dd id="update-checkout-state">正在读取…</dd></div>
</dl>
<label for="update-access-token" class="form-label">Gitea 私有仓库访问令牌</label>
<input id="update-access-token" class="form-control" type="password" maxlength="4096"
autocomplete="new-password" spellcheck="false" placeholder="留空即保留现有令牌">
<small class="text-muted">令牌只在保存请求中发送,不会回显或保存在浏览器中。</small>
<div class="form-check mt-3">
<input id="update-clear-token" class="form-check-input" type="checkbox">
<label class="form-check-label" for="update-clear-token">明确清除已保存的访问令牌</label>
<div class="cloud-update-credential">
<label for="update-access-token" class="form-label">Gitea 私有仓库访问令牌</label>
<input id="update-access-token" class="form-control admin-mono" type="password" maxlength="4096" autocomplete="new-password" spellcheck="false" placeholder="留空即保留现有令牌">
<div class="form-text">令牌只在保存请求中发送,不会回显或保存在浏览器中。</div>
<label class="form-check mt-3 mb-0" for="update-clear-token"><input id="update-clear-token" class="form-check-input" type="checkbox"><span class="form-check-label">明确清除已保存的访问令牌</span></label>
</div>
<button id="update-settings-save" class="btn btn-primary mt-3" type="submit">保存令牌设置</button>
<div class="cloud-admin-form-actions"><button id="update-settings-save" class="btn btn-primary" type="submit"><i class="mdi mdi-content-save-outline me-1"></i>保存令牌设置</button></div>
</div>
</form>
<div class="card">
<div class="card cloud-update-card">
<div class="card-body">
<h5>检查并执行</h5>
<p>每次执行都必须先重新检查。检查得到的本地与远端提交会作为不可变条件提交,版本变化时引擎会拒绝更新。</p>
<button id="update-check" class="btn btn-outline-primary" type="button">检查更新</button>
<dl class="cloud-update-details mt-3">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Deploy</p>
<h5 class="mb-1">检查并执行</h5>
<p class="text-muted mb-0">每次执行前都必须重新检查并锁定本地与远端提交。</p>
</div>
<span class="cloud-admin-card-icon is-warning"><i class="mdi mdi-update"></i></span>
</div>
<dl class="cloud-update-details">
<div><dt>检查状态</dt><dd id="update-check-status">尚未检查</dd></div>
<div><dt>已锁定本地提交</dt><dd id="update-checked-current">—</dd></div>
<div><dt>已锁定远端提交</dt><dd id="update-checked-remote">—</dd></div>
</dl>
<button id="update-apply" class="btn btn-danger" type="button" disabled>执行在线更新</button>
<div class="cloud-update-actions">
<button id="update-check" class="btn btn-outline-primary" type="button"><i class="mdi mdi-source-branch-check me-1"></i>检查更新</button>
<button id="update-apply" class="btn btn-danger" type="button" disabled><i class="mdi mdi-update me-1"></i>执行在线更新</button>
</div>
</div>
</div>
</div>
<div class="card mt-4">
<div class="card mt-3 cloud-update-job-card">
<div class="card-body">
<h5>更新任务</h5>
<p class="text-muted">更新期间 PHP 和私有引擎会重启,短暂连接失败会自动重试。请保留本页面,勿重复提交执行请求。若任务进入 <code>blocked</code>,代码或数据库状态尚未确认,页面会保持维护锁并禁用变更操作;请通过 SSH 核查。如果中断发生在数据库迁移期间,仅回退源码不会解除维护锁,必须人工完成并验证迁移与服务兼容性。</p>
<dl class="cloud-update-details">
<div class="cloud-admin-card-head">
<div>
<p class="admin-eyebrow mb-1">Progress</p>
<h5 class="mb-1">更新任务</h5>
<p class="text-muted mb-0">PHP 与私有引擎重启期间会自动只读恢复任务,请保留本页面且不要重复提交。</p>
</div>
<span class="cloud-admin-card-icon"><i class="mdi mdi-timeline-clock-outline"></i></span>
</div>
<dl class="cloud-update-details cloud-update-job-details">
<div><dt>任务编号</dt><dd id="update-job-id">—</dd></div>
<div><dt>任务状态</dt><dd id="update-job-status">—</dd></div>
<div><dt>当前阶段</dt><dd id="update-job-phase">—</dd></div>
<div><dt>结果</dt><dd id="update-job-result">—</dd></div>
</dl>
<p class="cloud-update-warning mb-0"><i class="mdi mdi-lock-alert-outline"></i><span>若任务进入 <code>blocked</code>,维护锁会保持启用。数据库迁移中断时仅回退源码不会解除锁,必须通过 SSH 完成并验证恢复。</span></p>
</div>
</div>
</section>

@ -1 +1 @@
{assign var=venix_asset_version value='2026092902' scope='global'}
{assign var=venix_asset_version value='2026092903' scope='global'}

@ -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) {

@ -1,6 +1,5 @@
<?php
require dirname(__DIR__) . '/app/Services/Config.php';
require dirname(__DIR__) . '/app/Services/TicketTelegramNotifier.php';
use App\Services\TicketTelegramNotifier as Notifications;
@ -12,17 +11,15 @@ function check($value, string $label): void
}
}
$System_Config = ['enable_telegram' => '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";

@ -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);

Loading…
Cancel
Save