diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index a15a73ba..4d08dfde 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -79,6 +79,14 @@ mariadb -h DB_HOST -P DB_PORT -u DB_USER -p BUSINESS_DB < /home/virt-cloud/web/s 服务条款和隐私政策按语言维护草稿与不可变发布版本,但不按域名拆分;所有配置域名读取同一份已发布内容,页面中的 `{{site_name}}` 会在展示时替换为当前站点名称。未导入增量表时公开页面使用内置安全文本,后台会明确提示先执行该 SQL,且不会把草稿误当作已发布内容。 +已经运行当前 `go` 分支 schema 的测试环境,在发布 Telegram 工单直接回复前,必须先导入持久消息映射表: + +```bash +mariadb -h DB_HOST -P DB_PORT -u DB_USER -p BUSINESS_DB < /home/virt-cloud/web/sql/ticket_telegram_replies.sql +``` + +顺序必须是“先备份并建表,再更新 PHP 代码,最后重载 PHP-FPM”。该表只保存工单通知与 Telegram 消息 ID 的映射,不回填历史通知;只有更新后新发送且成功记录的通知可以在 Telegram 中直接回复。发送超时会保留 `unknown` 栅栏并禁止自动重发;管理员应改用面板处理该条工单。 + 若实例是在缺少 PHP 模板展示快照的早期 Go Agent 版本中创建,更新面板代码后先执行只读检查,再显式应用元数据修复: ```bash diff --git a/docs/PRUNING_REPORT.md b/docs/PRUNING_REPORT.md index 4604ee63..5871dfd7 100644 --- a/docs/PRUNING_REPORT.md +++ b/docs/PRUNING_REPORT.md @@ -9,7 +9,7 @@ - 云套餐、库存、订单、发票、支付、独立预付费账期、冻结到用户与商业线路组的共享流量池、严格 FEFO 流量分配和三天未支付续费宽限。有限额度到期只作废自身未用部分;无限流量账期不加入有限流量池,旧的未入池账期继续使用实例独立额度。 - 多宿主机、资源池、容量策略、reservation、具体公网 IP 账本、多 CIDR、云镜像、救援 ISO、快照、防火墙、指标与控制台入口。 - 同地区 direct L3 VPC:后台地区 CIDR 池、用户 VPC/IPAM、实例冷启动连接与断开、宿主机路由投影和维护迁移保留私网 IP/MAC。VPC 不提供跨地区互联、NAT 或二层广播;独立备份恢复和云快照新建实例不继承源实例 VPC。 -- 管理员工单 Telegram 通知;普通用户仍只在网页处理工单。 +- 管理员工单 Telegram 通知,以及当前绑定的超级管理员对已映射通知的纯文本回复;普通用户仍只在网页处理工单。 - 公开产品落地页,以及后台统一维护、带草稿和发布历史的全局服务条款与隐私政策页面;法律内容不按域名拆分。 - 后台全局 S3 兼容对象存储应用配置、密钥密封和只读连接验证;管理员可把受支持实例的完整系统盘备份上传到对象存储,并在原宿主机或其他合格的 `bridge:br0` 宿主机使用全新公网 IP 创建独立免计费实例。普通用户可按服务周期购买自动备份,在实例设置中选择每天或每周执行并保留最多两份;全局备份库独立于源实例生命周期,源实例删除后仍可恢复或清理对象。增量链和管理员手工备份的自动保留策略暂未接入。 diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md index 9f486060..75cf4ae1 100644 --- a/docs/VALIDATION.md +++ b/docs/VALIDATION.md @@ -122,6 +122,7 @@ jq empty deploy/*.json.example - observer 单飞执行,单次请求有超时,总观察有绝对截止;`hidden`/`pagehide` 会停止,恢复可见时只允许继续同一 task GET。 - 观察停止只提示稍后在任务中心查看,不表示失败,也不取消或重发任务。 - 任务中心分别查询 active/completed,显示未读数量,并在已完成内容真实渲染后显式标记已读。 +- Telegram 工单验收必须覆盖:绑定成功回执;新工单和用户回复的脱敏完整通知;只允许当前绑定超级管理员在私聊中通过 `reply_to_message` 回复已映射通知;群聊、转发、机器人、旧绑定代次、未知消息、已关闭工单和非文本消息均不得写入回复。同一 `update_id` 重放只能写入一次;工单已提交后的 Telegram 确认发送失败不得回滚或要求重放。 - 全部 UI 不显示“待核对”、`uncertain`、`needs_attention`、停止自动核对、自动恢复、任务重试或续作旧 mutation 的控件。 - Unix 秒必须按秒转换;错误文本来自本地白名单,不显示 Agent 自由文本、路径、密钥或载荷。 - 服务条款和隐私政策的公开页面只读取最近一次已发布版本;保存草稿、预览草稿和发布失败都不能改变公开内容。 diff --git a/web/app/Services/Ticket/TicketNotificationTransportAdapter.php b/web/app/Services/Ticket/TicketNotificationTransportAdapter.php index 3bf6a43d..1f76d967 100644 --- a/web/app/Services/Ticket/TicketNotificationTransportAdapter.php +++ b/web/app/Services/Ticket/TicketNotificationTransportAdapter.php @@ -19,6 +19,9 @@ final class TicketNotificationTransportAdapter implements TicketNotificationTran public function sendTelegram(TicketEvent $event): void { - TicketTelegramNotifier::notify($event); + if (TicketTelegramNotifier::notify($event) + === TicketTelegramNotificationResult::Failed) { + throw new \RuntimeException('Telegram ticket delivery failed'); + } } } diff --git a/web/app/Services/Ticket/TicketTelegramNotificationResult.php b/web/app/Services/Ticket/TicketTelegramNotificationResult.php new file mode 100644 index 00000000..7d8070a7 --- /dev/null +++ b/web/app/Services/Ticket/TicketTelegramNotificationResult.php @@ -0,0 +1,10 @@ +value = json_encode($state, JSON_THROW_ON_ERROR); - $row->save(); + if (!$row->save()) { + throw new \RuntimeException('Administrator Telegram binding storage failed'); + } }); return ['code' => $code, 'expires_in' => self::BINDING_TTL]; } @@ -191,7 +194,8 @@ final class TicketTelegramNotifier null, null, true, - 'telegram.update.' . $command['update_id'], + 'telegram.' . $state['binding_generation'] + . '.update.' . $command['update_id'], 1 )); } catch (TicketReplyStateConflict $exception) { @@ -238,10 +242,9 @@ final class TicketTelegramNotifier private static function ticketReplyCommand(array $update): ?array { $message = $update['message'] ?? null; - $updateId = $update['update_id'] ?? null; + $updateId = self::positiveIntegerString($update['update_id'] ?? null); if (!is_array($message) - || (!is_int($updateId) && !is_string($updateId)) - || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $updateId) !== 1 + || $updateId === null || ($message['chat']['type'] ?? '') !== 'private' || !empty($message['from']['is_bot']) || !empty($message['via_bot']) @@ -253,15 +256,15 @@ final class TicketTelegramNotifier } $chatId = (string) ($message['chat']['id'] ?? ''); $senderId = (string) ($message['from']['id'] ?? ''); - $messageId = $message['message_id'] ?? null; - $replyMessageId = $message['reply_to_message']['message_id'] ?? null; + $messageId = self::positiveIntegerString($message['message_id'] ?? null); + $replyMessageId = self::positiveIntegerString( + $message['reply_to_message']['message_id'] ?? null + ); $text = $message['text'] ?? null; if (preg_match('/^[1-9][0-9]{0,18}$/D', $chatId) !== 1 || $chatId !== $senderId - || (!is_int($messageId) && !is_string($messageId)) - || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $messageId) !== 1 - || (!is_int($replyMessageId) && !is_string($replyMessageId)) - || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $replyMessageId) !== 1 + || $messageId === null + || $replyMessageId === null || !is_string($text) || trim($text) === '' || str_starts_with(trim($text), '/')) { @@ -274,7 +277,7 @@ final class TicketTelegramNotifier } } return [ - 'update_id' => (string) $updateId, + 'update_id' => $updateId, 'chat_id' => $chatId, 'message_id' => (int) $messageId, 'reply_to_message_id' => (int) $replyMessageId, @@ -282,6 +285,21 @@ final class TicketTelegramNotifier ]; } + private static function positiveIntegerString(mixed $value): ?string + { + if ((!is_int($value) && !is_string($value)) + || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $value) !== 1) { + return null; + } + $value = (string) $value; + $maximum = (string) PHP_INT_MAX; + if (strlen($value) > strlen($maximum) + || (strlen($value) === strlen($maximum) && strcmp($value, $maximum) > 0)) { + return null; + } + return $value; + } + private static function sendReplyAcknowledgement( string $chatId, int $replyToMessageId, @@ -303,9 +321,18 @@ final class TicketTelegramNotifier } } - public static function notify(TicketEvent $event): bool + public static function notify(TicketEvent $event): TicketTelegramNotificationResult { $ticketId = (int) $event->result->root->id; + try { + $public = TicketTelegramConfig::publicValues(); + if (!$public['enabled'] || !$public['configured']) { + return TicketTelegramNotificationResult::Skipped; + } + } catch (\Throwable $exception) { + error_log('Administrator ticket Telegram configuration check failed'); + return TicketTelegramNotificationResult::Failed; + } try { $config = TicketTelegramConfig::runtime(true); $state = self::deliveryBindingState(); @@ -313,12 +340,14 @@ final class TicketTelegramNotifier if ((!is_string($chatId) && !is_int($chatId)) || preg_match('/^[1-9][0-9]{0,18}$/D', (string) $chatId) !== 1 || !self::eligibleAdmin((int) ($state['bound_admin_id'] ?? 0))) { - return false; + return TicketTelegramNotificationResult::Skipped; } $text = self::notificationText($event); [$delivery, $ownsDispatch] = self::reserveDelivery($event, $state, $text); if (!$ownsDispatch) { - return (string) $delivery->state === 'sent'; + return (string) $delivery->state === 'sent' + ? TicketTelegramNotificationResult::Sent + : TicketTelegramNotificationResult::Failed; } try { $result = (new BotApi($config['bot_token']))->call('sendMessage', [ @@ -337,7 +366,7 @@ final class TicketTelegramNotifier if ((int) $updated !== 1) { throw new \RuntimeException('Telegram delivery finalization failed'); } - return true; + return TicketTelegramNotificationResult::Sent; } catch (\Throwable $exception) { self::markDeliveryUnknown((int) $delivery->id); throw $exception; @@ -345,7 +374,7 @@ final class TicketTelegramNotifier } catch (\Throwable $exception) { // SDK error URLs may contain bot secrets. Never log their messages. error_log('Administrator ticket Telegram delivery failed; ticket=' . $ticketId); - return false; + return TicketTelegramNotificationResult::Failed; } } @@ -359,6 +388,7 @@ final class TicketTelegramNotifier $kind = (string) $event->kind; $existing = self::deliveryForEvent($generation, $messageId, $kind); if ($existing !== null) { + self::settleStaleDispatching($existing); return [$existing, false]; } @@ -390,6 +420,25 @@ final class TicketTelegramNotifier } } + private static function settleStaleDispatching(TicketTelegramDelivery $delivery): void + { + if ((string) $delivery->state !== 'dispatching' + || (int) $delivery->updated_at > time() - 30) { + return; + } + $updated = TicketTelegramDelivery::where('id', (int) $delivery->id) + ->where('state', 'dispatching')->update([ + 'telegram_message_id' => null, + 'state' => 'unknown', + 'updated_at' => time(), + ]); + if ((int) $updated === 1) { + $delivery->telegram_message_id = null; + $delivery->state = 'unknown'; + $delivery->updated_at = time(); + } + } + private static function deliveryForEvent( string $generation, int $messageId, @@ -529,7 +578,9 @@ final class TicketTelegramNotifier } $lines[] = '后台地址:' . $adminUrl; $lines[] = ''; - $lines[] = '↩️ 直接回复本消息即可回复用户'; + $lines[] = (int) ($root->status ?? 0) === 1 + ? '↩️ 直接回复本消息即可回复用户' + : '工单已关闭,请在管理后台查看'; return mb_substr(implode("\n", $lines), 0, 4096, 'UTF-8'); } diff --git a/web/sql/ticket_telegram_replies.sql b/web/sql/ticket_telegram_replies.sql new file mode 100644 index 00000000..f23e89eb --- /dev/null +++ b/web/sql/ticket_telegram_replies.sql @@ -0,0 +1,23 @@ +-- Add durable Telegram notification-to-ticket mappings before deploying the +-- two-way administrator ticket bridge. No existing ticket or binding rows are +-- rewritten; the first post-upgrade notification assigns a binding generation. +CREATE TABLE IF NOT EXISTS `ticket_telegram_deliveries` ( + `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, + `binding_generation` char(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + `bound_admin_id` bigint(20) NOT NULL, + `chat_id` varchar(20) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + `ticket_id` bigint(20) NOT NULL, + `ticket_message_id` bigint(20) NOT NULL, + `event_kind` varchar(24) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + `telegram_message_id` bigint(20) unsigned DEFAULT NULL, + `state` varchar(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'dispatching', + `content_hash` char(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + `created_at` bigint(20) unsigned NOT NULL DEFAULT 0, + `sent_at` bigint(20) unsigned DEFAULT NULL, + `updated_at` bigint(20) unsigned NOT NULL DEFAULT 0, + PRIMARY KEY (`id`), + UNIQUE KEY `ticket_telegram_event` (`binding_generation`,`ticket_message_id`,`event_kind`), + UNIQUE KEY `ticket_telegram_message` (`binding_generation`,`chat_id`,`telegram_message_id`), + KEY `ticket_telegram_ticket` (`ticket_id`,`ticket_message_id`), + KEY `ticket_telegram_admin` (`bound_admin_id`,`created_at`,`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/web/tests/ManualAccountDeletionSqliteTest.php b/web/tests/ManualAccountDeletionSqliteTest.php index cf7a2398..a4dc8d75 100644 --- a/web/tests/ManualAccountDeletionSqliteTest.php +++ b/web/tests/ManualAccountDeletionSqliteTest.php @@ -44,6 +44,11 @@ $schema->create('ticket_attachments', static function (Blueprint $table) { $table->integer('user_id'); $table->string('storage_key'); }); +$schema->create('ticket_telegram_deliveries', static function (Blueprint $table) { + $table->increments('id'); + $table->integer('ticket_id'); + $table->integer('bound_admin_id'); +}); $schema->create('yipay_orders', static function (Blueprint $table) { $table->increments('id'); $table->integer('user_id'); @@ -156,6 +161,10 @@ Capsule::table('ticket_attachments')->insert([ ['id' => 3, 'ticket_id' => 20, 'message_id' => 20, 'user_id' => 3, 'storage_key' => 'retained-user.png'], ]); +Capsule::table('ticket_telegram_deliveries')->insert([ + ['id' => 1, 'ticket_id' => 10, 'bound_admin_id' => 2], + ['id' => 2, 'ticket_id' => 20, 'bound_admin_id' => 2], +]); Capsule::table('yipay_orders')->insert([ ['user_id' => 1, 'order_no' => 'deleted-order'], ['user_id' => 3, 'order_no' => 'retained-order'], @@ -243,6 +252,8 @@ $assert((int) User::find(3)->ref_by === 0, 'Deleted referrer was not cleared.'); $assert(Capsule::table('ticket')->pluck('id')->all() === [20], 'Ticket replies from the deleted thread were retained.'); $assert(Capsule::table('ticket_attachments')->pluck('id')->all() === [3], 'Ticket attachment deletion was not isolated.'); +$assert(Capsule::table('ticket_telegram_deliveries')->pluck('id')->all() === [2], + 'Telegram ticket delivery mapping deletion was not isolated.'); $assert(!is_file($attachmentDirectory . '/deleted-user.png') && !is_file($attachmentDirectory . '/deleted-admin-reply.png') && is_file($attachmentDirectory . '/retained-user.png'), @@ -361,6 +372,9 @@ Capsule::table('ticket_attachments')->insert([ 'id' => 7, 'ticket_id' => 70, 'message_id' => 70, 'user_id' => 7, 'storage_key' => 'rollback-user.png', ]); +Capsule::table('ticket_telegram_deliveries')->insert([ + 'id' => 7, 'ticket_id' => 70, 'bound_admin_id' => 2, +]); $rollbackAttachment = $attachmentDirectory . '/rollback-user.png'; if (file_put_contents($rollbackAttachment, 'rollback attachment') === false) { throw new RuntimeException('Could not create rollback attachment fixture.'); @@ -378,7 +392,8 @@ try { } $assert(User::find(7) !== null && Capsule::table('ticket')->where('id', 70)->exists() - && Capsule::table('ticket_attachments')->where('id', 7)->exists(), + && Capsule::table('ticket_attachments')->where('id', 7)->exists() + && Capsule::table('ticket_telegram_deliveries')->where('id', 7)->exists(), 'Database rows did not roll back after the forced account deletion failure.'); $assert(is_file($rollbackAttachment), 'Ticket attachment file was deleted before the account transaction committed.'); diff --git a/web/tests/TicketTelegramBoundaryTest.php b/web/tests/TicketTelegramBoundaryTest.php index e163224b..5b683e40 100644 --- a/web/tests/TicketTelegramBoundaryTest.php +++ b/web/tests/TicketTelegramBoundaryTest.php @@ -22,4 +22,13 @@ foreach (['enable_telegram', 'telegram_token', 'telegram_request_token', 'tgUrl' } $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'); +$notifier = file_get_contents(dirname(__DIR__) . '/app/Services/TicketTelegramNotifier.php'); +$transport = file_get_contents(dirname(__DIR__) . '/app/Services/Ticket/TicketNotificationTransportAdapter.php'); +check(str_contains($notifier, "->where('telegram_message_id', \$command['reply_to_message_id'])") + && str_contains($notifier, "'.update.' . \$command['update_id']") + && !str_contains($notifier, "preg_match('/^\\/reply"), + 'Telegram ticket replies are not restricted to durable reply-to-message mappings.'); +check(str_contains($transport, 'TicketTelegramNotificationResult::Failed') + && str_contains($transport, "throw new \\RuntimeException('Telegram ticket delivery failed')"), + 'Telegram transport still reports failed remote delivery as success.'); echo "Administrator-only Telegram command and database configuration boundaries passed.\n"; diff --git a/web/tests/TicketTelegramDeliverySchemaContractTest.php b/web/tests/TicketTelegramDeliverySchemaContractTest.php index e3ad7648..02afad3d 100644 --- a/web/tests/TicketTelegramDeliverySchemaContractTest.php +++ b/web/tests/TicketTelegramDeliverySchemaContractTest.php @@ -2,6 +2,7 @@ $root = dirname(__DIR__); $schema = file_get_contents($root . '/sql/ss.sql'); +$upgrade = file_get_contents($root . '/sql/ticket_telegram_replies.sql'); $model = file_get_contents($root . '/app/Models/TicketTelegramDelivery.php'); $deletion = file_get_contents($root . '/app/Services/UserDataDeletionService.php'); @@ -11,16 +12,24 @@ $assert = static function ($condition, string $message): void { $assert(str_contains($schema, 'CREATE TABLE `ticket_telegram_deliveries`'), 'Fresh schema is missing Telegram ticket delivery mappings.'); +$assert(str_contains($upgrade, 'CREATE TABLE IF NOT EXISTS `ticket_telegram_deliveries`'), + 'Existing test deployments lack a Telegram ticket delivery upgrade path.'); foreach (['binding_generation', 'bound_admin_id', 'chat_id', 'ticket_id', - 'ticket_message_id', 'event_kind', 'telegram_message_id', 'content_hash'] as $column) { + 'ticket_message_id', 'event_kind', 'telegram_message_id', 'state', + 'content_hash', 'created_at', 'sent_at', 'updated_at'] as $column) { $assert(str_contains($schema, '`' . $column . '`'), 'Telegram delivery schema is missing ' . $column . '.'); + $assert(str_contains($upgrade, '`' . $column . '`'), + 'Telegram delivery upgrade is missing ' . $column . '.'); } $assert(str_contains($schema, 'UNIQUE KEY `ticket_telegram_event` (`binding_generation`,`ticket_message_id`,`event_kind`)') && str_contains($schema, 'UNIQUE KEY `ticket_telegram_message` (`binding_generation`,`chat_id`,`telegram_message_id`)'), 'Telegram delivery schema lacks event idempotency or reply mapping uniqueness.'); +$assert(str_contains($upgrade, '`ticket_telegram_event`') + && str_contains($upgrade, '`ticket_telegram_message`'), + 'Telegram delivery upgrade does not preserve the fresh-schema uniqueness contract.'); $assert(str_contains($model, "protected \$table = 'ticket_telegram_deliveries'"), 'Telegram delivery model does not point at its durable table.'); $assert(str_contains($deletion, "['ticket_telegram_deliveries', 'bound_admin_id']") diff --git a/web/tests/TicketTelegramNotifierSecurityTest.php b/web/tests/TicketTelegramNotifierSecurityTest.php index 62249081..53eba430 100644 --- a/web/tests/TicketTelegramNotifierSecurityTest.php +++ b/web/tests/TicketTelegramNotifierSecurityTest.php @@ -327,6 +327,7 @@ namespace { use App\Services\TicketTelegramNotifier; use App\Services\Ticket\TicketEvent; use App\Services\Ticket\TicketNotificationDispatcher; + use App\Services\Ticket\TicketTelegramNotificationResult; use App\Services\Ticket\TicketThreadService; use App\Services\Ticket\TicketWriteResult; use App\Controllers\Admin\TelegramController; @@ -377,7 +378,11 @@ namespace { Configurations::$locks++; return $this; } - public function first() { return Configurations::$rows[$this->name] ?? null; } + public function first() + { + $row = Configurations::$rows[$this->name] ?? null; + return $row === null ? null : clone $row; + } public function firstOrFail() { return $this->first() ?? throw new RuntimeException('Missing fixture.'); } public function delete() { unset(Configurations::$rows[$this->name]); } } @@ -427,6 +432,7 @@ namespace { require dirname(__DIR__) . '/app/Services/TicketTelegramConfig.php'; require dirname(__DIR__) . '/app/Services/Ticket/TicketWriteResult.php'; require dirname(__DIR__) . '/app/Services/Ticket/TicketEvent.php'; + require dirname(__DIR__) . '/app/Services/Ticket/TicketTelegramNotificationResult.php'; require dirname(__DIR__) . '/app/Services/TicketTelegramNotifier.php'; require dirname(__DIR__) . '/app/Controllers/Admin/TelegramController.php'; require dirname(__DIR__) . '/app/Controllers/TelegramWebhookController.php'; @@ -537,6 +543,13 @@ namespace { $assert($state()['pending_hash'] === hash('sha256', $binding['code']) && !str_contains(Configurations::$rows['ticket_telegram_binding']->value, $binding['code']), 'Plain binding code is persisted.'); + $pendingState = $state(); + Configurations::$failWrites = true; + $expectRejected(fn () => TicketTelegramNotifier::createBinding(1), + 'A failed binding-code state write still returned an unusable code.'); + Configurations::$failWrites = false; + $assert($state() === $pendingState, + 'A failed binding-code state write changed the active pending code.'); foreach (['group', 'supergroup', 'channel'] as $type) { $group = $update($binding['code']); $group['message']['chat']['type'] = $type; @@ -602,7 +615,9 @@ namespace { TicketTelegramDelivery::$rows = []; TicketTelegramDelivery::$nextId = 1; $setState(['bound_admin_id' => 1, 'chat_id' => '123456']); - $assert(TicketTelegramNotifier::notify($ticketEvent()), 'Eligible administrator was not notified.'); + $assert(TicketTelegramNotifier::notify($ticketEvent()) + === TicketTelegramNotificationResult::Sent, + 'Eligible administrator was not notified.'); $alertText = BotApi::$calls[0][1]['text']; $assert(BotApi::$calls[0][1]['chat_id'] === '123456' && str_starts_with($alertText, '🆕 新工单 #42') @@ -623,18 +638,21 @@ namespace { && preg_match('/^[a-f0-9]{32}$/D', $delivery->binding_generation) === 1, 'Successful Telegram notification did not persist a reply mapping.'); $assert(TicketTelegramNotifier::notify($ticketEvent()) + === TicketTelegramNotificationResult::Sent && count(BotApi::$calls) === 1 && count(TicketTelegramDelivery::$rows) === 1, 'A repeated ticket event was sent or persisted more than once.'); BotApi::$fail = true; - $assert(!TicketTelegramNotifier::notify($ticketEvent('user_reply', 43)), + $assert(TicketTelegramNotifier::notify($ticketEvent('user_reply', 43)) + === TicketTelegramNotificationResult::Failed, 'An uncertain Telegram send was reported as successful.'); BotApi::$fail = false; $uncertain = TicketTelegramDelivery::$rows[2] ?? null; $callsAfterUnknown = count(BotApi::$calls); $assert($uncertain !== null && $uncertain->state === 'unknown' && $uncertain->telegram_message_id === null - && !TicketTelegramNotifier::notify($ticketEvent('user_reply', 43)) + && TicketTelegramNotifier::notify($ticketEvent('user_reply', 43)) + === TicketTelegramNotificationResult::Failed && count(BotApi::$calls) === $callsAfterUnknown, 'An uncertain Telegram delivery was not fenced against replay.'); @@ -653,7 +671,8 @@ namespace { && $replyCommand->actorId === 1 && $replyCommand->actorIsAdmin && $replyCommand->requiredCurrentStatus === 1 - && $replyCommand->requestKey === 'telegram.update.501' + && $replyCommand->requestKey === 'telegram.' . $delivery->binding_generation + . '.update.501' && count(TicketNotificationDispatcher::$events) === 1 && $replyReceipt[0] === 'sendMessage' && str_contains($replyReceipt[1]['text'], '已回复工单 #42'), @@ -706,22 +725,126 @@ namespace { TicketThreadService::$fail = false; $assert($replyFailureResponse->status === 503, 'A pre-commit Telegram ticket database failure was acknowledged as success.'); + + $originalBindingState = $state(); + $newGeneration = bin2hex(random_bytes(16)); + $setState([ + 'bound_admin_id' => 1, + 'chat_id' => '123456', + 'binding_generation' => $newGeneration, + ]); + $newBindingDelivery = new TicketTelegramDelivery(); + $newBindingDelivery->binding_generation = $newGeneration; + $newBindingDelivery->bound_admin_id = 1; + $newBindingDelivery->chat_id = '123456'; + $newBindingDelivery->ticket_id = 42; + $newBindingDelivery->ticket_message_id = 99; + $newBindingDelivery->event_kind = 'user_reply'; + $newBindingDelivery->telegram_message_id = 1100; + $newBindingDelivery->state = 'sent'; + $newBindingDelivery->content_hash = str_repeat('a', 64); + $newBindingDelivery->created_at = time(); + $newBindingDelivery->sent_at = time(); + $newBindingDelivery->updated_at = time(); + $newBindingDelivery->save(); + $commandsBeforeRebind = count(TicketThreadService::$commands); + $assert(TicketTelegramNotifier::handleUpdate($ticketReply(508, 'old binding', '123456', 1000)) + && count(TicketThreadService::$commands) === $commandsBeforeRebind, + 'An old binding generation still authorized its Telegram notification.'); + $assert(TicketTelegramNotifier::handleUpdate($ticketReply(501, 'new binding', '123456', 1100)), + 'A new binding could not reuse a Telegram update identifier.'); + $newBindingCommand = TicketThreadService::$commands[count(TicketThreadService::$commands) - 1] ?? null; + $assert($newBindingCommand !== null + && $newBindingCommand->requestKey === 'telegram.' . $newGeneration . '.update.501', + 'Telegram idempotency did not include the active binding generation.'); + $setState($originalBindingState); + + $commandsBeforeUnsafeReplies = count(TicketThreadService::$commands); + $unknownReply = $ticketReply(509, 'unknown notification', '123456', 999999); + $viaBotReply = $ticketReply(510); + $viaBotReply['message']['via_bot'] = ['id' => 99]; + $mediaReply = $ticketReply(511); + $mediaReply['message']['photo'] = [['file_id' => 'not-accepted']]; + $overflowReply = $ticketReply(512); + $overflowReply['update_id'] = (string) PHP_INT_MAX . '0'; + $assert(TicketTelegramNotifier::handleUpdate($unknownReply) + && !TicketTelegramNotifier::handleUpdate($viaBotReply) + && !TicketTelegramNotifier::handleUpdate($mediaReply) + && !TicketTelegramNotifier::handleUpdate($overflowReply) + && count(TicketThreadService::$commands) === $commandsBeforeUnsafeReplies, + 'Unknown, via-bot, media or overflowing Telegram updates reached the ticket workflow.'); + User::$users[1]->is_admin = 0; + $assert(!TicketTelegramNotifier::handleUpdate($ticketReply(513)), + 'A downgraded administrator replied through Telegram.'); + User::$users[1]->is_admin = 1; + + $fallbackEvent = $ticketEvent('user_reply', 44); + $fallbackEvent->result->root->userid = 999; + $fallbackEvent->result->root->instance_id = 999; + $fallbackEvent->result->message->content = str_repeat('测', 5000); + $assert(TicketTelegramNotifier::notify($fallbackEvent) + === TicketTelegramNotificationResult::Sent, + 'A missing user/instance projection suppressed the Telegram notification.'); + $fallbackText = BotApi::$calls[count(BotApi::$calls) - 1][1]['text'] ?? ''; + $assert(str_contains($fallbackText, '用户:UID 999') + && !str_contains($fallbackText, '关联实例:') + && mb_strlen($fallbackText, 'UTF-8') <= 4096, + 'Telegram notification fallback or length limit is invalid.'); + + $closedEvent = $ticketEvent('user_reply', 45); + $closedEvent->result->root->status = 0; + $assert(TicketTelegramNotifier::notify($closedEvent) + === TicketTelegramNotificationResult::Sent, + 'Closed ticket update notification was not sent.'); + $closedNotification = BotApi::$calls[count(BotApi::$calls) - 1][1]['text'] ?? ''; + $assert(str_contains($closedNotification, '工单已关闭,请在管理后台查看') + && !str_contains($closedNotification, '直接回复本消息'), + 'Closed ticket notification still advertises direct Telegram replies.'); + + $stale = new TicketTelegramDelivery(); + $stale->binding_generation = $originalBindingState['binding_generation']; + $stale->bound_admin_id = 1; + $stale->chat_id = '123456'; + $stale->ticket_id = 42; + $stale->ticket_message_id = 46; + $stale->event_kind = 'user_reply'; + $stale->telegram_message_id = null; + $stale->state = 'dispatching'; + $stale->content_hash = str_repeat('b', 64); + $stale->created_at = time() - 60; + $stale->sent_at = null; + $stale->updated_at = time() - 60; + $stale->save(); + $callsBeforeStale = count(BotApi::$calls); + $assert(TicketTelegramNotifier::notify($ticketEvent('user_reply', 46)) + === TicketTelegramNotificationResult::Failed + && $stale->state === 'unknown' + && count(BotApi::$calls) === $callsBeforeStale, + 'A stale dispatching delivery was replayed or left permanently unresolved.'); $calls = count(BotApi::$calls); foreach ([['bound_admin_id' => 1, 'chat_id' => '-100123456'], ['bound_admin_id' => 2, 'chat_id' => '123456'], ['bound_admin_id' => 1, 'chat_id' => ['unexpected']]] as $unsafe) { $setState($unsafe); - $assert(!TicketTelegramNotifier::notify($ticketEvent('user_reply')), 'Group/ordinary user/malformed recipient was notified.'); + $assert(TicketTelegramNotifier::notify($ticketEvent('user_reply')) + === TicketTelegramNotificationResult::Skipped, + 'Group/ordinary user/malformed recipient was notified.'); } $setState(['bound_admin_id' => 1, 'chat_id' => '123456']); User::$users[1]->is_admin = 0; - $assert(!TicketTelegramNotifier::notify($ticketEvent('user_reply')), 'Downgraded administrator received alerts.'); + $assert(TicketTelegramNotifier::notify($ticketEvent('user_reply')) + === TicketTelegramNotificationResult::Skipped, + 'Downgraded administrator received alerts.'); User::$users[1]->is_admin = 1; User::$users[1]->enable = 0; - $assert(!TicketTelegramNotifier::notify($ticketEvent('user_reply')), 'Disabled administrator received alerts.'); + $assert(TicketTelegramNotifier::notify($ticketEvent('user_reply')) + === TicketTelegramNotificationResult::Skipped, + 'Disabled administrator received alerts.'); User::$users[1]->enable = 1; $System_Config['super_admin'] = '2'; - $assert(!TicketTelegramNotifier::notify($ticketEvent('user_reply')), 'Removed super-admin received alerts.'); + $assert(TicketTelegramNotifier::notify($ticketEvent('user_reply')) + === TicketTelegramNotificationResult::Skipped, + 'Removed super-admin received alerts.'); $System_Config['super_admin'] = '1,2'; $assert(count(BotApi::$calls) === $calls, 'Rejected notification still invoked Telegram.');