You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/TicketTelegramConfig.php

461 lines
18 KiB
PHP

<?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_data_key')) {
return 'Telegram 凭据无法解密,请检查 cloud_data_key 配置';
}
return 'Telegram 配置无效,请在管理员页面重新保存';
}
}