Files
madar/app/Security/InitDataValidator.php
T
2026-09-05 15:54:33 +03:30

61 lines
2.6 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Security;
use App\Http\HttpException;
final class InitDataValidator
{
/** Parse without PHP parse_str's key rewriting or duplicate-key overwrite. */
public static function validate(string $raw, string $token, int $maxAge, ?int $now = null): array
{
if ($raw === '' || strlen($raw) > 16384 || $token === '') {
throw new HttpException('دادهٔ ورود معتبر نیست.', 401);
}
$values = [];
foreach (explode('&', $raw) as $pair) {
if (!str_contains($pair, '=') || preg_match('/%(?![0-9a-f]{2})/i', $pair)) {
throw new HttpException('ساختار دادهٔ امضاشده معتبر نیست.', 401);
}
[$key, $value] = array_map('urldecode', explode('=', $pair, 2));
if (!preg_match('/^[a-zA-Z0-9_]+$/D', $key) || array_key_exists($key, $values)) {
throw new HttpException('کلید تکراری یا نامعتبر است.', 401);
}
$values[$key] = $value;
}
$hash = $values['hash'] ?? '';
unset($values['hash']);
if (!preg_match('/^[a-f0-9]{64}$/D', $hash)) {
throw new HttpException('امضای داده معتبر نیست.', 401);
}
ksort($values, SORT_STRING);
$pairs = [];
foreach ($values as $key => $value) {
$pairs[] = $key . '=' . $value;
}
$key = hash_hmac('sha256', $token, 'WebAppData', true);
$expected = hash_hmac('sha256', implode("\n", $pairs), $key);
if (!hash_equals($expected, $hash)) {
throw new HttpException('امضا تأیید نشد. برنامه را از ایتا باز کنید.', 401);
}
$now ??= time();
$date = $values['auth_date'] ?? '';
if (!ctype_digit($date) || (int) $date > $now + 30 || $now - (int) $date > $maxAge) {
throw new HttpException('دادهٔ ورود منقضی شده است. برنامه را دوباره از ایتا باز کنید.', 401);
}
return $values + ['hash' => $hash];
}
public static function user(array $data): array
{
$user = json_decode($data['user'] ?? '', true, 16, JSON_BIGINT_AS_STRING);
if (!is_array($user) || !isset($user['id']) ||
!preg_match('/^[1-9][0-9]{0,15}$/D', (string) $user['id'])) {
throw new HttpException('شناسهٔ کاربر در دادهٔ امضاشده وجود ندارد.', 401);
}
return array_intersect_key($user, array_flip(['id', 'first_name', 'last_name', 'language_code', 'allows_write_to_pm']));
}
}