init
This commit is contained in:
54 files changed
+4604
No files matched your search
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App;
|
||||
|
||||
use App\Eitaa\Client;
|
||||
use App\Http\Controllers\DemoController;
|
||||
use App\Http\Request;
|
||||
use App\Http\Response;
|
||||
use App\Security\RateLimiter;
|
||||
use App\Security\Session;
|
||||
use function App\Support\storage_path;
|
||||
use function App\Support\view;
|
||||
|
||||
/** Composition root: dependencies are constructed once and passed explicitly. */
|
||||
final class Application
|
||||
{
|
||||
private function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly Request $request,
|
||||
private readonly Session $session,
|
||||
private readonly DemoController $controller,
|
||||
) {
|
||||
}
|
||||
|
||||
public static function boot(): self
|
||||
{
|
||||
ini_set('display_errors', '0');
|
||||
$request = Request::capture();
|
||||
Response::securityHeaders($request->isHttps());
|
||||
$config = Config::load();
|
||||
$session = new Session(storage_path('sessions'), $config->get('session_lifetime'));
|
||||
$session->start($request->isHttps());
|
||||
$controller = new DemoController(
|
||||
$config,
|
||||
$session,
|
||||
new RateLimiter(storage_path('cache/limits.json')),
|
||||
new Client($config->get('token')),
|
||||
);
|
||||
return new self($config, $request, $session, $controller);
|
||||
}
|
||||
|
||||
public function render(): void
|
||||
{
|
||||
$csrf = $this->session->csrf();
|
||||
$this->session->close();
|
||||
$publicUrl = rtrim($this->config->get('public_url'), '/');
|
||||
view('app', [
|
||||
'csrf' => $csrf,
|
||||
'shareImage' => $publicUrl === '' ? '' : $publicUrl . '/assets/brand/social.png',
|
||||
]);
|
||||
}
|
||||
|
||||
public function api(): void
|
||||
{
|
||||
try {
|
||||
$data = $this->controller->dispatch($this->request);
|
||||
} finally {
|
||||
$this->session->close();
|
||||
}
|
||||
Response::json($data);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App;
|
||||
|
||||
use function App\Support\base_path;
|
||||
use function App\Support\storage_path;
|
||||
|
||||
final class Config
|
||||
{
|
||||
private function __construct(private readonly array $values)
|
||||
{
|
||||
}
|
||||
|
||||
public static function load(): self
|
||||
{
|
||||
$values = require base_path('config/app.php');
|
||||
if (is_file(base_path('config/local.php'))) {
|
||||
$values = array_replace($values, require base_path('config/local.php'));
|
||||
}
|
||||
$values['token'] = getenv('EITAA_APP_TOKEN') ?: $values['token'];
|
||||
if ($values['token'] === '' && is_readable(storage_path('secrets/token.txt'))) {
|
||||
$values['token'] = trim(file_get_contents(storage_path('secrets/token.txt')));
|
||||
}
|
||||
foreach (['init_data_max_age', 'session_lifetime'] as $key) {
|
||||
if (!is_int($values[$key]) || $values[$key] < 1) {
|
||||
throw new \RuntimeException('Invalid duration configuration.');
|
||||
}
|
||||
}
|
||||
foreach (['allow_local_http', 'verify_on_login', 'verify_ip'] as $key) {
|
||||
if (!is_bool($values[$key])) {
|
||||
throw new \RuntimeException('Invalid boolean configuration.');
|
||||
}
|
||||
}
|
||||
if (!is_string($values['token'])) {
|
||||
throw new \RuntimeException('Invalid token configuration.');
|
||||
}
|
||||
$url = $values['public_url'];
|
||||
if (!is_string($url) || ($url !== '' && (!filter_var($url, FILTER_VALIDATE_URL)
|
||||
|| parse_url($url, PHP_URL_SCHEME) !== 'https'
|
||||
|| parse_url($url, PHP_URL_USER) !== null
|
||||
|| parse_url($url, PHP_URL_QUERY) !== null
|
||||
|| parse_url($url, PHP_URL_FRAGMENT) !== null))) {
|
||||
throw new \RuntimeException('Invalid public URL configuration.');
|
||||
}
|
||||
return new self($values);
|
||||
}
|
||||
|
||||
public function get(string $key): mixed
|
||||
{
|
||||
if (!array_key_exists($key, $this->values)) {
|
||||
throw new \InvalidArgumentException('Unknown configuration key.');
|
||||
}
|
||||
return $this->values[$key];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Eitaa;
|
||||
|
||||
use App\Http\HttpException;
|
||||
|
||||
final class Client
|
||||
{
|
||||
public function __construct(private readonly string $token)
|
||||
{
|
||||
}
|
||||
|
||||
public function verify(string $hash, ?string $ip): void
|
||||
{
|
||||
$payload = ['hash' => $hash];
|
||||
if ($ip !== null) {
|
||||
$payload['ip'] = $ip;
|
||||
}
|
||||
$this->post('verify', $payload);
|
||||
}
|
||||
|
||||
public function sendMessage(string $userId, string $text): void
|
||||
{
|
||||
$result = $this->post('sendMessage', ['chat_id' => $userId, 'text' => $text]);
|
||||
if (($result['result'] ?? null) !== 'success') {
|
||||
throw new HttpException('ارسال پیام توسط ایتایار تأیید نشد.', 502);
|
||||
}
|
||||
}
|
||||
|
||||
private function post(string $method, array $payload): array
|
||||
{
|
||||
if (!extension_loaded('curl')) {
|
||||
throw new HttpException('افزونهٔ cURL در تنظیمات PHP هاست فعال نیست.', 503);
|
||||
}
|
||||
// Only the two public methods select endpoints. Credentials stay in TLS POST bodies.
|
||||
$curl = curl_init('https://eitaayar.ir/api/app/' . $method);
|
||||
curl_setopt_array($curl, [
|
||||
CURLOPT_POST => true,
|
||||
CURLOPT_POSTFIELDS => http_build_query(['token' => $this->token] + $payload),
|
||||
CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
|
||||
CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 12,
|
||||
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
|
||||
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
||||
CURLOPT_HTTPHEADER => ['Accept: application/json', 'Content-Type: application/x-www-form-urlencoded'],
|
||||
]);
|
||||
$raw = curl_exec($curl);
|
||||
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
|
||||
if ($raw === false || $status !== 200 || strlen($raw) > 65536) {
|
||||
throw new HttpException('پاسخ معتبر از ایتایار دریافت نشد. بعداً تلاش کنید.', 502);
|
||||
}
|
||||
$data = json_decode($raw, true);
|
||||
if (!is_array($data) || ($data['ok'] ?? false) !== true) {
|
||||
throw new HttpException($method === 'verify'
|
||||
? 'اصالت تأیید نشد؛ مهلت یک دقیقهای یا محدودیت یک بار مصرف را بررسی کنید.'
|
||||
: 'ارسال انجام نشد؛ مجوز پیام و اعتبار برنامه را در ایتایار بررسی کنید.', 422);
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -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' => 'پیام به حساب ایتای شما ارسال شد.'];
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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']));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
function base_path(string $path = ''): string
|
||||
{
|
||||
return dirname(__DIR__, 2) . ($path === '' ? '' : '/' . ltrim($path, '/'));
|
||||
}
|
||||
|
||||
function storage_path(string $path = ''): string
|
||||
{
|
||||
return base_path('storage' . ($path === '' ? '' : '/' . ltrim($path, '/')));
|
||||
}
|
||||
|
||||
function e(string|int $value): string
|
||||
{
|
||||
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||
}
|
||||
|
||||
/** Render within an isolated scope so data cannot overwrite the template path. */
|
||||
function view(string $name, array $data = []): void
|
||||
{
|
||||
if (!preg_match('/^[a-zA-Z0-9_-]+$/D', $name)) {
|
||||
throw new \InvalidArgumentException('Invalid view name.');
|
||||
}
|
||||
(static function (string $__file, array $__data): void {
|
||||
extract($__data, EXTR_SKIP);
|
||||
require $__file;
|
||||
})(base_path('resources/views/' . $name . '.php'), $data);
|
||||
}
|
||||
Reference in new issue
Block a user