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

+125
View File
@@ -0,0 +1,125 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Config;
use App\Eitaa\Client;
use App\Http\HttpException;
use App\Http\Request;
use App\Security\InitDataValidator;
use App\Security\RateLimiter;
use App\Security\Session;
final class DemoController
{
public function __construct(
private readonly Config $config,
private readonly Session $session,
private readonly RateLimiter $limiter,
private readonly Client $eitaa,
) {
}
public function dispatch(Request $request): array
{
$request->requireSecurePost($this->config->get('allow_local_http'), $this->session->csrf());
$body = $request->json();
$action = $body['action'] ?? '';
if (!is_string($action)) {
throw new HttpException('عملیات نامعتبر است.');
}
$this->limiter->hit('ip:' . $request->ip(), 60, 60);
if ($action === 'logout') {
$this->session->logout();
return ['ok' => true, 'csrf' => $this->session->csrf()];
}
if ($this->config->get('token') === '') {
throw new HttpException('توکن برنامه هنوز در فضای خصوصی هاست تنظیم نشده است.', 503);
}
if ($action === 'authenticate') {
return $this->authenticate($request, $body);
}
$user = $this->session->user();
return match ($action) {
'verify' => $this->verify($request),
'contact' => $this->contact($body, $user),
'sendMessage' => $this->sendMessage($body, $user),
default => throw new HttpException('عملیات پیدا نشد.', 404),
};
}
private function authenticate(Request $request, array $body): array
{
$this->limiter->hit('login:' . $request->ip(), 20, 300);
if (!is_string($body['initData'] ?? null)) {
throw new HttpException('دادهٔ ورود وجود ندارد.', 401);
}
$data = InitDataValidator::validate(
$body['initData'], $this->config->get('token'), $this->config->get('init_data_max_age'),
);
$user = InitDataValidator::user($data);
$alreadyVerified = ($this->session->launch()['hash'] ?? '') === $data['hash']
&& $this->session->isRemoteVerified();
if ($this->config->get('verify_on_login') && !$alreadyVerified) {
$this->remoteVerify($request, $data);
}
$this->session->login($user, $data, $this->config->get('verify_on_login') || $alreadyVerified);
return [
'ok' => true,
'user' => $user,
'expires' => $this->session->expiresAt(),
'remoteVerified' => $this->session->isRemoteVerified(),
'context' => array_intersect_key($data, array_flip([
'auth_date', 'query_id', 'chat_type', 'chat_instance', 'start_param', 'device_id',
])),
];
}
private function verify(Request $request): array
{
if (!$this->session->isRemoteVerified()) {
$this->remoteVerify($request, $this->session->launch());
$this->session->markRemoteVerified();
}
return ['ok' => true, 'message' => 'اصالت ورود توسط ایتایار تأیید شد.'];
}
private function remoteVerify(Request $request, array $launch): void
{
if (time() - (int) $launch['auth_date'] > 60) {
throw new HttpException('اصالت‌سنجی فقط در دقیقهٔ اول ورود ممکن است.', 422);
}
$this->limiter->hit('verify-global', 10, 1);
$this->eitaa->verify($launch['hash'], $this->config->get('verify_ip') ? $request->ip() : null);
}
private function contact(array $body, array $user): array
{
if (!is_string($body['contactData'] ?? null)) {
throw new HttpException('دادهٔ امضاشدهٔ تماس وجود ندارد.');
}
$data = InitDataValidator::validate($body['contactData'], $this->config->get('token'), 300);
$contact = json_decode($data['contact'] ?? '', true, 16, JSON_BIGINT_AS_STRING);
if (!is_array($contact) || (string) ($contact['user_id'] ?? '') !== (string) $user['id']) {
throw new HttpException('تماس متعلق به کاربر واردشده نیست.', 401);
}
return [
'ok' => true,
'contact' => array_intersect_key($contact, array_flip(['first_name', 'last_name', 'phone_number', 'user_id'])),
];
}
private function sendMessage(array $body, array $user): array
{
$message = $body['text'] ?? null;
if (!is_string($message) || trim($message) === '' || strlen($message) > 4000) {
throw new HttpException('متن پیام لازم است و باید کمتر از ۴۰۰۰ بایت باشد.');
}
// No client-selected recipient. Quotas persist across sessions.
$this->limiter->hit('message:' . $user['id'], 5, 3600);
$this->limiter->hit('message-global', 100, 3600);
$this->eitaa->sendMessage((string) $user['id'], trim($message));
return ['ok' => true, 'message' => 'پیام به حساب ایتای شما ارسال شد.'];
}
}
+12
View File
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace App\Http;
final class HttpException extends \RuntimeException
{
public function __construct(string $message, public readonly int $status = 400)
{
parent::__construct($message);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace App\Http;
final class Request
{
public function __construct(private readonly array $server)
{
}
public static function capture(): self
{
return new self($_SERVER);
}
public function isHttps(): bool
{
return (!empty($this->server['HTTPS']) && $this->server['HTTPS'] !== 'off')
|| ($this->server['SERVER_PORT'] ?? '') == 443;
}
public function ip(): string
{
// Forwarded headers are not trusted; configure proxies at the web server.
return $this->server['REMOTE_ADDR'] ?? '';
}
public function requireSecurePost(bool $allowLocalHttp, string $csrf): void
{
if (($this->server['REQUEST_METHOD'] ?? '') !== 'POST') {
header('Allow: POST');
throw new HttpException('فقط درخواست POST پذیرفته می‌شود.', 405);
}
$loopback = in_array($this->ip(), ['127.0.0.1', '::1'], true);
if (!$this->isHttps() && !($allowLocalHttp && $loopback)) {
throw new HttpException('برای ورود امن از آدرس HTTPS استفاده کنید.', 403);
}
if (!hash_equals($csrf, $this->server['HTTP_X_CSRF_TOKEN'] ?? '')) {
throw new HttpException('نشست مرورگر معتبر نیست؛ صفحه را تازه کنید.', 403);
}
}
public function json(): array
{
if (!str_starts_with(strtolower($this->server['CONTENT_TYPE'] ?? ''), 'application/json')) {
throw new HttpException('نوع درخواست باید JSON باشد.', 415);
}
$raw = file_get_contents('php://input', false, null, 0, 20001);
if ($raw === false || strlen($raw) > 20000) {
throw new HttpException('درخواست بیش از حد بزرگ است.', 413);
}
try {
$body = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
} catch (\JsonException $error) {
throw new HttpException('ساختار JSON معتبر نیست.', 400);
}
if (!is_array($body)) {
throw new HttpException('درخواست معتبر نیست.');
}
return $body;
}
}
+53
View File
@@ -0,0 +1,53 @@
<?php
declare(strict_types=1);
namespace App\Http;
use function App\Support\view;
final class Response
{
public static function securityHeaders(bool $https): void
{
header('X-Content-Type-Options: nosniff');
header('Referrer-Policy: no-referrer');
header('Cache-Control: no-store, private');
header("Content-Security-Policy: default-src 'self'; script-src 'self' https://developer.eitaa.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'");
if ($https) {
header('Strict-Transport-Security: max-age=31536000');
}
// Native Eitaa can embed the page: no frame-blocking header.
}
public static function json(array $data, int $status = 200): void
{
http_response_code($status);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
}
public static function error(\Throwable $error, bool $json = true): void
{
$status = $error instanceof HttpException ? $error->status : 500;
$message = $error instanceof HttpException
? $error->getMessage()
: 'خطای داخلی سرور. تنظیمات و دسترسی پوشهٔ ذخیره‌سازی را بررسی کنید.';
header('Cache-Control: no-store');
if ($json) {
self::json(['ok' => false, 'error' => $message], $status);
return;
}
http_response_code($status);
header('Content-Type: text/plain; charset=utf-8');
echo $message;
}
public static function postcard(): void
{
header('Content-Type: image/svg+xml; charset=utf-8');
header('Content-Disposition: attachment; filename="madar-postcard.svg"');
header('X-Content-Type-Options: nosniff');
header("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox");
view('postcard');
}
}