This commit is contained in:
MeghdadFadaee committed 2026-09-05 15:54:33 +03:30
commit 8416b02b4f
54 files changed
+4604

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
<?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']));
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace App\Security;
use App\Http\HttpException;
final class RateLimiter
{
public function __construct(private readonly string $file)
{
}
/** One bounded, locked file avoids session-reset bypass and unlimited file creation. */
public function hit(string $key, int $limit, int $window): void
{
$handle = @fopen($this->file, 'c+');
if (!$handle || !flock($handle, LOCK_EX)) {
throw new HttpException('ذخیره‌سازی امن سرور در دسترس نیست.', 503);
}
try {
@chmod($this->file, 0600);
$rawState = stream_get_contents($handle);
$state = $rawState === '' ? [] : json_decode($rawState, true, 32, JSON_THROW_ON_ERROR);
if (!is_array($state)) {
throw new HttpException('ذخیره‌سازی امن سرور معتبر نیست.', 503);
}
$now = time();
foreach ($state as $entry => $bucket) {
if (($bucket['expires'] ?? 0) <= $now) {
unset($state[$entry]);
}
}
$key = hash('sha256', $key);
$bucket = $state[$key] ?? ['count' => 0, 'expires' => $now + $window];
if ($bucket['count'] >= $limit || (!isset($state[$key]) && count($state) >= 10000)) {
throw new HttpException('تعداد درخواست‌ها زیاد است؛ کمی بعد دوباره تلاش کنید.', 429);
}
$bucket['count']++;
$state[$key] = $bucket;
$json = json_encode($state, JSON_THROW_ON_ERROR);
rewind($handle);
if (!ftruncate($handle, 0) || fwrite($handle, $json) !== strlen($json) || !fflush($handle)) {
throw new HttpException('ذخیره‌سازی امن سرور در دسترس نیست.', 503);
}
} finally {
flock($handle, LOCK_UN);
fclose($handle);
}
}
}
+89
View File
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace App\Security;
use App\Http\HttpException;
final class Session
{
public function __construct(private readonly string $directory, private readonly int $lifetime)
{
}
public function start(bool $https): void
{
if (!is_dir($this->directory) || !is_writable($this->directory)) {
throw new \RuntimeException('Session storage is unavailable.');
}
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.gc_maxlifetime', (string) $this->lifetime);
session_name('app_session');
session_save_path($this->directory);
session_set_cookie_params([
'lifetime' => 0, 'path' => '/', 'secure' => $https,
'httponly' => true, 'samesite' => $https ? 'None' : 'Lax',
]);
if (!session_start()) {
throw new \RuntimeException('Could not start session.');
}
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
if (isset($_SESSION['expires']) && $_SESSION['expires'] <= time()) {
$this->logout();
}
}
public function csrf(): string
{
return $_SESSION['csrf'];
}
public function user(): array
{
if (!isset($_SESSION['user'], $_SESSION['expires']) || $this->expiresAt() <= time()) {
throw new HttpException('ابتدا از داخل ایتا وارد شوید و هویت خود را تأیید کنید.', 401);
}
return $_SESSION['user'];
}
public function launch(): array
{
return $_SESSION['launch'] ?? [];
}
public function expiresAt(): int
{
return $_SESSION['expires'] ?? 0;
}
public function isRemoteVerified(): bool
{
return $_SESSION['remote_verified'] ?? false;
}
public function markRemoteVerified(): void
{
$_SESSION['remote_verified'] = true;
}
public function login(array $user, array $launch, bool $remoteVerified): void
{
session_regenerate_id(true);
$_SESSION['user'] = $user;
$_SESSION['launch'] = $launch;
$_SESSION['expires'] = time() + $this->lifetime;
$_SESSION['remote_verified'] = $remoteVerified;
}
public function logout(): void
{
$_SESSION = ['csrf' => bin2hex(random_bytes(32))];
session_regenerate_id(true);
}
public function close(): void
{
session_write_close();
}
}