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.
This commit is contained in:
Timofey
2026-10-27 23:21:31 +05:00
parent b0d87b80b0
commit e7770fadda
7 changed files with 405 additions and 0 deletions
+18
View File
@@ -10,6 +10,7 @@ use BushlanovDev\MaxMessengerBot\ClientApiInterface;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\PollingStartCommand;
use BushlanovDev\MaxMessengerBot\ModelFactory;
use BushlanovDev\MaxMessengerBot\UpdateDispatcher;
use BushlanovDev\MaxMessengerBot\WebAppDataValidator;
use BushlanovDev\MaxMessengerBot\WebhookHandler;
use BushlanovDev\MaxMessengerBot\LongPollingHandler;
use BushlanovDev\MaxMessengerBot\Laravel\Commands\WebhookSubscribeCommand;
@@ -151,6 +152,20 @@ class MaxBotServiceProvider extends ServiceProvider
);
});
$this->app->singleton(WebAppDataValidator::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.'
);
}
return new WebAppDataValidator($accessToken);
});
$this->app->singleton(MaxBotManager::class, function (Application $app) {
return new MaxBotManager(
$app,
@@ -165,6 +180,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(WebAppDataValidator::class, 'maxbot.webapp');
$this->app->alias(MaxBotManager::class, 'maxbot.manager');
}
@@ -201,6 +217,7 @@ class MaxBotServiceProvider extends ServiceProvider
UpdateDispatcher::class,
WebhookHandler::class,
LongPollingHandler::class,
WebAppDataValidator::class,
MaxBotManager::class,
'maxbot',
'maxbot.api',
@@ -208,6 +225,7 @@ class MaxBotServiceProvider extends ServiceProvider
'maxbot.dispatcher',
'maxbot.webhook',
'maxbot.polling',
'maxbot.webapp',
'maxbot.manager',
];
}
+30
View File
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot;
/**
* Init data of a MAX mini app (window.WebApp.initData), after its signature was checked
* by WebAppDataValidator. Field names follow the init data as MAX sends it.
*/
final readonly class WebAppData
{
/**
* @param int $authDate Unix time the data was signed.
* @param string|null $queryId Query id, when the mini app was opened from a message button.
* @param string|null $startParam The start parameter of the link (?startapp=...).
* @param array<string, mixed>|null $user The user: id, first_name, last_name, username, language_code, photo_url.
* @param array<string, mixed>|null $chat The chat the mini app was opened from: id, type.
* @param array<string, string> $fields Every signed field, values decoded.
*/
public function __construct(
public int $authDate,
public ?string $queryId,
public ?string $startParam,
public ?array $user,
public ?array $chat,
public array $fields,
) {
}
}
+135
View File
@@ -0,0 +1,135 @@
<?php
declare(strict_types=1);
namespace BushlanovDev\MaxMessengerBot;
use BushlanovDev\MaxMessengerBot\Exceptions\SecurityException;
use InvalidArgumentException;
/**
* 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 WebAppDataValidator
{
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.
*
* @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 WebAppData
* @throws SecurityException
*/
public function validate(string $initData, ?int $maxAge = 86400, ?int $now = null): WebAppData
{
$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 new WebAppData(
authDate: $authDate,
queryId: $fields['query_id'] ?? null,
startParam: $fields['start_param'] ?? null,
user: $this->decodeJson($fields['user'] ?? null),
chat: $this->decodeJson($fields['chat'] ?? null),
fields: $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);
}
/**
* @return array<string, mixed>|null
*/
private function decodeJson(?string $value): ?array
{
if ($value === null) {
return null;
}
$decoded = json_decode($value, true);
return is_array($decoded) ? $decoded : null;
}
}