name] = $this; self::$writes++; return true; } } } namespace App\Services { final class Auth { public static $user; public static function getUser() { return self::$user; } } } namespace App\Controllers { class BaseController {} class AdminController extends BaseController {} } namespace TelegramBot\Api { final class BotApi { public static array $calls = []; public static bool $fail = false; public function __construct(private string $token) {} public function call($method, $parameters, $timeout) { self::$calls[] = [$method, $parameters, $timeout]; if (self::$fail) { throw new \RuntimeException('synthetic SDK failure with token=' . $this->token); } return true; } } } namespace { use App\Models\Configurations; use App\Models\User; use App\Services\Auth; use App\Services\TicketTelegramNotifier; use App\Controllers\Admin\TelegramController; use App\Controllers\TelegramWebhookController; use TelegramBot\Api\BotApi; final class TelegramTestConnection { public function transaction($callback) { Configurations::$transactions++; try { return $callback(); } finally { Configurations::$transactions--; } } } final class TelegramTestQuery { public function __construct(private string $name) {} public function lockForUpdate() { if (Configurations::$transactions === 0) { throw new RuntimeException('Row lock requested outside a transaction.'); } Configurations::$locks++; return $this; } public function first() { return Configurations::$rows[$this->name] ?? null; } public function firstOrFail() { return $this->first() ?? throw new RuntimeException('Missing fixture.'); } public function delete() { unset(Configurations::$rows[$this->name]); } } final class TelegramTestResponse { public int $status = 200; public array $payload = []; public function withJson($payload, $status = 200) { $result = clone $this; $result->status = $status; $result->payload = $payload; return $result; } } final class TelegramTestStream { public int $bytesRequested = 0; public function __construct(private string $body, private bool $knownSize = true) {} public function getSize() { return $this->knownSize ? strlen($this->body) : null; } public function isSeekable() { return true; } public function rewind() {} public function read($bytes) { $this->bytesRequested = $bytes; return substr($this->body, 0, $bytes); } } final class TelegramTestRequest { public function __construct(private string $secret, public TelegramTestStream $stream) {} public function getHeaderLine($name) { return $this->secret; } public function getBody() { return $this->stream; } } require dirname(__DIR__) . '/app/Services/Config.php'; require dirname(__DIR__) . '/app/Services/AdminPermission.php'; require dirname(__DIR__) . '/app/Services/TicketTelegramNotifier.php'; require dirname(__DIR__) . '/app/Controllers/Admin/TelegramController.php'; require dirname(__DIR__) . '/app/Controllers/TelegramWebhookController.php'; $assert = function ($condition, $message) { if (!$condition) { fwrite(STDERR, $message . PHP_EOL); exit(1); } }; $expectRejected = function ($callback, $message) use ($assert) { $rejected = false; try { $callback(); } catch (RuntimeException $exception) { $rejected = true; } $assert($rejected, $message); }; $state = function () { return json_decode(Configurations::$rows['ticket_telegram_binding']->value ?? '{}', true); }; $setState = function ($value) { Configurations::$rows['ticket_telegram_binding'] = new Configurations('ticket_telegram_binding', json_encode($value)); }; $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', '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)]; $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(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']) && !str_contains(Configurations::$rows['ticket_telegram_binding']->value, $binding['code']), 'Plain binding code is persisted.'); foreach (['group', 'supergroup', 'channel'] as $type) { $group = $update($binding['code']); $group['message']['chat']['type'] = $type; $assert(!TicketTelegramNotifier::handleUpdate($group), 'A non-private chat consumed the binding code.'); } $forwarded = $update($binding['code']); $forwarded['message']['forward_origin'] = ['type' => 'user']; $assert(!TicketTelegramNotifier::handleUpdate($forwarded), 'Forwarded binding command was accepted.'); $bot = $update($binding['code']); $bot['message']['from']['is_bot'] = true; $assert(!TicketTelegramNotifier::handleUpdate($bot), 'A bot consumed the binding code.'); $mismatched = $update($binding['code']); $mismatched['message']['from']['id'] = '654321'; $assert(!TicketTelegramNotifier::handleUpdate($mismatched), 'Mismatched sender/chat accepted.'); $assert(TicketTelegramNotifier::handleUpdate($update($binding['code'])), 'Valid private binding failed.'); $assert($state() === ['bound_admin_id' => 1, 'chat_id' => '123456'], 'Consumed token or recipient state is incorrect.'); $assert(!TicketTelegramNotifier::handleUpdate($update($binding['code'], '654321')) && $state()['chat_id'] === '123456', 'Replayed binding token changed the recipient.'); $assert(Configurations::$locks >= 3 && Configurations::$transactions === 0, 'Binding issuance/consumption did not use transaction row locks.'); $binding = TicketTelegramNotifier::createBinding(1); $expired = $state(); $expired['pending_expires_at'] = time() - 1; $setState($expired); $assert(!TicketTelegramNotifier::handleUpdate($update($binding['code'])), 'Expired binding token was accepted.'); $binding = TicketTelegramNotifier::createBinding(1); User::$users[1]->is_admin = 0; $assert(!TicketTelegramNotifier::handleUpdate($update($binding['code'])), 'Downgraded issuer completed a binding.'); User::$users[1]->is_admin = 1; $setState(['bound_admin_id' => 1, 'chat_id' => '123456']); $assert(TicketTelegramNotifier::notify('新工单', 42, 'Example', 'Body'), 'Eligible administrator was not notified.'); $assert(BotApi::$calls[0][1]['chat_id'] === '123456' && str_starts_with(BotApi::$calls[0][1]['text'], '新工单 #42') && !isset(BotApi::$calls[0][1]['parse_mode']), 'Alert recipient/Chinese event label/plain-text mode is wrong.'); $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('updated', 42, 'Title', 'Body'), 'Group/ordinary user/malformed recipient was notified.'); } $setState(['bound_admin_id' => 1, 'chat_id' => '123456']); User::$users[1]->is_admin = 0; $assert(!TicketTelegramNotifier::notify('updated', 42, 'Title', 'Body'), 'Downgraded administrator received alerts.'); User::$users[1]->is_admin = 1; User::$users[1]->enable = 0; $assert(!TicketTelegramNotifier::notify('updated', 42, 'Title', 'Body'), 'Disabled administrator received alerts.'); User::$users[1]->enable = 1; $System_Config['super_admin'] = '2'; $assert(!TicketTelegramNotifier::notify('updated', 42, 'Title', 'Body'), 'Removed super-admin received alerts.'); $System_Config['super_admin'] = '1,2'; $assert(count(BotApi::$calls) === $calls, 'Rejected notification still invoked Telegram.'); $controller = new TelegramController(); foreach ([User::$users[2], new User(1, 0), new User(1, 1, 0)] as $account) { Auth::$user = $account; foreach (['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); } } $webhook = new TelegramWebhookController(); $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)); $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')); $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('{}')); $assert($webhook->handle($disabled, new TelegramTestResponse(), [])->status === 403, 'Disabled bot still accepts webhooks.'); $System_Config['enable_telegram'] = true; $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]['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'; BotApi::$fail = true; $failure = ''; try { TicketTelegramNotifier::registerWebhook(); } catch (RuntimeException $exception) { $failure = $exception->getMessage(); } $assert($failure !== '' && !str_contains($failure, $System_Config['telegram_token']), 'SDK failure leaked the Telegram bot token.'); BotApi::$fail = false; $routes = file_get_contents(dirname(__DIR__) . '/config/routes.php'); foreach (['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); } $assert(str_contains($routes, '})->add(new Admin());'), 'Admin group middleware was removed.'); echo "Administrator Telegram private one-time binding, replay/expiry/downgrade and webhook boundaries passed.\n"; }