Compare commits

..

6 Commits

Author SHA1 Message Date
Alex f7bd66570b tag 1.8.0 2026-10-28 13:54:42 +03:00
Alex 21b7979ecd Refactoring WebApp InitData 2026-10-28 13:52:14 +03:00
Alex a83a2a3a84 Merge pull request #48 from smotim/feat/web-app-data-validation
Add WebAppDataValidator for mini app init data
2026-10-28 11:10:24 +03:00
Alex df8d3c9dcd Merge pull request #47 from BushlanovDev/laravel-log-chanel
Add maxbot.logging.channel config (env MAXBOT_LOGGING_CHANNEL) #46
2026-10-28 08:56:00 +03:00
Timofey e7770fadda Add WebAppDataValidator for mini app init data
Checks window.WebApp.initData by the bot token as dev.max.ru/docs/webapps/validation
describes, then its age, and returns the data parsed. A repeated field is refused.
Bound in the Laravel service provider with the configured token.
2026-10-27 23:21:31 +05:00
Alex fbfd93a04c Add maxbot.logging.channel config (env MAXBOT_LOGGING_CHANNEL) 2026-10-27 21:00:47 +03:00
12 changed files with 864 additions and 42 deletions
+7
View File
@@ -174,6 +174,13 @@ $handler = $api->createLongPollingHandler(); // Обновления
$handler->handle();
```
Проверка данных мини-приложения (`window.WebApp.initData`) на сервере
```php
$data = (new InitDataValidator('YOUR_BOT_API_TOKEN'))->validate($initData); // SecurityException, если подпись не сошлась
$data->user?->id;
```
> ℹ️ С полной документацией [вы можете ознакомиться тут](./docs/README.md).
## Реализованные методы
+97
View File
@@ -46,6 +46,8 @@
- `POST /messages/{messageId}/comments` (`sendComment`) - [*Отправка комментария.*](#Отправка-комментария)
- `PUT /messages/{messageId}/comments` (`editComment`) - [*Редактирование комментария.*](#Редактирование-комментария)
- `DELETE /messages/{messageId}/comments` (`deleteComment`) - [*Удаление комментария.*](#Удаление-комментария)
- [Мини-приложения](#Мини-приложения)
- [Проверка данных мини-приложения](#Проверка-данных-мини-приложения)
- [Laravel](#Laravel)
- [Регистрация пакета](#Регистрация-пакета)
- [Настройка](#Настройка)
@@ -529,6 +531,53 @@ $result = $api->editComment(
$result = $api->deleteComment('mid.post', 'mid.comment');
```
## Мини-приложения
### Проверка данных мини-приложения
Мини-приложение передаёт на ваш сервер строку `window.WebApp.initData`. Перед тем как доверять
пользователю из неё, проверьте подпись токеном бота
([документация MAX](https://dev.max.ru/docs/webapps/validation)):
```php
use BushlanovDev\MaxMessengerBot\Exceptions\SecurityException;
use BushlanovDev\MaxMessengerBot\WebApp\InitDataValidator;
$validator = new InitDataValidator('YOUR_BOT_API_TOKEN');
try {
$data = $validator->validate($initData); // по умолчанию данные действительны сутки
// $validator->validate($initData, maxAge: 3600); — свой срок; maxAge: null — без проверки срока
} catch (SecurityException $e) {
// подпись не сошлась, поле повторяется, нет auth_date или данные устарели
}
$data->user?->id; // пользователь (InitDataUser): id, firstName, lastName, username, languageCode, photoUrl
$data->chat?->type; // чат, из которого открыто приложение (InitDataChat): id, type (ChatType)
$data->startParam; // параметр ссылки ?startapp=...
$data->queryId; // идентификатор сессии
$data->ip; // IP-адрес пользователя
$data->authDate; // время подписи, Unix time
$data->fields; // все подписанные поля как пришли
```
Исключение бросается, только если данным нельзя доверять. Если MAX изменит формат подписанных
данных — например, добавит поле или новый тип чата, — валидация не упадёт: то, что не удалось
разобрать, станет `null`, а исходные значения останутся в `$data->fields`.
Пока мини-приложение открыто, `initData` не обновляется. Проверьте данные при входе и дальше
работайте со своей сессией — или передайте больший `maxAge`.
В Laravel валидатор берёт токен из `maxbot.access_token`:
```php
public function profile(Request $request, InitDataValidator $validator)
{
$data = $validator->validate($request->header('X-Max-Init-Data', ''));
// ...
}
```
## Laravel
### Регистрация пакета
@@ -559,8 +608,56 @@ php artisan vendor:publish --provider="BushlanovDev\MaxMessengerBot\Laravel\MaxB
```env
MAXBOT_ACCESS_TOKEN=your_bot_access_token_here
MAXBOT_WEBHOOK_SECRET=your_webhook_secret_here
# Необязательные настройки
MAXBOT_LOGGING_ENABLED=true
MAXBOT_LOGGING_CHANNEL=maxbot
```
#### Переменные окружения
| Переменная | Конфиг-ключ | По умолчанию | Описание |
|---|---|---|---|
| `MAXBOT_ACCESS_TOKEN` | `access_token` | — | Токен бота из @MasterBot (**обязателен**) |
| `MAXBOT_WEBHOOK_SECRET` | `webhook_secret` | `null` | Секрет для проверки подписи webhook-запросов |
| `MAXBOT_BASE_URL` | `base_url` | `Api::API_BASE_URL` | Базовый URL Max Bot API |
| `MAXBOT_API_VERSION` | `api_version` | `null` | Версия API (напр. `v1`) |
| `MAXBOT_TIMEOUT` | `timeout` | `10` | Таймаут HTTP-запроса, сек |
| `MAXBOT_CONNECT_TIMEOUT` | `connect_timeout` | `5` | Таймаут соединения, сек |
| `MAXBOT_READ_TIMEOUT` | `read_timeout` | `10` | Таймаут чтения, сек |
| `MAXBOT_POLLING_TIMEOUT` | `polling.timeout` | `90` | Таймаут long polling `getUpdates` (0–90), сек |
| `MAXBOT_LOGGING_ENABLED` | `logging.enabled` | `false` | Включить детальное логирование запросов/ответов API |
| `MAXBOT_LOGGING_CHANNEL` | `logging.channel` | `null` | Имя канала из `config/logging.php`; `null` — дефолтный логгер приложения. Действует только при `MAXBOT_LOGGING_ENABLED=true` |
#### Логирование
При `MAXBOT_LOGGING_ENABLED=true` пакет пишет детальные логи API-запросов.
Укажите `MAXBOT_LOGGING_CHANNEL=maxbot`, чтобы направить их в отдельный канал —
определите его в своём `config/logging.php`:
```php
'channels' => [
'maxbot' => [
'driver' => 'daily',
'path' => storage_path('logs/maxbot.log'),
'level' => 'debug',
'days' => 14,
],
],
```
Уровень фильтрации задаётся в конфиге канала (`level`), а не пакетом.
Если канал с указанным именем не определён, Laravel выбросит
`InvalidArgumentException: Log [maxbot] is not defined` при первом обращении.
> **Обновление с предыдущих версий:** если у вас опубликован `config/maxbot.php`,
> добавьте ключ `'channel' => env('MAXBOT_LOGGING_CHANNEL')` в секцию `logging`
> вручную (или удалите файл и переопубликуйте конфиг командой `vendor:publish`).
> Laravel mergeConfigFrom заменяет вложенные секции опубликованного конфига
> целиком, поэтому новый ключ `channel` не появится автоматически.
> Удалено: `MAXBOT_LOGGING_LEVEL` — настройка никогда не работала; используйте `level` в конфиге канала.
### Использование
Все методы бота доступны через фасад MaxBot, например:
+1 -1
View File
@@ -53,7 +53,7 @@ class Api
{
public const string API_BASE_URL = 'https://platform-api2.max.ru';
public const string LIBRARY_VERSION = '1.7.0';
public const string LIBRARY_VERSION = '1.8.0';
public const string API_VERSION = '1.2.5';
+64 -39
View File
@@ -10,12 +10,14 @@ use BushlanovDev\MaxMessengerBot\ClientApiInterface;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\PollingStartCommand;
use BushlanovDev\MaxMessengerBot\ModelFactory;
use BushlanovDev\MaxMessengerBot\UpdateDispatcher;
use BushlanovDev\MaxMessengerBot\WebApp\InitDataValidator;
use BushlanovDev\MaxMessengerBot\WebhookHandler;
use BushlanovDev\MaxMessengerBot\LongPollingHandler;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookSubscribeCommand;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookUnsubscribeCommand;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookListCommand;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Log\LogManager;
use Illuminate\Support\ServiceProvider;
use Illuminate\Contracts\Config\Repository as Config;
use Psr\Log\LoggerInterface;
@@ -41,13 +43,7 @@ class MaxBotServiceProvider extends ServiceProvider
$this->app->singleton(ClientApiInterface::class, function (Application $app) {
/** @var Config $config */
$config = $app->make(Config::class);
$accessToken = $config->get('maxbot.access_token');
if (empty($accessToken)) {
throw new InvalidArgumentException(
'Max Bot access token is not configured. Please set MAXBOT_ACCESS_TOKEN in your .env file.'
);
}
$accessToken = $this->resolveAccessToken($app);
if (!class_exists(\GuzzleHttp\Client::class) || !class_exists(\GuzzleHttp\Psr7\HttpFactory::class)) {
throw new \LogicException(
@@ -55,9 +51,7 @@ class MaxBotServiceProvider extends ServiceProvider
);
}
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
$logger = $this->resolveLogger($app);
$guzzle = new \GuzzleHttp\Client([
'timeout' => (int)$config->get('maxbot.timeout', 10),
@@ -83,29 +77,12 @@ class MaxBotServiceProvider extends ServiceProvider
});
$this->app->singleton(ModelFactory::class, function (Application $app) {
/** @var Config $config */
$config = $app->make(Config::class);
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
return new ModelFactory($logger);
return new ModelFactory($this->resolveLogger($app));
});
$this->app->singleton(Api::class, function (Application $app) {
/** @var Config $config */
$config = $app->make(Config::class);
$accessToken = $config->get('maxbot.access_token');
if (empty($accessToken)) {
throw new InvalidArgumentException(
'Max Bot access token is not configured. Please set MAXBOT_ACCESS_TOKEN in your .env file.'
);
}
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
$accessToken = $this->resolveAccessToken($app);
$logger = $this->resolveLogger($app);
return new Api(
$accessToken,
@@ -124,9 +101,7 @@ class MaxBotServiceProvider extends ServiceProvider
$config = $app->make(Config::class);
$secret = $config->get('maxbot.webhook_secret');
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
$logger = $this->resolveLogger($app);
return new WebhookHandler(
$app->make(UpdateDispatcher::class),
@@ -137,12 +112,7 @@ class MaxBotServiceProvider extends ServiceProvider
});
$this->app->bind(LongPollingHandler::class, function (Application $app) {
/** @var Config $config */
$config = $app->make(Config::class);
$logger = $config->get('maxbot.logging.enabled', false)
? $app->make(LoggerInterface::class)
: new NullLogger();
$logger = $this->resolveLogger($app);
return new LongPollingHandler(
$app->make(Api::class),
@@ -151,6 +121,10 @@ class MaxBotServiceProvider extends ServiceProvider
);
});
$this->app->singleton(InitDataValidator::class, function (Application $app) {
return new InitDataValidator($this->resolveAccessToken($app));
});
$this->app->singleton(MaxBotManager::class, function (Application $app) {
return new MaxBotManager(
$app,
@@ -165,6 +139,7 @@ class MaxBotServiceProvider extends ServiceProvider
$this->app->alias(UpdateDispatcher::class, 'maxbot.dispatcher');
$this->app->alias(WebhookHandler::class, 'maxbot.webhook');
$this->app->alias(LongPollingHandler::class, 'maxbot.polling');
$this->app->alias(InitDataValidator::class, 'maxbot.webapp.validator');
$this->app->alias(MaxBotManager::class, 'maxbot.manager');
}
@@ -201,6 +176,7 @@ class MaxBotServiceProvider extends ServiceProvider
UpdateDispatcher::class,
WebhookHandler::class,
LongPollingHandler::class,
InitDataValidator::class,
MaxBotManager::class,
'maxbot',
'maxbot.api',
@@ -208,7 +184,56 @@ class MaxBotServiceProvider extends ServiceProvider
'maxbot.dispatcher',
'maxbot.webhook',
'maxbot.polling',
'maxbot.webapp.validator',
'maxbot.manager',
];
}
/**
* Resolve the bot access token from the package configuration.
*
* @throws InvalidArgumentException When `maxbot.access_token` is not set.
*/
private function resolveAccessToken(Application $app): string
{
/** @var Config $config */
$config = $app->make(Config::class);
$accessToken = $config->get('maxbot.access_token');
if (empty($accessToken)) {
throw new InvalidArgumentException(
'Max Bot access token is not configured. Please set MAXBOT_ACCESS_TOKEN in your .env file.'
);
}
return $accessToken;
}
/**
* Resolve the logger based on the package configuration.
*
* Returns NullLogger when logging is disabled, the configured logging
* channel when `maxbot.logging.channel` is set, or the application's
* default logger otherwise.
*/
private function resolveLogger(Application $app): LoggerInterface
{
/** @var Config $config */
$config = $app->make(Config::class);
if (!$config->get('maxbot.logging.enabled', false)) {
return new NullLogger();
}
$channel = $config->get('maxbot.logging.channel');
if (is_string($channel) && $channel !== '') {
/** @var LogManager $logManager */
$logManager = $app->make(LogManager::class);
return $logManager->channel($channel);
}
return $app->make(LoggerInterface::class);
}
}
+3 -2
View File
@@ -72,12 +72,13 @@ return [
|--------------------------------------------------------------------------
|
| Whether to enable detailed logging of API requests and responses.
| This uses Laravel's configured logger.
| When `channel` is set, logs are sent to that channel from your
| config/logging.php; otherwise the default application logger is used.
|
*/
'logging' => [
'enabled' => (bool)env('MAXBOT_LOGGING_ENABLED', false),
'level' => env('MAXBOT_LOGGING_LEVEL', 'debug'),
'channel' => env('MAXBOT_LOGGING_CHANNEL'),
],
];
// @codeCoverageIgnoreEnd
+85
View File
@@ -0,0 +1,85 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\WebApp;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
use ReflectionException;
use TypeError;
use ValueError;
/**
* Init data of a MAX mini app (window.WebApp.initData).
*
* fromArray() does not check the signature: take trusted data from InitDataValidator::validate().
*
* @see https://dev.max.ru/docs/webapps/bridge
*/
final readonly class InitData extends AbstractModel
{
/**
* @param int $authDate Unix time the data was signed.
* @param string|null $queryId Unique id of the current session.
* @param string|null $startParam The start parameter of the link (?startapp=...).
* @param string|null $ip IP address of the user.
* @param InitDataUser|null $user The user who opened the mini app.
* @param InitDataChat|null $chat The chat the mini app was opened from.
* @param array<string, string> $fields Every signed field as MAX sent it, values decoded.
*/
public function __construct(
public int $authDate,
public ?string $queryId,
public ?string $startParam,
public ?string $ip,
public ?InitDataUser $user,
public ?InitDataChat $chat,
public array $fields,
) {
}
/**
* Builds init data from its fields as MAX sends them, where user and chat are JSON. A user or
* chat that does not fit its model becomes null rather than an error, so a change in the format
* does not break validation; the raw value stays in fields.
*
* @param array<string, mixed> $data
*
* @return static
* @throws ReflectionException
*/
public static function fromArray(array $data): static
{
return parent::fromArray([
...$data,
'user' => self::nested(InitDataUser::class, $data['user'] ?? null),
'chat' => self::nested(InitDataChat::class, $data['chat'] ?? null),
'fields' => $data,
]);
}
/**
* @param class-string<InitDataUser>|class-string<InitDataChat> $class
*
* @throws ReflectionException
*/
private static function nested(string $class, mixed $value): InitDataUser|InitDataChat|null
{
if (is_string($value)) {
$value = json_decode($value, true);
}
if (!is_array($value)) {
return null;
}
try {
// Both models hold scalars only. A value MAX turned into an object is dropped: casting
// it to string would raise a warning, and Laravel turns warnings into exceptions.
return $class::fromArray(array_filter($value, is_scalar(...)));
} catch (TypeError|ValueError) {
// A required field, the id, is missing.
return null;
}
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\WebApp;
use BushlanovDev\MaxMessengerBot\Enums\ChatType;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
use ReflectionException;
/**
* The chat a MAX mini app was opened from, from its init data.
*/
final readonly class InitDataChat extends AbstractModel
{
/**
* @param int $id Chat identifier.
* @param ChatType|null $type Chat type, null when MAX sends a type this library does not know.
*/
public function __construct(
public int $id,
public ?ChatType $type,
) {
}
/**
* MAX sends the type in upper case (DIALOG) while ChatType holds it in lower case. An unknown
* type becomes null instead of an error, so a new chat type does not break validation.
*
* @param array<string, mixed> $data
*
* @return static
* @throws ReflectionException
*/
public static function fromArray(array $data): static
{
$type = $data['type'] ?? null;
$data['type'] = is_string($type) ? ChatType::tryFrom(strtolower($type)) : null;
return parent::fromArray($data);
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Models\WebApp;
use BushlanovDev\MaxMessengerBot\Models\AbstractModel;
/**
* The user who opened a MAX mini app, from its init data.
*/
final readonly class InitDataUser extends AbstractModel
{
/**
* @param int $id User identifier.
* @param string|null $firstName First name.
* @param string|null $lastName Last name.
* @param string|null $username Username.
* @param string|null $languageCode Language of the MAX app interface (RFC 5646).
* @param string|null $photoUrl URL of the profile photo.
*/
public function __construct(
public int $id,
public ?string $firstName,
public ?string $lastName,
public ?string $username,
public ?string $languageCode,
public ?string $photoUrl,
) {
}
}
+118
View File
@@ -0,0 +1,118 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\WebApp;
use BushlanovDev\MaxMessengerBot\Exceptions\SecurityException;
use BushlanovDev\MaxMessengerBot\Models\WebApp\InitData;
use InvalidArgumentException;
use ReflectionException;
/**
* Checks init data a MAX mini app sends to your server (window.WebApp.initData): the
* signature by the bot token, then the age of the data.
*
* @see https://dev.max.ru/docs/webapps/validation
*/
final readonly class InitDataValidator
{
private const string HMAC_KEY = 'WebAppData';
/**
* @param string $botToken Your bot's access token from @MasterBot.
*
* @throws InvalidArgumentException
*/
public function __construct(
private string $botToken,
) {
if ($botToken === '') {
throw new InvalidArgumentException('Bot token cannot be empty.');
}
}
/**
* Validates init data and returns it parsed. Only data that cannot be trusted is refused:
* a change in the format of the signed data does not fail validation, see InitData::fromArray().
*
* @param string $initData Raw init data, as the mini app read it from window.WebApp.initData.
* @param int|null $maxAge Seconds the data stays valid after auth_date; null skips the check.
* A mini app open for long keeps sending the same data, so a day is a fair default.
* @param int|null $now Current Unix time; for tests.
*
* @return InitData
* @throws SecurityException
* @throws ReflectionException
*/
public function validate(string $initData, ?int $maxAge = 86400, ?int $now = null): InitData
{
$fields = $this->parseFields($initData);
$hash = $fields['hash'] ?? '';
if ($hash === '') {
throw new SecurityException('Init data has no hash.');
}
unset($fields['hash']);
if (!hash_equals($this->calculateHash($fields), strtolower($hash))) {
throw new SecurityException('Init data signature verification failed.');
}
$authDate = filter_var($fields['auth_date'] ?? null, FILTER_VALIDATE_INT);
if ($authDate === false) {
throw new SecurityException('Init data has no valid auth_date.');
}
if ($maxAge !== null && ($now ?? time()) - $authDate > $maxAge) {
throw new SecurityException('Init data has expired.');
}
return InitData::fromArray($fields);
}
/**
* Splits the query string by hand: parse_str() turns `hash[]=` into an array and rewrites
* dots and spaces in keys, while the signature covers the keys as sent. A repeated key is
* refused: the signature would cover one value while a caller reading the raw string with
* another parser could take the other.
*
* @return array<string, string>
* @throws SecurityException
*/
private function parseFields(string $initData): array
{
$fields = [];
foreach (explode('&', $initData) as $pair) {
if ($pair === '') {
continue;
}
[$key, $value] = array_pad(explode('=', $pair, 2), 2, '');
$key = urldecode($key);
if (array_key_exists($key, $fields)) {
throw new SecurityException(sprintf('Init data has a repeated field "%s".', $key));
}
$fields[$key] = urldecode($value);
}
return $fields;
}
/**
* HMAC-SHA256 of the sorted `key=value` lines, keyed with HMAC-SHA256("WebAppData", bot token).
*
* @param array<string, string> $fields
*/
private function calculateHash(array $fields): string
{
ksort($fields, SORT_STRING);
$lines = [];
foreach ($fields as $key => $value) {
$lines[] = $key . '=' . $value;
}
$secretKey = hash_hmac('sha256', $this->botToken, self::HMAC_KEY, true);
return hash_hmac('sha256', implode("\n", $lines), $secretKey);
}
}
@@ -16,7 +16,9 @@ use BushlanovDev\MaxMessengerBot\Laravel\MaxBotServiceProvider;
use BushlanovDev\MaxMessengerBot\LongPollingHandler;
use BushlanovDev\MaxMessengerBot\ModelFactory;
use BushlanovDev\MaxMessengerBot\UpdateDispatcher;
use BushlanovDev\MaxMessengerBot\WebApp\InitDataValidator;
use BushlanovDev\MaxMessengerBot\WebhookHandler;
use Illuminate\Log\LogManager;
use Illuminate\Support\Facades\Artisan;
use InvalidArgumentException;
use LogicException;
@@ -40,6 +42,7 @@ use ReflectionClass;
#[UsesClass(UpdateDispatcher::class)]
#[UsesClass(MaxBotManager::class)]
#[UsesClass(WebhookHandler::class)]
#[UsesClass(InitDataValidator::class)]
#[UsesClass(ModelFactory::class)]
final class MaxBotServiceProviderTest extends TestCase
{
@@ -90,6 +93,19 @@ final class MaxBotServiceProviderTest extends TestCase
$this->app->make(Api::class);
}
#[Test]
public function itThrowsExceptionWhenAccessTokenIsMissingForInitDataValidator(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Max Bot access token is not configured. Please set MAXBOT_ACCESS_TOKEN in your .env file.'
);
$this->app['config']->set('maxbot.access_token', null);
$this->app->make(InitDataValidator::class);
}
#[Test]
#[RunInSeparateProcess]
#[PreserveGlobalState(false)]
@@ -128,6 +144,8 @@ final class MaxBotServiceProviderTest extends TestCase
'maxbot.webhook alias' => ['maxbot.webhook', WebhookHandler::class],
'LongPollingHandler::class' => [LongPollingHandler::class, LongPollingHandler::class],
'maxbot.polling alias' => ['maxbot.polling', LongPollingHandler::class],
'InitDataValidator::class' => [InitDataValidator::class, InitDataValidator::class],
'maxbot.webapp.validator alias' => ['maxbot.webapp.validator', InitDataValidator::class],
'MaxBotManager::class' => [MaxBotManager::class, MaxBotManager::class],
'maxbot.manager alias' => ['maxbot.manager', MaxBotManager::class],
];
@@ -150,6 +168,7 @@ final class MaxBotServiceProviderTest extends TestCase
'ClientApiInterface' => [ClientApiInterface::class],
'ModelFactory' => [ModelFactory::class],
'UpdateDispatcher' => [UpdateDispatcher::class],
'InitDataValidator' => [InitDataValidator::class],
'MaxBotManager' => [MaxBotManager::class],
];
}
@@ -388,6 +407,66 @@ final class MaxBotServiceProviderTest extends TestCase
$this->assertSame($mockLogger, $actualLogger);
}
#[Test]
public function clientIsConfiguredWithChannelLoggerWhenLoggingChannelIsConfigured(): void
{
$this->app['config']->set('maxbot.logging.enabled', true);
$this->app['config']->set('maxbot.logging.channel', 'maxbot');
$this->app['config']->set('logging.channels.maxbot', [
'driver' => 'single',
'path' => storage_path('logs/maxbot.log'),
'level' => 'debug',
]);
/** @var Client $client */
$client = $this->app->make(ClientApiInterface::class);
$reflection = new ReflectionClass($client);
$loggerProp = $reflection->getProperty('logger');
$actualLogger = $loggerProp->getValue($client);
$expectedLogger = $this->app->make(LogManager::class)->channel('maxbot');
$this->assertSame($expectedLogger, $actualLogger);
}
#[Test]
public function webhookHandlerIsConfiguredWithChannelLoggerWhenLoggingChannelIsConfigured(): void
{
$this->app['config']->set('maxbot.logging.enabled', true);
$this->app['config']->set('maxbot.logging.channel', 'maxbot');
$this->app['config']->set('logging.channels.maxbot', [
'driver' => 'single',
'path' => storage_path('logs/maxbot.log'),
'level' => 'debug',
]);
/** @var WebhookHandler $handler */
$handler = $this->app->make(WebhookHandler::class);
$reflection = new ReflectionClass($handler);
$loggerProp = $reflection->getProperty('logger');
$actualLogger = $loggerProp->getValue($handler);
$expectedLogger = $this->app->make(LogManager::class)->channel('maxbot');
$this->assertSame($expectedLogger, $actualLogger);
}
#[Test]
public function clientIsConfiguredWithNullLoggerWhenLoggingIsDisabledEvenWithChannel(): void
{
$this->app['config']->set('maxbot.logging.enabled', false);
$this->app['config']->set('maxbot.logging.channel', 'maxbot');
/** @var Client $client */
$client = $this->app->make(ClientApiInterface::class);
$reflection = new ReflectionClass($client);
$loggerProp = $reflection->getProperty('logger');
$actualLogger = $loggerProp->getValue($client);
$this->assertInstanceOf(NullLogger::class, $actualLogger);
}
/**
* @return array<string, array{0: string}>
*/
@@ -420,6 +499,7 @@ final class MaxBotServiceProviderTest extends TestCase
UpdateDispatcher::class,
WebhookHandler::class,
LongPollingHandler::class,
InitDataValidator::class,
MaxBotManager::class,
'maxbot',
'maxbot.api',
@@ -427,6 +507,7 @@ final class MaxBotServiceProviderTest extends TestCase
'maxbot.dispatcher',
'maxbot.webhook',
'maxbot.polling',
'maxbot.webapp.validator',
'maxbot.manager',
];
+142
View File
@@ -0,0 +1,142 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Tests\Models\WebApp;
use BushlanovDev\MaxMessengerBot\Enums\ChatType;
use BushlanovDev\MaxMessengerBot\Models\WebApp\InitData;
use BushlanovDev\MaxMessengerBot\Models\WebApp\InitDataChat;
use BushlanovDev\MaxMessengerBot\Models\WebApp\InitDataUser;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\TestCase;
#[CoversClass(InitData::class)]
#[CoversClass(InitDataUser::class)]
#[CoversClass(InitDataChat::class)]
final class InitDataTest extends TestCase
{
private const string AUTH_DATE = '1761580800';
#[Test]
public function canBeCreatedFromInitDataFields(): void
{
$fields = [
'auth_date' => self::AUTH_DATE,
'query_id' => 'f7b3a1c2',
'start_param' => 'promo_42',
'ip' => '10.0.0.1',
'user' => '{"id":400,"first_name":"Иван","last_name":"Петров","username":"ivan",'
. '"language_code":"ru","photo_url":"https://example.com/400.jpg"}',
'chat' => '{"id":500,"type":"DIALOG"}',
];
$data = InitData::fromArray($fields);
$this->assertSame(1761580800, $data->authDate);
$this->assertSame('f7b3a1c2', $data->queryId);
$this->assertSame('promo_42', $data->startParam);
$this->assertSame('10.0.0.1', $data->ip);
$this->assertEquals(
new InitDataUser(400, 'Иван', 'Петров', 'ivan', 'ru', 'https://example.com/400.jpg'),
$data->user,
);
$this->assertEquals(new InitDataChat(500, ChatType::Dialog), $data->chat);
$this->assertSame($fields, $data->fields);
}
#[Test]
public function absentFieldsAreNull(): void
{
$data = InitData::fromArray(['auth_date' => self::AUTH_DATE]);
$this->assertNull($data->queryId);
$this->assertNull($data->startParam);
$this->assertNull($data->ip);
$this->assertNull($data->user);
$this->assertNull($data->chat);
}
#[Test]
public function unknownFieldsStayOnlyInFields(): void
{
$data = InitData::fromArray([
'auth_date' => self::AUTH_DATE,
'platform' => 'ios',
'user' => '{"id":400,"first_name":"Иван","is_premium":true}',
]);
$this->assertSame('ios', $data->fields['platform']);
$this->assertEquals(new InitDataUser(400, 'Иван', null, null, null, null), $data->user);
}
#[Test]
public function userWithoutFirstNameIsKept(): void
{
$user = InitData::fromArray(['auth_date' => self::AUTH_DATE, 'user' => '{"id":400}'])->user;
$this->assertSame(400, $user?->id);
$this->assertNull($user?->firstName);
}
#[Test]
public function fieldTurnedIntoObjectBecomesNull(): void
{
$user = InitData::fromArray([
'auth_date' => self::AUTH_DATE,
'user' => '{"id":400,"first_name":"Иван","photo_url":{"small":"https://example.com/400.jpg"}}',
])->user;
$this->assertSame('Иван', $user?->firstName);
$this->assertNull($user?->photoUrl);
}
/**
* @return array<string, array{string, ChatType|null}>
*/
public static function chats(): array
{
return [
'upper case, as MAX sends it' => ['{"id":500,"type":"DIALOG"}', ChatType::Dialog],
'lower case' => ['{"id":500,"type":"channel"}', ChatType::Channel],
'unknown type' => ['{"id":500,"type":"GROUP"}', null],
'no type' => ['{"id":500}', null],
'unknown field' => ['{"id":500,"type":"CHAT","title":"Команда"}', ChatType::Chat],
];
}
#[Test]
#[DataProvider('chats')]
public function chatTypeIsMappedToEnumOrNull(string $json, ?ChatType $type): void
{
$chat = InitData::fromArray(['auth_date' => self::AUTH_DATE, 'chat' => $json])->chat;
$this->assertSame(500, $chat?->id);
$this->assertSame($type, $chat?->type);
}
/**
* @return array<string, array{string}>
*/
public static function unparsableObjects(): array
{
return [
'not JSON' => ['oops'],
'JSON scalar' => ['"oops"'],
'no id' => ['{"first_name":"Иван","type":"DIALOG"}'],
];
}
#[Test]
#[DataProvider('unparsableObjects')]
public function unparsableUserAndChatAreNull(string $json): void
{
$data = InitData::fromArray(['auth_date' => self::AUTH_DATE, 'user' => $json, 'chat' => $json]);
$this->assertNull($data->user);
$this->assertNull($data->chat);
$this->assertSame($json, $data->fields['user']);
}
}
+193
View File
@@ -0,0 +1,193 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot\Tests\WebApp;
use BushlanovDev\MaxMessengerBot\Enums\ChatType;
use BushlanovDev\MaxMessengerBot\Exceptions\SecurityException;
use BushlanovDev\MaxMessengerBot\Models\WebApp\InitData;
use BushlanovDev\MaxMessengerBot\Models\WebApp\InitDataChat;
use BushlanovDev\MaxMessengerBot\Models\WebApp\InitDataUser;
use BushlanovDev\MaxMessengerBot\WebApp\InitDataValidator;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\UsesClass;
use PHPUnit\Framework\TestCase;
#[CoversClass(InitDataValidator::class)]
#[UsesClass(InitData::class)]
#[UsesClass(InitDataUser::class)]
#[UsesClass(InitDataChat::class)]
final class InitDataValidatorTest extends TestCase
{
private const string BOT_TOKEN = '123456:test-token-not-real';
private const int AUTH_DATE = 1761580800;
/**
* Signs init data independently of the validator: HMAC-SHA256 of the sorted `key=value` lines
* with the key HMAC-SHA256("WebAppData", bot token), as https://dev.max.ru/docs/webapps/validation describes.
*
* @param array<string, string> $fields
*/
private static function sign(array $fields, string $botToken = self::BOT_TOKEN): string
{
$sorted = $fields;
ksort($sorted);
$dataCheckString = implode("\n", array_map(
static fn (string $key, string $value): string => $key . '=' . $value,
array_keys($sorted),
$sorted,
));
$secretKey = hash_hmac('sha256', $botToken, 'WebAppData', true);
return http_build_query(
$fields + ['hash' => hash_hmac('sha256', $dataCheckString, $secretKey)],
'',
'&',
PHP_QUERY_RFC3986,
);
}
/**
* @return array<string, string>
*/
private static function fields(): array
{
return [
'auth_date' => (string)self::AUTH_DATE,
'query_id' => 'f7b3a1c2',
'start_param' => 'promo_42',
'user' => '{"id":400,"first_name":"Иван","last_name":"","username":null,"language_code":"ru"}',
'chat' => '{"id":500,"type":"DIALOG"}',
'ip' => '10.0.0.1',
];
}
#[Test]
public function validDataIsParsed(): void
{
$data = (new InitDataValidator(self::BOT_TOKEN))->validate(self::sign(self::fields()), now: self::AUTH_DATE + 60);
$this->assertSame(self::AUTH_DATE, $data->authDate);
$this->assertSame('f7b3a1c2', $data->queryId);
$this->assertSame('promo_42', $data->startParam);
$this->assertSame('10.0.0.1', $data->ip);
$this->assertSame(400, $data->user?->id);
$this->assertSame('Иван', $data->user?->firstName);
$this->assertSame(500, $data->chat?->id);
$this->assertSame(ChatType::Dialog, $data->chat?->type);
$this->assertSame('10.0.0.1', $data->fields['ip']);
$this->assertArrayNotHasKey('hash', $data->fields);
}
#[Test]
public function optionalFieldsMayBeAbsent(): void
{
// A trailing `&` leaves an empty pair, which is skipped.
$data = (new InitDataValidator(self::BOT_TOKEN))->validate(
self::sign(['auth_date' => (string)self::AUTH_DATE]) . '&',
now: self::AUTH_DATE,
);
$this->assertNull($data->queryId);
$this->assertNull($data->startParam);
$this->assertNull($data->ip);
$this->assertNull($data->user);
$this->assertNull($data->chat);
}
#[Test]
public function changedFormatOfSignedDataDoesNotFailValidation(): void
{
$initData = self::sign([
'auth_date' => (string)self::AUTH_DATE,
'platform' => 'ios',
'user' => '{"first_name":"Иван"}',
'chat' => '{"id":500,"type":"GROUP"}',
]);
$data = (new InitDataValidator(self::BOT_TOKEN))->validate($initData, now: self::AUTH_DATE);
$this->assertNull($data->user);
$this->assertSame(500, $data->chat?->id);
$this->assertNull($data->chat?->type);
$this->assertSame('ios', $data->fields['platform']);
}
#[Test]
public function changedFieldIsRefused(): void
{
$initData = str_replace('promo_42', 'promo_43', self::sign(self::fields()));
$this->expectException(SecurityException::class);
$this->expectExceptionMessage('signature verification failed');
(new InitDataValidator(self::BOT_TOKEN))->validate($initData, now: self::AUTH_DATE);
}
#[Test]
public function anotherBotIsRefused(): void
{
$this->expectException(SecurityException::class);
(new InitDataValidator('999:other-bot'))->validate(self::sign(self::fields()), now: self::AUTH_DATE);
}
#[Test]
public function repeatedFieldInFrontOfValidDataIsRefused(): void
{
$forged = 'user=' . rawurlencode('{"id":1,"first_name":"Forged"}') . '&' . self::sign(self::fields());
$this->expectException(SecurityException::class);
$this->expectExceptionMessage('repeated field "user"');
(new InitDataValidator(self::BOT_TOKEN))->validate($forged, now: self::AUTH_DATE);
}
#[Test]
public function missingHashIsRefused(): void
{
$this->expectException(SecurityException::class);
$this->expectExceptionMessage('no hash');
(new InitDataValidator(self::BOT_TOKEN))->validate('auth_date=' . self::AUTH_DATE, now: self::AUTH_DATE);
}
#[Test]
public function dataIsValidForAnHourByDefault(): void
{
$validator = new InitDataValidator(self::BOT_TOKEN);
$initData = self::sign(self::fields());
$this->assertSame(self::AUTH_DATE, $validator->validate($initData, now: self::AUTH_DATE + 86400)->authDate);
$this->expectException(SecurityException::class);
$this->expectExceptionMessage('expired');
$validator->validate($initData, now: self::AUTH_DATE + 86401);
}
#[Test]
public function expiryCheckCanBeTurnedOff(): void
{
$data = (new InitDataValidator(self::BOT_TOKEN))->validate(
self::sign(self::fields()),
maxAge: null,
now: self::AUTH_DATE + 86400 * 365,
);
$this->assertSame(self::AUTH_DATE, $data->authDate);
}
#[Test]
public function signedDataWithoutAuthDateIsRefused(): void
{
$this->expectException(SecurityException::class);
$this->expectExceptionMessage('auth_date');
(new InitDataValidator(self::BOT_TOKEN))->validate(self::sign(['query_id' => 'f7b3a1c2']));
}
#[Test]
public function emptyTokenIsRejected(): void
{
$this->expectException(InvalidArgumentException::class);
new InitDataValidator('');
}
}