commit 8416b02b4f4ca1abcf9da1c715d27f97bebb2b96 Author: MeghdadFadaee Date: Sat Sep 5 15:54:33 2026 +0330 init diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..c1c203a --- /dev/null +++ b/.editorconfig @@ -0,0 +1,12 @@ +root = true + +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = space +indent_size = 4 + +[*.{js,mjs,css}] +indent_size = 2 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c052c3b --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +.idea/ +eitaa-app-documentation/ +/token.txt +/config/local.php +/storage/secrets/* +!/storage/secrets/.gitkeep +/storage/sessions/* +!/storage/sessions/.gitkeep +/storage/cache/* +!/storage/cache/.gitkeep +/dist/ +/node_modules/ +/vendor/ diff --git a/BRANDING.md b/BRANDING.md new file mode 100644 index 0000000..f1be3b9 --- /dev/null +++ b/BRANDING.md @@ -0,0 +1,27 @@ +# Madar · مدار + +The symbol is an abstract tilted orbit, a central body and a satellite. It contains no letters or initials. The app's name is separate typography; the PHP namespace remains `App\`. + +| Color | Value | Use | +| --- | --- | --- | +| Deep green | `#163E37` | Icon and hero backgrounds | +| Satellite lime | `#D7F68A` | Celestial bodies and primary accents | +| Soft ivory | `#E8F5D6` | Orbital ring and light text | +| Cloud | `#F6F7F9` | Light interface background | + +Keep the symbol's proportions and a clear margin of at least one central-dot radius. Use `symbol.svg` on deep green and `symbol-dark.svg` on light backgrounds. Use the full icon for profiles and app listings. Avoid adding letters inside the orbit. + +## Assets + +- `public/assets/brand/icon.svg`: editable vector master. +- `public/assets/brand/icon-1024.png`: high-resolution app/profile upload. +- `public/assets/brand/icon-192.png` and `icon-512.png`: web app icons. +- `public/assets/brand/icon-maskable-512.png`: home-screen icon with safe padding. +- `public/favicon.svg`, `public/favicon.ico`: browser icons, including 16/32/48/64px ICO entries. +- `public/apple-touch-icon.png`: 180px phone bookmark icon. +- `public/assets/brand/social.png`: 1200×630 share image. +- `public/brand.html`: visual asset sheet and downloads. + +Run `php scripts/branding.php` to regenerate bitmap exports from the SVG sources. This development command needs `rsvg-convert` and ImageMagick; the deployed PHP application does not. + +The manifest supplies app identity and home-screen assets. It does not add offline support or make Eitaa-only APIs work in a standalone browser. Social crawlers generally require an absolute image URL; configure `public_url` in your private config for share metadata. diff --git a/FEATURES.md b/FEATURES.md new file mode 100644 index 0000000..0fb6c81 --- /dev/null +++ b/FEATURES.md @@ -0,0 +1,39 @@ +# Documentation coverage + +| Documented capability | Demo | +| --- | --- | +| `initData`, `initDataUnsafe`, HMAC validation, user fields, `auth_date` | Verified identity card; unsafe data never used for authentication | +| `query_id`, `chat_type`, `chat_instance`, `start_param`, `device_id` | Verified launch context displayed after server authentication | +| Optional `POST /api/app/verify` | Authenticity card and optional mandatory check on login | +| `POST /api/app/sendMessage` | Message composer, current authenticated user only | +| `version`, `platform`, `isVersionAtLeast()` | Header/version metric, inspector and version checker | +| All documented `ThemeParams` | Inspector and labeled color swatches; theme synchronization | +| `setHeaderColor`, `setBackgroundColor`, `setBottomBarColor` | Appearance card with color picker and target selector | +| `MainButton`, `SecondaryButton` properties | Live inspector | +| BottomButton `setText`, `setParams`, `show`, `hide`, `enable`, `disable` | Main/secondary button cards, text/color/position/shine inputs | +| BottomButton `showProgress`, `hideProgress`, `onClick`, `offClick` | Main/secondary button cards; stable callback references | +| `BackButton`, `SettingsButton`: `show`, `hide`, `onClick`, `offClick`, `isVisible` | Native navigation cards and inspector | +| `showAlert`, `showConfirm`, `showPopup`, `PopupParams`, `PopupButton` | Dialog card; callbacks and browser preview explicitly labeled | +| `HapticFeedback.impactOccurred` (all five styles), `notificationOccurred` (all three types), `selectionChanged` | Haptic card; selection feedback triggered only when selection changes | +| `showScanQrPopup`, `closeScanQrPopup`, `ScanQrPopupParams` | QR card; result treated as untrusted text, never opened automatically | +| `requestWriteAccess`, `requestContact` | Permissions card; signed contact validated server-side | +| `ready`, `close`, `enableClosingConfirmation`, `disableClosingConfirmation` | Lifecycle card; also calls ready at startup | +| `enableVerticalSwipes`, `disableVerticalSwipes` | Lifecycle card, Android guard | +| `expand`, `requestFullScreen`, `exitFullScreen`, `lockOrientation`, `unlockOrientation` | Viewport card; compatible with current SDK capitalization | +| `isExpanded`, `isActive`, `isFullscreen`, `isOrientationLocked`, `isClosingConfirmationEnabled`, `isVerticalSwipesEnabled` | Live state inspector | +| `viewportHeight`, `viewportStableHeight`, `safeAreaInset`, `contentSafeAreaInset`, header/background/bottom colors | Live state inspector; layout respects safe area CSS variables | +| `addToHomeScreen`, `checkHomeScreenStatus` | Home screen card | +| `openLink`, `OpenLinkOptions.try_instant_view`, `try_browser`, `openEitaaLink` | Link card with URL and option controls | +| `downloadFile`, `DownloadFileParams` | Download card with HTTPS URL, filename and bundled SVG postcard | +| `Accelerometer.start/stop`, x/y/z, `isStarted`, `refresh_rate` | Accelerometer card with live values and motion visualization | +| `Gyroscope.start/stop`, x/y/z, `isStarted`, `refresh_rate` | Gyroscope card with live values and motion visualization | +| `DeviceOrientation.start/stop`, alpha/beta/gamma, `absolute`, `isStarted`, `refresh_rate`, `need_absolute` | Orientation card; absolute mode option and live readout | +| `onEvent`, `offEvent` | Event tools and event console; stable handlers, explicit subscribe/unsubscribe | +| `themeChanged`, `viewportChanged`, `activated`, `deactivated`, `safeAreaChanged`, `contentSafeAreaChanged` | Event console + refreshed inspector/theme | +| `mainButtonClicked`, `backButtonClicked`, `settingsButtonClicked` | Event console + native control callbacks; secondary button click also observed | +| `popupClosed`, `qrTextReceived`, `scanQrPopupClosed`, `writeAccessRequested`, `contactRequested` | Event console; sensitive payloads redacted | +| `fullscreenChanged`, `fullscreenFailed`, `homeScreenAdded`, `homeScreenChecked` | Event console | + +Sensors stop when the page is hidden or unloaded. Android-only methods and SDK 1.3/1.4 additions are guarded. SDK dispatch is reported as a request, not a fabricated successful native operation; callbacks and events report outcomes. + +The overview features six cards; all 22 cards are accessible through the sidebar or search. Categories preserve control state when hidden. Browser preview never fabricates authentication, message delivery, sensor measurements, QR scans or native permission approval. diff --git a/README.md b/README.md new file mode 100644 index 0000000..86938de --- /dev/null +++ b/README.md @@ -0,0 +1,115 @@ +# مدار · Madar + +A Persian, RTL feature playground for Eitaa apps and mini apps. PHP 8.2+, vanilla JavaScript and CSS; no database, frontend build, cron job or persistent application server required on the host. + +## Project structure + +```text +bootstrap/ + autoload.php PSR-4-compatible autoloader and helper loading + app.php Application startup +config/ + app.php Committed, non-secret defaults + local.example.php Example local overrides + local.php Optional private overrides (ignored) +public/ The ONLY web document root + index.php Page entry point + api.php JSON API entry point + sample.php Postcard download entry point + assets/ Browser JavaScript, CSS and font +resources/views/ Page and postcard templates +app/ + Application.php Constructs and connects dependencies + Config.php Loads and validates configuration + Eitaa/Client.php Outbound EitaaYar HTTPS calls + Http/ + Controllers/DemoController.php + Request.php HTTP, TLS, CSRF and JSON validation + Response.php Headers, JSON and safe error responses + HttpException.php Intentional client-facing errors + Security/ + InitDataValidator.php Signature, freshness and identity validation + RateLimiter.php Locked, persistent request quotas + Session.php Session lifecycle and authenticated identity + Support/helpers.php base_path(), storage_path(), view(), e() +storage/ + secrets/token.txt App token (ignored, private) + sessions/ PHP session files (ignored) + cache/ Rate-limit state (ignored) +scripts/package.php Credential-free deployment archive +tests/ Security, HTTP and browser checks +composer.json PHP requirements, PSR-4 metadata and scripts +``` + +Classes use the `App\` namespace, strict types and explicit constructor dependencies. The application owns dependency construction; controllers return data, responses handle HTTP output, and templates handle presentation. Request globals are confined to the HTTP request adapter and session state to the session class. Loading the autoloader for CLI tests does not start a session or send headers. + +Composer is optional. The included autoloader keeps cPanel deployment self-contained. `composer.json` declares the same PSR-4 mapping for editors and tools; `composer test`, `composer serve` and `composer package` are conveniences for the PHP commands below. + +## cPanel deployment + +1. Choose **64-bit PHP 8.2 or later** in MultiPHP Manager, with `curl`, `json`, `hash`, `openssl` and `session` enabled. +2. Enable a valid SSL certificate through SSL/TLS Status / AutoSSL. +3. Upload the project to a directory such as `/home/CPANEL_USER/app/`. In **Domains**, set the domain's document root to **`/home/CPANEL_USER/app/public`**. If your provider restricts document-root changes for the main domain, ask them to configure it or use an addon domain/subdomain with that document root. +4. Place the token in `/home/CPANEL_USER/app/storage/secrets/token.txt`, without quotes. Set the file to **0600** and `storage/secrets`, `storage/sessions` and `storage/cache` to **0700**. PHP must run as the owning cPanel account and be able to write to sessions and cache. Do not use 0777. +5. If needed, copy `config/local.example.php` to `config/local.php`. Use 0600 for a local config containing secrets. Keep `allow_local_http` **false** on the host. Configuration precedence is defaults → local overrides; the token prefers `EITAA_APP_TOKEN`, then the configured token, then `storage/secrets/token.txt`. +6. Open the final HTTPS URL directly, for example `https://example.com/index.php`, and register that exact URL in EitaaYar. The supplied documentation requires no redirect in the launch URL. +7. Open the app from Eitaa. Authentication runs automatically. Test permissions, then intentionally send yourself one message. + +No `.htaccess` files or rewrite rules are needed: endpoints are real PHP files. The web server must serve **only `public/`**, use `index.php` as its directory index and have directory listings disabled in its configuration. Never expose the repository root, `app/`, `config/`, `storage/`, or the deployment ZIP. Do not merge the entire project into an existing `public_html` web root. + +Build the package with: + +```sh +php scripts/package.php +``` + +`dist/madar-cpanel.zip` preserves the project layout, including `public/`. Extract into the project directory and configure its public document root as above. The archive includes only application code, templates, assets, non-secret configuration and empty storage placeholders. It excludes tokens, local overrides, runtime data, tests and local documentation sources. Transfer the token separately to the private storage location. + +## Security + +- Token storage stays outside the web root and is ignored by Git. Tokens never appear in HTML, JS, API URLs or the deployment archive. +- PHP validates raw launch data using HMAC-SHA256 and constant-time comparison. Duplicate or ambiguous keys, expired launches and dates too far in the future are rejected. Default launch lifetime: five minutes, with 30 seconds of clock tolerance. +- Sessions use strict mode, ID regeneration, HTTP-only cookies and an absolute one-hour expiry. HTTPS cookies use `Secure; SameSite=None` for embedding. API requests require a session-bound CSRF header. Native Eitaa is preferable when a browser blocks third-party cookies. +- Message recipients come exclusively from the verified session user. The Eitaa service enforces write permission. Limits are five send attempts per user per hour and 100 per installation per hour; failed attempts also count. Locked file storage enforces quotas across sessions. +- Signed contacts require a fresh signature and a `contact.user_id` matching the session user. Contact details appear only in that page, not persistent application logs. +- Outbound calls use fixed HTTPS endpoints, TLS verification, POST bodies, timeouts and no redirects. Raw upstream errors, credentials, paths and exception traces are not sent to the browser. +- Optional remote authenticity checking is available in the demo or through `verify_on_login`. It is single-use and must run within 60 seconds of launch; success is cached for that launch in the session. Local HMAC validation alone permits reuse of stolen valid launch data within its short lifetime. Enable mandatory verification if single-use login is required. +- IP checking uses `REMOTE_ADDR`; forwarding headers are not trusted. Configure proxy/CDN handling and HTTPS detection at the web server, or disable optional `verify_ip` if appropriate. +- Apps running under the same cPanel account may read each other's private files. Separate hosting accounts provide stronger isolation. Rotate the token if it was previously publicly accessible. + +## Development and verification + +```sh +php -S 127.0.0.1:8080 -t public +php tests/security.php +php tests/http.php +node --check public/assets/app.js +``` + +Visit `http://127.0.0.1:8080` for browser preview. Production TLS enforcement can stay enabled: preview works, while authenticated APIs reject HTTP. For deliberate loopback API development, set `allow_local_http` to true in the ignored local config. + +HTTP tests create a temporary isolated installation with a fake token and explicit loopback HTTP permission. They never load your real token or contact Eitaa. They require permission to bind a local port. + +Optional browser checks require Playwright and Chromium, with the preview server running: + +```sh +PLAYWRIGHT_MODULE=/path/to/playwright/index.mjs node tests/browser.mjs +``` + +Override `CHROMIUM_PATH` or `APP_URL` if necessary. Tests cover browser preview, responsive layouts and a simulated Eitaa bridge; they do not prove native device support. + +## Brand assets + +The abstract orbit identity includes SVG originals, PNG app icons up to 1024px, multi-size ICO/SVG favicons, an Apple touch icon, a maskable home-screen icon and a 1200×630 share image. Open `brand.html` for previews and downloads; [BRANDING.md](BRANDING.md) documents colors and exports. The icon has no letters or initials. + +Set `public_url` in `config/local.php` to the deployed HTTPS base URL (including any subdirectory) to enable absolute social-preview metadata. Icons and the manifest work without this setting. `php scripts/branding.php` regenerates the exports on a development machine with librsvg and ImageMagick; cPanel only needs the prebuilt assets. + +## Feature coverage + +The app provides 22 experiment cards, light/dark themes, live sensor visualizations, search and an in-memory event console. [FEATURES.md](FEATURES.md) maps documented features to their demos. Browser dialog previews are explicitly labeled; authentication, messages, sensors and native permissions are never fabricated. + +The official SDK is loaded directly from `https://developer.eitaa.com/eitaa-web-app.js`, before application scripts. Fullscreen dispatch supports both documented `FullScreen` and current `Fullscreen` spelling. Contact callbacks support either a signed string or the current event object's `response` string. + +Commented documentation placeholders for cloud storage, biometrics, location, device/secure storage, stories and emoji statuses are not presented as implemented APIs. Message credit purchases, balances and application management belong in EitaaYar. + +After deployment, verify on real Eitaa Android and desktop clients: login, native buttons, contact/permissions, authenticity within a minute, one intentional message, sensors, fullscreen/safe areas, QR and downloads. diff --git a/app/Application.php b/app/Application.php new file mode 100644 index 0000000..b5cc480 --- /dev/null +++ b/app/Application.php @@ -0,0 +1,63 @@ +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); + } +} diff --git a/app/Config.php b/app/Config.php new file mode 100644 index 0000000..9bf97ce --- /dev/null +++ b/app/Config.php @@ -0,0 +1,56 @@ +values)) { + throw new \InvalidArgumentException('Unknown configuration key.'); + } + return $this->values[$key]; + } +} diff --git a/app/Eitaa/Client.php b/app/Eitaa/Client.php new file mode 100644 index 0000000..6057d1b --- /dev/null +++ b/app/Eitaa/Client.php @@ -0,0 +1,60 @@ + $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; + } +} diff --git a/app/Http/Controllers/DemoController.php b/app/Http/Controllers/DemoController.php new file mode 100644 index 0000000..b9a8e63 --- /dev/null +++ b/app/Http/Controllers/DemoController.php @@ -0,0 +1,125 @@ +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' => 'پیام به حساب ایتای شما ارسال شد.']; + } +} diff --git a/app/Http/HttpException.php b/app/Http/HttpException.php new file mode 100644 index 0000000..c6702ba --- /dev/null +++ b/app/Http/HttpException.php @@ -0,0 +1,12 @@ +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; + } +} diff --git a/app/Http/Response.php b/app/Http/Response.php new file mode 100644 index 0000000..88f1247 --- /dev/null +++ b/app/Http/Response.php @@ -0,0 +1,53 @@ +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'); + } +} diff --git a/app/Security/InitDataValidator.php b/app/Security/InitDataValidator.php new file mode 100644 index 0000000..1abc838 --- /dev/null +++ b/app/Security/InitDataValidator.php @@ -0,0 +1,60 @@ + 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'])); + } + +} diff --git a/app/Security/RateLimiter.php b/app/Security/RateLimiter.php new file mode 100644 index 0000000..c9bea71 --- /dev/null +++ b/app/Security/RateLimiter.php @@ -0,0 +1,51 @@ +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); + } + } +} diff --git a/app/Security/Session.php b/app/Security/Session.php new file mode 100644 index 0000000..d4e0640 --- /dev/null +++ b/app/Security/Session.php @@ -0,0 +1,89 @@ +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(); + } +} diff --git a/app/Support/helpers.php b/app/Support/helpers.php new file mode 100644 index 0000000..93092d3 --- /dev/null +++ b/app/Support/helpers.php @@ -0,0 +1,31 @@ + '', + 'token' => '', + 'init_data_max_age' => 300, + 'session_lifetime' => 3600, + 'allow_local_http' => false, + 'verify_on_login' => false, + 'verify_ip' => true, +]; diff --git a/config/local.example.php b/config/local.example.php new file mode 100644 index 0000000..4b1a74f --- /dev/null +++ b/config/local.example.php @@ -0,0 +1,11 @@ + '', + // Prefer EITAA_APP_TOKEN or storage/secrets/token.txt for the token. + // Enable only for loopback development, never on your public host. + 'allow_local_http' => false, + // Optional single-use authenticity check, within 60 seconds of launch. + 'verify_on_login' => false, +]; diff --git a/public/api.php b/public/api.php new file mode 100644 index 0000000..0fc3eda --- /dev/null +++ b/public/api.php @@ -0,0 +1,11 @@ +api(); +} catch (Throwable $error) { + Response::error($error); +} diff --git a/public/apple-touch-icon.png b/public/apple-touch-icon.png new file mode 100644 index 0000000..e9c9e7d Binary files /dev/null and b/public/apple-touch-icon.png differ diff --git a/public/assets/Vazirmatn-Regular.ttf b/public/assets/Vazirmatn-Regular.ttf new file mode 100644 index 0000000..64e4a81 Binary files /dev/null and b/public/assets/Vazirmatn-Regular.ttf differ diff --git a/public/assets/app.css b/public/assets/app.css new file mode 100644 index 0000000..a7410b8 --- /dev/null +++ b/public/assets/app.css @@ -0,0 +1,1441 @@ +@font-face { + font-family: Vazir; + src: url("Vazirmatn-Regular.ttf") format("truetype"); + font-display: swap; +} +:root { + --bg: #f6f7f9; + --panel: #fff; + --text: #233832; + --muted: #84908e; + --line: #e8eeeb; + --accent: #28725c; + --soft: #edf5f0; + --lime: #d7f68a; + --shadow: 0 5px 20px #223c3104; + color-scheme: light; +} +* { + box-sizing: border-box; +} +body { + margin: 0; + background: var(--bg); + color: var(--text); + font: + 14px/1.85 Vazir, + Tahoma, + sans-serif; +} +button, +input, +select, +textarea { + font: inherit; +} +button, +a, +input, +select, +textarea { + -webkit-tap-highlight-color: transparent; +} +button, +a { + touch-action: manipulation; +} +button { + cursor: pointer; +} +button:disabled { + cursor: not-allowed; + opacity: 0.45; +} +button { + transition: + background 0.18s, + transform 0.18s; +} +button:not(:disabled):active { + transform: translateY(1px); +} +button:focus-visible, +a:focus-visible, +input:focus-visible, +select:focus-visible, +textarea:focus-visible { + outline: 3px solid #78af85; + outline-offset: 3px; +} +a { + color: inherit; + text-decoration: none; +} +button { + color: inherit; +} +p, +h1, +h2, +h3 { + margin: 0; +} +button { + border: 0; +} +code, +kbd, +pre { + font-family: ui-monospace, SFMono-Regular, Consolas, monospace; +} +code { + font-size: 11px; + direction: ltr; + unicode-bidi: embed; +} +button, +select, +input { + min-height: 40px; +} +[hidden] { + display: none !important; +} +.sidebar { + position: fixed; + inset: 0 0 0 auto; + width: 242px; + background: var(--panel); + border-left: 1px solid var(--line); + display: flex; + flex-direction: column; + padding: 35px 24px 20px; + z-index: 10; +} +.brand { + display: flex; + gap: 13px; + align-items: center; + font-size: 30px; + font-weight: bold; + line-height: 1.35; +} +.brand small { + display: block; + font-size: 10px; + font-weight: normal; + color: var(--muted); + margin-top: 5px; +} +.brand-mark { + background: #173e36; + color: #dbf3ba; + border-radius: 16px; + width: 47px; + height: 49px; + display: grid; + place-items: center; + position: relative; + font-size: 37px; +} +.nav-caption { + font-size: 10px; + letter-spacing: 0.3px; + color: var(--muted); + margin: 40px 12px 14px; +} +.nav-item { + width: 100%; + display: flex; + gap: 12px; + align-items: center; + text-align: right; + background: none; + color: #798580; + border-radius: 9px; + margin-bottom: 5px; + padding: 10px 12px; + font-size: 12px; + min-height: 43px; +} +.nav-item .nav-icon { + font: 21px/1 sans-serif; + width: 22px; + text-align: center; +} +.nav-item .nav-number { + margin-right: auto; + font: 10px monospace; + opacity: 0.6; +} +.nav-item:hover { + background: var(--bg); +} +.nav-item.active { + color: #28664d; + background: #edf4ee; + font-weight: bold; +} +.sidebar-note { + margin-top: auto; + padding: 22px 16px 16px; + border-radius: 13px; + background: var(--bg); + overflow: hidden; + position: relative; +} +.sidebar-note strong { + font-size: 15px; + line-height: 1.9; + display: block; +} +.sidebar-note p { + font-size: 11px; + color: var(--muted); + margin: 8px 0 15px; +} +.sidebar-note a { + font-size: 11px; + display: flex; + justify-content: space-between; + border-top: 1px solid var(--line); + padding-top: 11px; +} +.mini-orbit { + position: absolute; + font-size: 74px; + color: #c8d8ce; + left: -8px; + top: -15px; + transform: rotate(20deg); +} +.sidebar-footer { + display: flex; + gap: 6px; + align-items: center; + font-size: 9px; + color: var(--muted); + margin-top: 24px; +} +.sidebar-footer > span:last-child { + margin-right: auto; +} +.status-dot, +.live-dot { + background: #85b18d; + border-radius: 50%; + width: 6px; + height: 6px; + display: inline-block; + flex-shrink: 0; +} +.page { + margin-right: 242px; +} +.topbar { + height: 88px; + border-bottom: 1px solid var(--line); + padding: 0 42px; + display: flex; + justify-content: space-between; + align-items: center; + background: var(--panel); +} +.breadcrumb { + font-size: 11px; + color: var(--muted); + display: flex; + gap: 17px; +} +.breadcrumb strong { + font-weight: normal; + color: var(--text); +} +.top-actions { + display: flex; + gap: 18px; + align-items: center; +} +.pill { + font-size: 10px; + padding: 4px 12px; + border: 1px solid var(--line); + border-radius: 30px; + display: flex; + gap: 7px; + align-items: center; +} +.pill i { + width: 5px; + height: 5px; + border-radius: 50%; + background: #daa56b; +} +.pill.connected i { + background: #64a780; +} +.icon-button { + background: none; + font-size: 22px; + width: 35px; +} +.avatar { + display: grid; + place-items: center; + width: 34px; + height: 34px; + border: 3px solid var(--panel); + outline: 1px solid var(--line); + border-radius: 50%; + background: #edebe4; + font-size: 11px; + color: #766c58; +} +main { + max-width: 1490px; + margin: auto; + padding: 32px 42px 0; + padding-top: calc(32px + var(--tg-content-safe-area-inset-top, 0px)); + padding-bottom: var(--tg-content-safe-area-inset-bottom, 0px); +} +.hero { + min-height: 335px; + background: #163e37; + border-radius: 18px; + display: flex; + position: relative; + overflow: hidden; + color: #fff; + padding: 35px 38px; +} +.hero-copy { + z-index: 2; + width: 55%; +} +.eyebrow { + font-size: 10px; + letter-spacing: 0.25px; + display: flex; + align-items: center; + gap: 8px; +} +.eyebrow > span { + height: 5px; + width: 5px; + background: var(--lime); + border-radius: 50%; +} +.hero .eyebrow { + color: #b9cec3; +} +.hero h1 { + font-size: 37px; + line-height: 1.55; + margin: 12px 0 9px; + font-weight: normal; + letter-spacing: -1px; +} +.hero p { + font-size: 11px; + line-height: 2; + color: #b5c9c1; +} +.hero-actions { + display: flex; + gap: 21px; + align-items: center; + margin-top: 22px; +} +.primary { + padding: 10px 18px; + border-radius: 8px; + background: var(--accent); + color: #fff; + font-size: 12px; + display: inline-flex; + gap: 24px; + align-items: center; + justify-content: center; +} +.lime { + background: var(--lime); + color: #253e30; +} +.hero-link { + background: none; + color: #e5efe9; + font-size: 11px; + display: flex; + gap: 15px; + align-items: center; +} +.hero-foot { + font-size: 9px; + color: #98b5a8; + display: flex; + gap: 10px; + align-items: center; + margin-top: 22px; +} +.tiny-stack { + display: flex; + direction: ltr; +} +.tiny-stack b { + display: grid; + place-items: center; + width: 21px; + height: 21px; + background: #35604e; + color: #bdd4bc; + border-radius: 50%; + border: 2px solid #163e37; + margin-right: -6px; + font: 12px sans-serif; +} +.orbital { + position: absolute; + left: 0; + top: 0; + bottom: 0; + width: 49%; + background: radial-gradient(ellipse at 42% 48%, #7da27625, transparent 67%); +} +.orbit { + position: absolute; + top: 50%; + left: 48%; + border: 1px solid #bad0aa24; + border-radius: 50%; + transform: translate(-50%, -50%) rotate(-32deg); +} +.orbit-one { + width: 295px; + height: 230px; +} +.orbit-two { + width: 390px; + height: 300px; +} +.orbit-three { + width: 495px; + height: 385px; + border-style: dashed; + border-color: #bad0aa16; +} +.planet { + position: absolute; + top: 49%; + left: 47%; + transform: translate(-50%, -50%) rotate(-12deg); + width: 137px; + height: 137px; + border: 1px solid #c5eca663; + border-radius: 36px; + background: linear-gradient(145deg, #91b985, #426c50 65%, #2b553e); + box-shadow: + inset 0 0 32px #b3dea44a, + 15px 22px 35px #081f3370; + display: grid; + place-items: center; +} +.satellite { + position: absolute; + width: 48px; + height: 48px; + border: 1px solid #a1bf8f55; + border-radius: 14px; + display: grid; + place-items: center; + font: 25px sans-serif; + background: #2e5547; + box-shadow: 3px 7px 13px #0b2b3540; + color: #cfedaf; +} +.sat-a { + left: 70%; + top: 20%; + transform: rotate(14deg); +} +.sat-b { + left: 23%; + top: 71%; + transform: rotate(-14deg); + background: #bed58d; + color: #274839; +} +.sat-c { + left: 11%; + top: 21%; + transform: rotate(-10deg); +} +.orbit-label { + position: absolute; + padding: 5px 12px; + background: #284d42c9; + border: 1px solid #96b38740; + border-radius: 20px; + font-size: 9px; + color: #bdd2b7; + white-space: nowrap; +} +.label-a { + left: 51%; + top: 77%; + transform: rotate(-5deg); +} +.label-a i { + display: inline-block; + width: 5px; + height: 5px; + background: #c9e896; + border-radius: 50%; + margin-left: 5px; +} +.label-b { + top: 13%; + left: 29%; + font: 10px monospace; + transform: rotate(7deg); + direction: ltr; +} +.label-b span { + color: #d4eea3; + margin-left: 7px; +} +.star { + position: absolute; + color: #b8d894; + font: 23px serif; +} +.star-a { + left: 81%; + top: 57%; +} +.star-b { + left: 24%; + top: 49%; + font-size: 13px; +} +.star-c { + left: 59%; + top: 9%; +} +.metrics { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 15px; + margin: 22px 0; +} +.metrics > div { + background: var(--panel); + border: 1px solid var(--line); + border-radius: 11px; + display: flex; + align-items: center; + gap: 13px; + padding: 17px 16px; + box-shadow: var(--shadow); +} +.metric-icon { + width: 39px; + height: 40px; + border-radius: 11px; + display: grid; + place-items: center; + font: 22px sans-serif; +} +.mint { + background: #edf6ed; + color: #649970; +} +.violet { + background: #f2eef9; + color: #9880b4; +} +.peach { + background: #fcf0e7; + color: #cfab89; +} +.blue { + background: #ebf2fa; + color: #809fb7; +} +.metrics strong { + display: block; + font-size: 18px; + font-weight: normal; + line-height: 1.5; +} +.metrics small { + display: block; + color: var(--muted); + font-size: 9px; +} +.metric-tail { + color: var(--muted); + font-size: 9px; + margin-right: auto; +} +.metrics .live-dot { + margin-right: auto; +} +.notice { + display: flex; + align-items: center; + gap: 12px; + border: 1px solid #e0e9da; + background: #f0f5e9; + color: #718361; + border-radius: 9px; + padding: 11px 15px; + font-size: 10px; + margin-bottom: 29px; +} +.notice > span { + font: 17px sans-serif; +} +.notice button { + background: none; + margin-right: auto; + font: 19px sans-serif; + min-height: 24px; +} +.section-heading { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + margin: 28px 0 18px; +} +.muted { + color: var(--muted); +} +.section-heading h2 { + font-size: 21px; + font-weight: normal; + margin: 3px 0; +} +.section-heading h2 span { + font-size: 17px; + color: #aab7a1; + margin-right: 6px; +} +.section-heading p { + font-size: 11px; + color: var(--muted); +} +.search { + display: flex; + align-items: center; + border: 1px solid var(--line); + background: var(--panel); + padding: 0 12px; + border-radius: 9px; + width: 260px; + gap: 8px; +} +.search > span { + font: 25px sans-serif; + color: var(--muted); +} +.search input { + background: none; + border: 0; + outline: 0; + color: var(--text); + font-size: 10px; + min-width: 0; + width: 100%; + height: 41px; +} +.search kbd { + border: 1px solid var(--line); + border-radius: 4px; + color: var(--muted); + padding: 0 5px; + font-size: 10px; +} +.filter-row { + display: flex; + justify-content: space-between; + align-items: center; + margin: 0 0 18px; + gap: 15px; +} +#filters { + display: flex; + gap: 7px; + flex-wrap: wrap; +} +.filter { + font-size: 10px; + border: 1px solid var(--line); + background: var(--panel); + padding: 3px 13px; + border-radius: 7px; + min-height: 31px; +} +.filter.active { + background: #294d3e; + color: #fff; + border-color: #294d3e; +} +#result-count { + font-size: 10px; + color: var(--muted); + white-space: nowrap; +} +.card-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 18px; + align-items: start; +} +.feature-card { + min-width: 0; + background: var(--panel); + border: 1px solid var(--line); + border-radius: 13px; + padding: 20px; + box-shadow: var(--shadow); + height: 100%; + display: flex; + flex-direction: column; +} +.card-top { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 16px; +} +.card-icon { + width: 40px; + height: 40px; + display: grid; + place-items: center; + border-radius: 12px; + font: 23px sans-serif; +} +.tag { + font: + 9px Vazir, + sans-serif; + color: var(--muted); + background: var(--bg); + border: 1px solid var(--line); + padding: 2px 8px; + border-radius: 20px; +} +.tag.ready { + color: #64856b; + background: #f0f6ed; + border-color: #e3edde; +} +.feature-card h3 { + font-size: 15px; + font-weight: normal; + margin-bottom: 5px; +} +.card-description { + color: var(--muted); + font-size: 10px; + line-height: 2; + min-height: 40px; +} +.method-line { + margin: 10px 0 14px; + direction: ltr; + color: #8c9a93; + overflow-wrap: anywhere; + font: 10px/1.6 monospace; +} +.controls { + margin-top: auto; + display: flex; + flex-direction: column; + gap: 9px; +} +.button-row { + display: flex; + gap: 6px; + flex-wrap: wrap; +} +.lab-button { + background: var(--soft); + border: 1px solid transparent; + border-radius: 7px; + padding: 7px 10px; + color: var(--accent); + font-size: 10px; + min-height: 34px; + flex: 1; + white-space: nowrap; +} +.lab-button:hover { + border-color: #bacbbd; +} +.lab-button.main { + background: #2e5b45; + color: #fff; +} +.lab-button.danger { + color: #bc6e63; + background: #faf0ed; +} +.control-label { + display: flex; + flex-direction: column; + gap: 4px; + font-size: 10px; + color: var(--muted); +} +.control-label input, +.control-label select, +.control-label textarea { + width: 100%; + color: var(--text); + background: var(--bg); + border: 1px solid var(--line); + border-radius: 7px; + padding: 7px 9px; + font-size: 11px; + min-height: 35px; +} +.control-label textarea { + resize: vertical; + min-height: 75px; + line-height: 1.8; +} +.control-label input[type="color"] { + height: 35px; + padding: 3px; + width: 100%; +} +.control-label:has(input[type="checkbox"]) { + flex-direction: row; + align-items: center; + gap: 8px; +} +.control-label input[type="checkbox"] { + width: 15px; + min-height: 15px; + accent-color: var(--accent); +} +.field-row { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 9px; +} +.result { + font: + 10px/1.8 Vazir, + sans-serif; + border: 1px dashed var(--line); + background: var(--bg); + color: var(--muted); + padding: 9px 11px; + border-radius: 7px; + overflow-wrap: anywhere; + white-space: pre-wrap; + max-height: 230px; + overflow: auto; +} +.result.error { + color: #b46257; + border-color: #e5b6aa; +} +.result.success { + color: var(--accent); +} +.result:empty { + display: none; +} +.details { + margin: 8px 0; + font-size: 10px; +} +.details summary { + cursor: pointer; + color: var(--accent); +} +pre.inspector { + direction: ltr; + text-align: left; + font-size: 10px; + white-space: pre-wrap; + overflow-wrap: anywhere; + max-height: 300px; + overflow: auto; + background: var(--bg); + border: 1px solid var(--line); + padding: 12px; + border-radius: 8px; +} +.theme-swatches { + display: flex; + gap: 6px; + flex-wrap: wrap; + margin: 10px 0; +} +.swatch { + width: 25px; + height: 25px; + border-radius: 7px; + border: 1px solid var(--line); +} +.sensor-stage { + height: 110px; + border: 1px solid var(--line); + border-radius: 9px; + position: relative; + overflow: hidden; + background: + linear-gradient(var(--line) 1px, transparent 1px), + linear-gradient(90deg, var(--line) 1px, transparent 1px), var(--bg); + background-size: 22px 22px; +} +.sensor-stage:before, +.sensor-stage:after { + content: ""; + position: absolute; + border: 1px solid #a8bbab; + border-radius: 50%; + height: 70px; + width: 70px; + top: 19px; + left: calc(50% - 35px); +} +.sensor-stage:after { + height: 36px; + width: 36px; + top: 36px; + left: calc(50% - 18px); +} +.sensor-ball { + position: absolute; + height: 17px; + width: 17px; + top: calc(50% - 8px); + left: calc(50% - 8px); + background: #86b685; + border: 3px solid #cbe0bd; + border-radius: 50%; + box-shadow: 0 0 15px #8eb572; + z-index: 1; + transition: transform 0.15s; +} +.sensor-readout { + font: 10px monospace; + direction: ltr; + text-align: center; + color: var(--muted); + padding-top: 6px; +} +.helper { + font-size: 9px; + color: var(--muted); +} +.empty { + text-align: center; + padding: 60px; + color: var(--muted); +} +.event-panel { + margin-top: 30px; + border: 1px solid var(--line); + background: var(--panel); + border-radius: 12px; + overflow: hidden; +} +.event-heading { + display: flex; + justify-content: space-between; + align-items: center; + padding: 16px 20px; + border-bottom: 1px solid var(--line); + gap: 10px; +} +.event-heading > div { + display: flex; + align-items: center; + gap: 10px; +} +.event-heading h2 { + font-size: 13px; + font-weight: normal; +} +.event-heading .muted { + font-size: 9px; +} +.text-button { + background: none; + color: var(--muted); + font-size: 10px; + min-height: 28px; +} +.event-log { + max-height: 220px; + overflow: auto; + min-height: 96px; + padding: 9px 20px; + direction: ltr; + text-align: left; +} +.log-empty { + direction: rtl; + text-align: center; + color: var(--muted); + font-size: 10px; + padding: 26px 0; +} +.log-row { + display: grid; + grid-template-columns: 64px 1fr; + gap: 10px; + padding: 6px 0; + border-bottom: 1px solid var(--line); + font: 10px/1.8 monospace; + overflow-wrap: anywhere; +} +.log-row time { + color: #9aaba1; +} +.log-row strong { + color: #649476; + font-weight: normal; +} +.log-row.error strong { + color: #bd7767; +} +.log-row p { + color: var(--muted); + white-space: pre-wrap; +} +.event-footer { + padding: 9px 20px; + background: var(--bg); + display: flex; + justify-content: space-between; + gap: 10px; + color: var(--muted); + font-size: 9px; +} +.footer { + padding: 26px 0; + display: flex; + justify-content: space-between; + color: var(--muted); + font-size: 10px; +} +.footer b { + font-size: 13px; + color: #6c7e70; + font-weight: normal; +} +.footer-spark { + font-size: 20px; + vertical-align: middle; + color: #afbe9c; + margin-right: 7px; +} +.toast { + position: fixed; + bottom: 25px; + left: 50%; + transform: translateX(-50%); + background: #213e33; + color: #f2f9ed; + box-shadow: 0 6px 24px #14332833; + padding: 12px 22px; + border-radius: 11px; + z-index: 100; + max-width: calc(100vw - 30px); + font-size: 12px; +} +.skip { + position: fixed; + top: -100px; + background: var(--lime); + color: #173e36; + padding: 12px; + z-index: 1000; +} +.skip:focus { + top: 5px; +} +dialog { + background: var(--panel); + color: var(--text); + border: 1px solid var(--line); + border-radius: 18px; + max-width: 400px; + width: calc(100vw - 40px); + padding: 28px; + text-align: center; +} +dialog::backdrop { + background: #112d296b; + backdrop-filter: blur(4px); +} +.dialog-icon { + font-size: 32px; + color: #72976a; + background: var(--soft); + width: 62px; + height: 62px; + border-radius: 18px; + margin: 0 auto 16px; +} +dialog h2 { + font-size: 19px; +} +dialog p { + font-size: 12px; + color: var(--muted); + margin: 12px 0 24px; +} +#dialog-buttons { + display: flex; + gap: 10px; +} +#dialog-buttons button { + flex: 1; +} +.noscript { + position: fixed; + bottom: 0; + left: 0; + right: 0; + background: #fee1ab; + padding: 20px; + text-align: center; + z-index: 500; +} +body.dark { + --bg: #17231f; + --panel: #202e27; + --text: #e0e9de; + --muted: #a0afa5; + --line: #35473b; + --accent: #bddda4; + --soft: #314735; + color-scheme: dark; +} +body.dark .notice { + background: #2b3c27; + border-color: #425537; + color: #c0d0ac; +} +body.dark .nav-item.active { + background: #364b36; + color: #dbebcc; +} +body.dark .tag.ready { + background: #31472f; + color: #c3d4b1; + border-color: #475b3c; +} +body.dark .filter.active { + background: #cce4af; + color: #233820; +} +body.dark .card-icon, +body.dark .metric-icon { + filter: brightness(0.8); +} +@media (min-width: 1600px) { + .hero { + min-height: 360px; + } + .hero h1 { + font-size: 43px; + } + .sidebar { + width: 265px; + } + .page { + margin-right: 265px; + } + .card-grid { + gap: 22px; + } +} +@media (max-width: 1200px) { + .sidebar { + width: 210px; + padding-inline: 18px; + } + .page { + margin-right: 210px; + } + main { + padding-inline: 25px; + } + .topbar { + padding-inline: 25px; + } + .metrics { + gap: 10px; + } + .metrics > div { + padding: 13px 10px; + gap: 8px; + } + .metric-tail { + display: none; + } + .card-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .hero { + padding: 30px; + } + .hero h1 { + font-size: 33px; + } + .orbital { + transform: scale(0.9); + transform-origin: left center; + width: 48%; + } +} +@media (max-height: 860px) and (min-width: 901px) { + .sidebar-note { + padding: 12px; + } + .sidebar-note p { + display: none; + } + .nav-caption { + margin-top: 27px; + } + .nav-item { + padding-block: 7px; + min-height: 37px; + } + .sidebar-footer { + margin-top: 15px; + } +} +@media (max-width: 900px) { + .sidebar { + position: static; + width: auto; + padding: 16px 20px 10px; + border-left: 0; + border-bottom: 1px solid var(--line); + } + .brand { + font-size: 24px; + } + .brand-mark { + width: 38px; + height: 40px; + font-size: 30px; + } + .brand small { + font-size: 9px; + } + .nav-caption, + .sidebar-note, + .sidebar-footer { + display: none; + } + #navigation { + display: flex; + overflow-x: auto; + gap: 5px; + margin-top: 18px; + padding-bottom: 4px; + } + .nav-item { + width: auto; + flex-shrink: 0; + margin: 0; + font-size: 10px; + gap: 6px; + padding: 8px 12px; + min-height: 35px; + } + .nav-item .nav-icon { + font-size: 17px; + width: 18px; + } + .nav-number { + display: none; + } + .page { + margin: 0; + } + .topbar { + height: 62px; + } + .metrics strong { + font-size: 16px; + } + .hero { + min-height: 320px; + } +} +@media (max-width: 600px) { + main { + padding: 20px 16px 0; + } + .topbar { + padding: 0 18px; + } + .top-actions { + gap: 8px; + } + .breadcrumb { + gap: 9px; + font-size: 10px; + } + .avatar { + display: none; + } + .pill { + font-size: 9px; + padding: 3px 8px; + } + .hero { + min-height: 344px; + padding: 25px 22px; + } + .hero-copy { + width: 76%; + } + .hero h1 { + font-size: 30px; + } + .hero .eyebrow { + font-size: 8px; + } + .hero p { + font-size: 10px; + } + .orbital { + left: -74px; + width: 210px; + opacity: 0.5; + transform: scale(0.7); + transform-origin: left center; + } + .hero-actions { + gap: 13px; + } + .primary { + padding: 9px 13px; + font-size: 11px; + gap: 12px; + } + .hero-link { + font-size: 10px; + } + .hero-foot { + font-size: 8px; + } + .metrics { + grid-template-columns: 1fr 1fr; + margin: 16px 0; + gap: 9px; + } + .metrics > div { + padding: 12px; + } + .notice { + margin-bottom: 20px; + align-items: start; + font-size: 9px; + } + .section-heading { + flex-direction: column; + align-items: stretch; + gap: 16px; + } + .section-heading h2 { + font-size: 21px; + } + .search { + width: 100%; + } + .filter-row { + align-items: start; + } + .card-grid { + grid-template-columns: 1fr; + gap: 14px; + } + .feature-card { + padding: 20px; + } + .card-description { + min-height: 0; + font-size: 11px; + } + .lab-button { + font-size: 11px; + min-height: 40px; + } + .method-line { + margin-bottom: 16px; + } + .event-heading { + padding: 12px; + align-items: start; + } + .event-heading .muted { + display: none; + } + .event-heading > div { + gap: 6px; + } + .event-heading h2 { + font-size: 12px; + } + .event-footer { + padding: 8px 12px; + font-size: 8px; + } + .event-footer code { + font-size: 9px; + } + .event-log { + padding: 8px 12px; + } + .footer { + font-size: 8px; + } + .footer-spark { + font-size: 16px; + } +} +body { + padding-top: var(--tg-safe-area-inset-top, env(safe-area-inset-top, 0px)); + padding-bottom: var( + --tg-safe-area-inset-bottom, + env(safe-area-inset-bottom, 0px) + ); + padding-left: calc( + var(--tg-safe-area-inset-left, env(safe-area-inset-left, 0px)) + + var(--tg-content-safe-area-inset-left, 0px) + ); + padding-right: calc( + var(--tg-safe-area-inset-right, env(safe-area-inset-right, 0px)) + + var(--tg-content-safe-area-inset-right, 0px) + ); +} +@media (prefers-reduced-motion: reduce) { + *, + *:before, + *:after { + transition: none !important; + scroll-behavior: auto !important; + } +} + +/* The identity is a vector orbit, independent of font rendering. */ +.brand-mark { background: transparent; border-radius: 0; object-fit: contain; } +.planet { background: #163e37; } +.planet img { width: 100%; height: 100%; object-fit: contain; } diff --git a/public/assets/app.js b/public/assets/app.js new file mode 100644 index 0000000..4d1add8 --- /dev/null +++ b/public/assets/app.js @@ -0,0 +1,1441 @@ +"use strict"; +(() => { + const $ = (id) => document.getElementById(id); + const sdk = window.Eitaa?.WebApp; + const native = Boolean( + sdk?.initData && sdk.platform && sdk.platform !== "unknown", + ); + const android = native && /android/i.test(sdk.platform); + let csrf = document.querySelector('meta[name="csrf-token"]').content; + let authenticated = false, + authExpiry = 0, + currentCategory = "overview", + currentFilter = "all"; + let listening = false, + eventTotal = 0, + toastTimer, + themeOverride = false; + const actions = new Map(), + subscriptions = [], + clickHandlers = new Map(); + const fa = new Intl.NumberFormat("fa-IR"); + const categories = [ + ["overview", "نمای کلی", "◫"], + ["all", "همهٔ آزمایش‌ها", "⌘"], + ["interface", "رابط و ظاهر", "◈"], + ["interaction", "تعامل با کاربر", "☷"], + ["device", "دستگاه و حسگرها", "◎"], + ["connection", "لینک و فایل", "↗"], + ["security", "هویت و پیام", "◇"], + ["inspector", "داده‌ها و رویدادها", "≋"], + ]; + const esc = (s) => + String(s).replace( + /[&<>"']/g, + (c) => + ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + })[c], + ); + const compact = (value) => JSON.stringify(value, null, 2); + function toast(message) { + $("toast").textContent = message; + $("toast").hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => ($("toast").hidden = true), 4200); + } + function safeLog(value) { + return ( + JSON.stringify( + value, + (key, item) => + /hash|token|initData|contact|phone|response|user|device_id|query_id|chat_instance/i.test( + key, + ) + ? "[private]" + : item, + 2, + )?.slice(0, 1400) ?? "" + ); + } + function log(name, value = "", error = false) { + const container = $("event-log"); + container.querySelector(".log-empty")?.remove(); + const row = document.createElement("div"); + row.className = `log-row${error ? " error" : ""}`; + const time = document.createElement("time"); + time.textContent = new Date().toLocaleTimeString("en-GB"); + const content = document.createElement("div"), + title = document.createElement("strong"), + detail = document.createElement("p"); + title.textContent = name; + detail.textContent = + typeof value === "string" ? value.slice(0, 1000) : safeLog(value); + content.append(title, detail); + row.append(time, content); + container.prepend(row); + while (container.children.length > 80) container.lastElementChild.remove(); + $("event-count").textContent = fa.format(++eventTotal); + } + function result(id, message, error = false) { + const target = $(`${id}-result`); + if (target) { + target.textContent = + typeof message === "string" ? message : compact(message); + target.className = `result ${error ? "error" : "success"}`; + } + } + function fail(id, error) { + const message = error.message || "اجرای آزمایش ممکن نشد."; + result(id, message, true); + log(id, message, true); + toast(message); + } + function resolve(path) { + // Documentation spells FullScreen differently from the current official SDK. + if (path === "requestFullScreen") + path = sdk?.requestFullscreen ? "requestFullscreen" : path; + if (path === "exitFullScreen") + path = sdk?.exitFullscreen ? "exitFullscreen" : path; + const parts = path.split("."); + const name = parts.pop(); + return { owner: parts.reduce((obj, key) => obj?.[key], sdk), name }; + } + function availability(path, version = "1.0", androidOnly = false) { + if (!native) return "این قابلیت را از داخل ایتا اجرا کنید."; + if (androidOnly && !android) + return "طبق مستندات، این قابلیت فقط در ایتای اندروید در دسترس است."; + if (sdk.isVersionAtLeast && !sdk.isVersionAtLeast(version)) + return `این قابلیت به SDK نسخهٔ ${version} یا جدیدتر نیاز دارد.`; + const { owner, name } = resolve(path); + if (typeof owner?.[name] !== "function") + return "این نسخهٔ ایتا از این متد پشتیبانی نمی‌کند."; + return ""; + } + function call(id, path, args = [], version = "1.0", androidOnly = false) { + const reason = availability(path, version, androidOnly); + if (reason) throw new Error(reason); + const { owner, name } = resolve(path); + result( + id, + "درخواست به ایتا فرستاده شد؛ نتیجهٔ بومی یا رویداد را بررسی کنید.", + ); + log(path, "درخواست ارسال شد"); + const response = owner[name](...args); + refreshInspector(); + return response; + } + async function api(action, payload = {}) { + const response = await fetch("api.php", { + method: "POST", + credentials: "same-origin", + cache: "no-store", + headers: { "Content-Type": "application/json", "X-CSRF-Token": csrf }, + body: JSON.stringify({ action, ...payload }), + signal: AbortSignal.timeout(18000), + }); + let data; + try { + data = await response.json(); + } catch { + throw new Error( + "پاسخ سرور قابل خواندن نیست. تنظیمات PHP هاست را بررسی کنید.", + ); + } + if (!response.ok || !data.ok) { + if (response.status === 401) { + authenticated = false; + updateAuth(); + } + throw new Error(data.error || "درخواست انجام نشد."); + } + return data; + } + function needAuth() { + if (!authenticated || Date.now() >= authExpiry) + throw new Error("ابتدا در بخش «هویت و پیام» ورود امن را انجام دهید."); + } + const value = (id) => $(id).value; + const checkbox = (id) => $(id).checked; + function field(id, label, initial = "", type = "text", extra = "") { + return ``; + } + function select(id, label, options) { + return ``; + } + function check(id, label, checked = false) { + return ``; + } + function button(id, label, handler, style = "") { + const key = `${id}-${actions.size}`; + actions.set(key, { id, handler }); + return ``; + } + const row = (...items) => `
${items.join("")}
`; + const simple = ( + id, + label, + path, + args = [], + version = "1.0", + androidOnly = false, + style = "", + ) => + button(id, label, () => call(id, path, args, version, androidOnly), style); + const cards = []; + function card( + id, + category, + title, + description, + method, + icon, + color, + body, + options = {}, + ) { + cards.push({ + id, + category, + title, + description, + method, + icon, + color, + body, + ...options, + }); + } + + card( + "appearance", + "interface", + "رنگِ حال و هوای شما", + "ظاهر برنامه را با رنگ دلخواه بسازید؛ یا آن را با تم ایتا هماهنگ کنید.", + "themeParams · setHeaderColor()", + "◈", + "violet", + `
${field("accent-color", "رنگ انتخابی", "#476c51", "color")}${select( + "color-target", + "محل اعمال", + [ + ["setHeaderColor", "سربرگ"], + ["setBackgroundColor", "پس‌زمینه"], + ["setBottomBarColor", "نوار پایین · 1.3"], + ], + )}
` + + row( + button( + "appearance", + "اعمال رنگ", + () => + call( + "appearance", + value("color-target"), + [value("accent-color")], + value("color-target") === "setBottomBarColor" ? "1.3" : "1.0", + ), + "main", + ), + button("appearance", "همگام‌سازی تم", () => { + themeOverride = false; + syncTheme(); + result( + "appearance", + native ? "تم ایتا اعمال شد." : "تم پیش‌فرض مرورگر اعمال شد.", + ); + }), + ) + + '
', + { featured: true }, + ); + + function nativeButton(kind, title) { + const id = kind === "MainButton" ? "main-button" : "secondary-button"; + const version = kind === "SecondaryButton" ? "1.3" : "1.0"; + const handler = () => { + result(id, "دکمهٔ بومی لمس شد."); + log(`${kind}.click`); + toast("کلیک دکمهٔ بومی دریافت شد."); + }; + clickHandlers.set(kind, handler); + card( + id, + "interface", + title, + "متن، رنگ، وضعیت و نشانگر بارگذاری دکمهٔ بومی را تغییر دهید.", + `${kind}.setParams()`, + kind === "MainButton" ? "▰" : "▱", + "mint", + field( + `${id}-text`, + "متن دکمه", + kind === "MainButton" ? "بزن بریم!" : "کمی بعد", + "text", + 'maxlength="64"', + ) + + `
${field(`${id}-color`, "رنگ دکمه", kind === "MainButton" ? "#397057" : "#e5eedc", "color")}${field(`${id}-text-color`, "رنگ متن", kind === "MainButton" ? "#ffffff" : "#254a39", "color")}
` + + (kind === "SecondaryButton" + ? select(`${id}-position`, "جایگاه نسبت به دکمهٔ اصلی", [ + "left", + "right", + "top", + "bottom", + ]) + check(`${id}-shine`, "افکت درخشش") + : "") + + row( + button( + id, + "نمایش و اعمال", + () => { + call( + id, + `${kind}.setParams`, + [ + { + text: value(`${id}-text`), + color: value(`${id}-color`), + text_color: value(`${id}-text-color`), + is_visible: true, + is_active: true, + ...(kind === "SecondaryButton" + ? { + position: value(`${id}-position`), + has_shine_effect: checkbox(`${id}-shine`), + } + : {}), + }, + ], + version, + ); + }, + "main", + ), + simple(id, "پنهان", `${kind}.hide`, [], version), + ) + + row( + simple(id, "فعال", `${kind}.enable`, [], version), + simple(id, "غیرفعال", `${kind}.disable`, [], version), + simple(id, "بارگذاری", `${kind}.showProgress`, [false], version), + simple(id, "پایان بارگذاری", `${kind}.hideProgress`, [], version), + ) + + `
متن و رویداد کلیک${row( + button(id, "فقط تغییر متن", () => + call(id, `${kind}.setText`, [value(`${id}-text`)], version), + ), + button(id, "اتصال کلیک", () => { + call(id, `${kind}.offClick`, [handler], version); + call(id, `${kind}.onClick`, [handler], version); + }), + simple(id, "قطع کلیک", `${kind}.offClick`, [handler], version), + )}
`, + { featured: kind === "MainButton", version }, + ); + } + nativeButton("MainButton", "یک دکمه، کلی امکان"); + nativeButton("SecondaryButton", "دکمهٔ دوم، انتخاب بیشتر"); + + for (const [kind, title, icon] of [ + ["BackButton", "یک قدم به عقب", "↪"], + ["SettingsButton", "تنظیمات در دسترس", "⚙"], + ]) { + const id = kind === "BackButton" ? "back-button" : "settings-button"; + const handler = () => { + navigate(kind === "BackButton" ? "overview" : "interface"); + log(`${kind}.click`); + toast(title); + }; + clickHandlers.set(kind, handler); + card( + id, + "interface", + title, + "دکمهٔ بومی را نمایش دهید و اتصال یا حذف رویداد کلیک را آزمایش کنید.", + `${kind}.show() · onClick()`, + icon, + "blue", + row( + simple(id, "نمایش", `${kind}.show`, [], "1.0", false, "main"), + simple(id, "پنهان", `${kind}.hide`), + ) + + row( + button(id, "اتصال کلیک", () => { + call(id, `${kind}.offClick`, [handler]); + call(id, `${kind}.onClick`, [handler]); + }), + simple(id, "قطع کلیک", `${kind}.offClick`, [handler]), + ), + ); + } + + function previewDialog(title, message, options) { + return new Promise((resolve) => { + const dialog = $("demo-dialog"); + $("dialog-title").textContent = title; + $("dialog-message").textContent = message; + $("dialog-buttons").replaceChildren(); + for (const [id, label] of options) { + const b = document.createElement("button"); + b.className = "primary"; + b.value = id; + b.textContent = label; + $("dialog-buttons").append(b); + } + dialog.returnValue = ""; + dialog.addEventListener("close", () => resolve(dialog.returnValue), { + once: true, + }); + dialog.showModal(); + }); + } + card( + "dialogs", + "interaction", + "گفت‌وگو از همین‌جا شروع می‌شود", + "هشدار، تأیید یا یک پنجرهٔ سه‌انتخابی؛ واکنش بومی ایتا را ببینید.", + "showPopup() · showAlert() · showConfirm()", + "▤", + "peach", + field( + "popup-message", + "پیام پنجره", + "آماده‌ای یک ایدهٔ تازه را امتحان کنی؟", + "text", + 'maxlength="256"', + ) + + row( + ...[ + ["alert", "هشدار"], + ["confirm", "تأیید"], + ["popup", "سه انتخاب"], + ].map(([type, label]) => + button("dialogs", label, async () => { + const message = value("popup-message").trim(); + if (!message) throw new Error("متن پیام را وارد کنید."); + const done = (response) => { + result("dialogs", { + mode: native ? "Eitaa" : "پیش‌نمایش مرورگر", + response: response ?? "closed", + }); + log(`dialog.${type}`, response ?? "closed"); + }; + if (!native) { + done( + await previewDialog( + "پیش‌نمایش مرورگر", + message, + type === "alert" + ? [["ok", "متوجه شدم"]] + : type === "confirm" + ? [ + ["yes", "بله"], + ["cancel", "انصراف"], + ] + : [ + ["explore", "کشف کنیم"], + ["later", "بعداً"], + ["cancel", "انصراف"], + ], + ), + ); + return; + } + if (type === "alert") call("dialogs", "showAlert", [message, done]); + else if (type === "confirm") + call("dialogs", "showConfirm", [message, done]); + else + call("dialogs", "showPopup", [ + { + title: "یک ایدهٔ تازه", + message, + buttons: [ + { id: "explore", type: "default", text: "کشف کنیم" }, + { id: "later", type: "default", text: "بعداً" }, + { id: "cancel", type: "cancel" }, + ], + }, + done, + ]); + }), + ), + ), + { featured: true, preview: true }, + ); + + card( + "haptics", + "interaction", + "قابلیت‌ها را لمس کنید", + "ضربه‌های سبک و سنگین یا بازخورد موفقیت و خطا را احساس کنید.", + "HapticFeedback", + "↯", + "violet", + `
${select("impact-style", "نوع ضربه", ["light", "medium", "heavy", "rigid", "soft"])}${select("notification-type", "نوع اعلان", ["success", "warning", "error"])}
` + + row( + button( + "haptics", + "ضربه", + () => + call("haptics", "HapticFeedback.impactOccurred", [ + value("impact-style"), + ]), + "main", + ), + button("haptics", "اعلان", () => + call("haptics", "HapticFeedback.notificationOccurred", [ + value("notification-type"), + ]), + ), + ) + + select("haptic-selection", "انتخاب را تغییر دهید (selectionChanged)", [ + ["one", "گزینهٔ اول"], + ["two", "گزینهٔ دوم"], + ["three", "گزینهٔ سوم"], + ]), + ); + + card( + "viewport", + "device", + "فضای بیشتری برای ایده‌ها", + "گسترش صفحه، تمام‌صفحه و قفل چرخش؛ اندازهٔ تجربه را تغییر دهید.", + "expand() · requestFullScreen()", + "⛶", + "blue", + row( + simple("viewport", "گسترش", "expand", [], "1.0", true, "main"), + simple("viewport", "تمام‌صفحه", "requestFullScreen", [], "1.3"), + simple("viewport", "خروج", "exitFullScreen", [], "1.3"), + ) + + row( + simple("viewport", "قفل چرخش", "lockOrientation", [], "1.3", true), + simple( + "viewport", + "آزادسازی چرخش", + "unlockOrientation", + [], + "1.3", + true, + ), + ) + + '

قفل چرخش و گسترش: اندروید · تمام‌صفحه: نسخهٔ 1.3

', + ); + card( + "lifecycle", + "device", + "رفتار برنامه در دستان شما", + "آماده‌بودن، تأیید خروج و ژست‌های عمودی را کنترل کنید.", + "ready() · close() · enableClosingConfirmation()", + "⌁", + "peach", + row( + simple("lifecycle", "اعلام آمادگی", "ready"), + button( + "lifecycle", + "بستن برنامه", + async () => { + if (!native) + throw new Error("بستن برنامه فقط از داخل ایتا ممکن است."); + const answer = await previewDialog( + "خروج از مدار", + "این کار برنامک را در ایتا می‌بندد.", + [ + ["close", "بستن برنامه"], + ["cancel", "انصراف"], + ], + ); + if (answer === "close") call("lifecycle", "close"); + }, + "danger", + ), + ) + + row( + simple("lifecycle", "تأیید خروج: روشن", "enableClosingConfirmation"), + simple("lifecycle", "تأیید خروج: خاموش", "disableClosingConfirmation"), + ) + + row( + simple( + "lifecycle", + "سوایپ: روشن", + "enableVerticalSwipes", + [], + "1.0", + true, + ), + simple( + "lifecycle", + "سوایپ: خاموش", + "disableVerticalSwipes", + [], + "1.0", + true, + ), + ), + ); + card( + "home", + "device", + "مدار، یک لمس نزدیک‌تر", + "برنامک را به صفحهٔ اصلی اضافه کنید و وضعیت میان‌بر را ببینید.", + "addToHomeScreen() · checkHomeScreenStatus()", + "⌂", + "mint", + row( + simple( + "home", + "افزودن به صفحهٔ اصلی", + "addToHomeScreen", + [], + "1.3", + true, + "main", + ), + button("home", "بررسی وضعیت", () => + call( + "home", + "checkHomeScreenStatus", + [ + (status) => { + result("home", status); + log("homeScreenStatus", status); + }, + ], + "1.3", + true, + ), + ), + ), + { androidOnly: true, version: "1.3" }, + ); + + card( + "qr", + "interaction", + "یک کد، یک کشف تازه", + "اسکنر دوربین ایتا را باز کنید. محتوای کد فقط نمایش داده می‌شود.", + "showScanQrPopup() · closeScanQrPopup()", + "▦", + "mint", + row( + button( + "qr", + "شروع اسکن", + () => + call( + "qr", + "showScanQrPopup", + [ + { text: "یک کد QR را داخل کادر قرار دهید" }, + (text) => { + result( + "qr", + `متن اسکن‌شده (تأییدنشده):\n${String(text).slice(0, 2000)}`, + ); + log("QR received", "متن اسکن شد؛ در گزارش ذخیره نمی‌شود."); + return true; + }, + ], + "1.0", + true, + ), + "main", + ), + simple("qr", "بستن اسکنر", "closeScanQrPopup", [], "1.0", true), + ), + { androidOnly: true }, + ); + + for (const [kind, title, icon, unit] of [ + ["Accelerometer", "حرکت را به تصویر بکشید", "◎", "m/s²"], + ["Gyroscope", "چرخش در سه محور", "⟳", "rad/s"], + ["DeviceOrientation", "جهتِ تازه‌ای پیدا کنید", "⌖", "rad"], + ]) { + const id = kind.toLowerCase(); + card( + id, + "device", + title, + "حسگر دستگاه را روشن کنید و تغییرات واقعی را زنده ببینید.", + `${kind}.start() · stop()`, + icon, + "blue", + `
— / — / — ${unit}
` + + field( + `${id}-rate`, + "فاصلهٔ نمونه‌برداری (میلی‌ثانیه)", + "200", + "number", + 'min="20" max="1000" step="10"', + ) + + (kind === "DeviceOrientation" + ? check(`${id}-absolute`, "جهت مطلق نسبت به شمال مغناطیسی") + : "") + + row( + button( + id, + "شروع حسگر", + () => { + const rate = Number(value(`${id}-rate`)); + if (!Number.isInteger(rate) || rate < 20 || rate > 1000) + throw new Error("فاصله باید بین ۲۰ تا ۱۰۰۰ میلی‌ثانیه باشد."); + call( + id, + `${kind}.start`, + [ + { + refresh_rate: rate, + ...(kind === "DeviceOrientation" + ? { need_absolute: checkbox(`${id}-absolute`) } + : {}), + }, + (started) => { + result( + id, + started + ? "حسگر فعال شد." + : "حسگر فعال نشد؛ پشتیبانی و مجوز دستگاه را بررسی کنید.", + !started, + ); + }, + ], + "1.3", + true, + ); + }, + "main", + ), + simple( + id, + "توقف", + `${kind}.stop`, + [ + (stopped) => + result(id, stopped ? "حسگر متوقف شد." : "توقف تأیید نشد."), + ], + "1.3", + true, + ), + ), + { androidOnly: true, version: "1.3", featured: kind === "Accelerometer" }, + ); + } + + async function authenticate() { + if (!native) + throw new Error("برای ورود امن، این برنامه را از داخل ایتا باز کنید."); + const data = await api("authenticate", { initData: sdk.initData }); + authenticated = true; + authExpiry = data.expires * 1000; + updateAuth(data.user); + result("identity", { + verified: true, + user: data.user, + context: data.context, + expires: new Date(authExpiry).toLocaleString("fa-IR"), + remoteVerified: data.remoteVerified, + }); + result("messages", "ورود تأیید شد. پس از دادن مجوز، پیام را ارسال کنید."); + log("authentication", "امضا و زمان ورود در سرور تأیید شد."); + } + function updateAuth(user) { + $("auth-status").textContent = authenticated ? "تأییدشده" : "مهمان"; + $("auth-caption").textContent = authenticated + ? String(user?.first_name || "ورود امن فعال است") + : "هنوز وارد نشده‌اید"; + } + card( + "identity", + "security", + "اعتماد از اینجا شروع می‌شود", + "امضای ورود و تاریخ آن در سرور بررسی می‌شود؛ سپس هویت تأییدشده را می‌بینید.", + "initData → PHP → HMAC-SHA256", + "◇", + "mint", + row( + button("identity", "تأیید ورود", authenticate, "main"), + button("identity", "پایان نشست", async () => { + const data = await api("logout"); + csrf = data.csrf; + authenticated = false; + authExpiry = 0; + updateAuth(); + for (const id of ["identity", "permissions", "messages"]) + result(id, "نشست پایان یافت."); + log("logout"); + }), + ) + + '

توکن فقط در سرور است. ورود تازه: ۵ دقیقه · نشست: ۱ ساعت

', + { featured: true }, + ); + card( + "authenticity", + "security", + "یک لایه اطمینان بیشتر", + "اصالت همین ورود را یک بار از سرور ایتایار بپرسید؛ در دقیقهٔ اول اجرا کنید.", + "POST /api/app/verify", + "⬡", + "blue", + row( + button( + "authenticity", + "اصالت‌سنجی با ایتایار", + async () => { + needAuth(); + const data = await api("verify"); + result("authenticity", data.message); + log("verify", "اصالت تأیید شد."); + }, + "main", + ), + ) + + '

هر hash فقط یک بار قابل تأیید است. نتیجهٔ موفق در نشست نگهداری می‌شود.

', + ); + card( + "permissions", + "security", + "ارتباط، با اجازهٔ شما", + "اجازهٔ پیام یا اشتراک تماس را درخواست کنید. تماس امضاشده در سرور بررسی می‌شود.", + "requestWriteAccess() · requestContact()", + "♧", + "violet", + row( + button( + "permissions", + "اجازهٔ ارسال پیام", + () => + call("permissions", "requestWriteAccess", [ + (allowed) => { + result( + "permissions", + allowed ? "اجازهٔ ارسال پیام داده شد." : "درخواست مجوز رد شد.", + ); + log("write access", { allowed }); + }, + ]), + "main", + ), + button("permissions", "اشتراک تماس", () => { + needAuth(); + call("permissions", "requestContact", [ + async (sent, details) => { + try { + if (!sent) { + result("permissions", "اشتراک تماس لغو شد."); + return; + } + const raw = + typeof details === "string" ? details : details?.response; + if (!raw) + throw new Error("این کلاینت دادهٔ امضاشدهٔ تماس را برنگرداند."); + const data = await api("contact", { contactData: raw }); + result("permissions", { verified: true, contact: data.contact }); + log("contact verification", "تماس امضاشده تأیید شد."); + } catch (error) { + fail("permissions", error); + } + }, + ]); + }), + ) + + '

شمارهٔ تماس در فایل یا گزارش رویداد ذخیره نمی‌شود.

', + ); + card( + "messages", + "security", + "یک سلام، از سمت سرور", + "یک پیام واقعی به حساب ایتای خود بفرستید و مسیر کامل ارتباط را تجربه کنید.", + "POST /api/app/sendMessage", + "✉", + "peach", + '' + + row( + button( + "messages", + "ارسال به خودم ↗", + async () => { + needAuth(); + const text = value("message-text").trim(); + if (!text) throw new Error("متن پیام را بنویسید."); + const data = await api("sendMessage", { text }); + result("messages", data.message); + log("sendMessage", "ارسال به کاربر تأییدشده موفق بود."); + }, + "main", + ), + ) + + '

نیازمند ورود و مجوز پیام · هر کاربر: ۵ تلاش در ساعت · هر پیام از اعتبار برنامه کسر می‌شود.

', + { featured: true }, + ); + + function httpsUrl(input, eitaaOnly = false) { + let url; + try { + url = new URL(input); + } catch { + throw new Error("یک آدرس کامل و معتبر وارد کنید."); + } + if (url.protocol !== "https:" || url.username || url.password) + throw new Error("آدرس باید HTTPS و بدون نام کاربری و رمز باشد."); + if (eitaaOnly && !["eitaa.com", "www.eitaa.com"].includes(url.hostname)) + throw new Error("برای لینک داخلی از دامنهٔ eitaa.com استفاده کنید."); + return url.href; + } + card( + "links", + "connection", + "درهای تازه باز کنید", + "یک صفحهٔ وب یا لینک داخلی ایتا را با گزینه‌های دلخواه باز کنید.", + "openLink() · openEitaaLink()", + "↗", + "blue", + field( + "external-url", + "آدرس وب", + "https://developer.eitaa.com", + "url", + 'dir="ltr"', + ) + + check("instant-view", "تلاش برای نمایش Instant View") + + check("try-browser", "باز کردن در مرورگر پیش‌فرض · 1.3") + + row( + button( + "links", + "باز کردن صفحهٔ وب", + () => { + const url = httpsUrl(value("external-url")); + call( + "links", + "openLink", + [ + url, + { + try_instant_view: checkbox("instant-view"), + try_browser: checkbox("try-browser"), + }, + ], + checkbox("try-browser") ? "1.3" : "1.0", + ); + }, + "main", + ), + ) + + field( + "eitaa-url", + "لینک داخلی ایتا", + "https://eitaa.com", + "url", + 'dir="ltr"', + ) + + row( + button("links", "باز کردن در ایتا", () => + call("links", "openEitaaLink", [httpsUrl(value("eitaa-url"), true)]), + ), + ), + ); + card( + "download", + "connection", + "یک یادگاری از مدار", + "فایل نمونهٔ مدار یا یک فایل HTTPS دلخواه را با دانلود بومی دریافت کنید.", + "downloadFile({url, file_name})", + "⇣", + "mint", + field( + "download-url", + "آدرس HTTPS فایل", + new URL("sample.php", location.href).href, + "url", + 'dir="ltr"', + ) + + field( + "download-name", + "نام فایل", + "madar-postcard.svg", + "text", + 'dir="ltr" maxlength="80"', + ) + + row( + button( + "download", + "دریافت فایل", + () => { + const name = value("download-name").trim(); + if (!name || /[\\/\x00-\x1f]/.test(name)) + throw new Error("نام فایل معتبر نیست."); + call( + "download", + "downloadFile", + [ + { url: httpsUrl(value("download-url")), file_name: name }, + (started) => + result( + "download", + started ? "دانلود شروع شد." : "دانلود لغو شد.", + ), + ], + "1.4", + true, + ); + }, + "main", + ), + ), + { androidOnly: true, version: "1.4" }, + ); + + card( + "inspector", + "inspector", + "پشت صحنهٔ این تجربه", + "نسخه، پلتفرم، ابعاد، ناحیهٔ امن، تم و وضعیت همهٔ کنترل‌ها را زنده ببینید.", + "WebApp properties · isVersionAtLeast()", + "≋", + "violet", + `
${field("version-check", "نسخهٔ مورد بررسی", "1.3", "text", 'dir="ltr" maxlength="12"')}${button( + "inspector", + "بررسی نسخه", + () => { + if (!/^\d+(\.\d+){0,2}$/.test(value("version-check"))) + throw new Error("نسخه را مانند 1.3 وارد کنید."); + const supported = call("inspector", "isVersionAtLeast", [ + value("version-check"), + ]); + result("inspector", { version: value("version-check"), supported }); + }, + )}
` + + row( + button("inspector", "تازه‌سازی داده‌ها", () => { + refreshInspector(); + result("inspector", "داده‌ها تازه شدند."); + }), + ) + + '

initDataUnsafe قابل اعتماد نیست و برای احراز هویت استفاده نمی‌شود. hash و دادهٔ خام ورود نمایش داده نمی‌شوند.

', + ); + card( + "event-tools", + "inspector", + "به نبض برنامه گوش کنید", + "همهٔ رویدادهای مستند را مشاهده کنید؛ شنیدن رویدادها را متوقف و دوباره وصل کنید.", + "onEvent(event, handler) · offEvent(event, handler)", + "⌁", + "mint", + row( + button( + "event-tools", + "اتصال رویدادها", + () => { + listen(true); + result( + "event-tools", + native + ? "شنیدن رویدادها فعال شد." + : "رویدادهای بومی نیازمند ایتا هستند.", + ); + }, + "main", + ), + button("event-tools", "قطع رویدادها", () => { + listen(false); + result("event-tools", "شنیدن رویدادهای بومی متوقف شد."); + }), + ) + + '
رویدادهای پوشش‌داده‌شده
', + ); + + for (const [index, [id, title, icon]] of categories.entries()) { + const button = document.createElement("button"); + button.className = `nav-item${index === 0 ? " active" : ""}`; + button.dataset.category = id; + button.innerHTML = `${icon}${title}${String(index + 1).padStart(2, "0")}`; + button.setAttribute("aria-current", index === 0 ? "page" : "false"); + $("navigation").append(button); + } + $("filters").innerHTML = [ + ["all", "همه"], + ["available", "قابل اجرا"], + ["android", "فقط اندروید"], + ] + .map( + ([id, label]) => + ``, + ) + .join(""); + $("cards").innerHTML = cards + .map( + (c) => + `
${c.androidOnly ? "Android" : c.preview && !native ? "پیش‌نمایش مرورگر" : c.version ? `SDK ${c.version}` : c.category === "security" ? "سمت سرور" : "Eitaa SDK"}

${c.title}

${c.description}

${esc(c.method)}
${c.body}
`, + ) + .join(""); + $("feature-count").textContent = fa.format(cards.length); + function filterCards() { + const search = value("search").trim().toLowerCase(); + let count = 0; + for (const c of cards) { + const available = + c.category === "inspector" || + c.preview || + (native && + (!c.androidOnly || android) && + (!c.version || sdk.isVersionAtLeast?.(c.version))); + const category = + search || + currentCategory === "all" || + (currentCategory === "overview" + ? c.featured + : c.category === currentCategory); + const text = + `${c.title} ${c.description} ${c.method} ${$("card-" + c.id).textContent}`.toLowerCase(); + const visible = Boolean( + category && + (!search || text.includes(search)) && + (currentFilter === "all" || + (currentFilter === "available" && available) || + (currentFilter === "android" && c.androidOnly)), + ); + $("card-" + c.id).hidden = !visible; + if (visible) count++; + } + $("result-count").textContent = `${fa.format(count)} آزمایش`; + $("empty").hidden = count !== 0; + } + function navigate(category) { + currentCategory = category; + currentFilter = "all"; + $("search").value = ""; + const title = categories.find((c) => c[0] === category)?.[1] || "نمای کلی"; + $("breadcrumb").textContent = title; + $("section-title").textContent = + category === "overview" ? "از اینجا شروع کنید ✦" : title; + $("section-description").textContent = + category === "overview" + ? "چند تجربهٔ منتخب برای اولین دور در مدار." + : "آزمایش را اجرا کنید و نتیجه را در همان کارت یا نبض مدار ببینید."; + $("hero").hidden = category !== "overview"; + document.querySelectorAll("[data-category]").forEach((b) => { + const active = b.dataset.category === category; + b.classList.toggle("active", active); + b.setAttribute("aria-current", active ? "page" : "false"); + }); + document.querySelectorAll("[data-filter]").forEach((b) => { + const active = b.dataset.filter === "all"; + b.classList.toggle("active", active); + b.setAttribute("aria-pressed", String(active)); + }); + filterCards(); + } + $("navigation").addEventListener("click", (e) => { + const b = e.target.closest("[data-category]"); + if (b) navigate(b.dataset.category); + }); + $("filters").addEventListener("click", (e) => { + const b = e.target.closest("[data-filter]"); + if (!b) return; + currentFilter = b.dataset.filter; + document.querySelectorAll("[data-filter]").forEach((item) => { + item.classList.toggle("active", item === b); + item.setAttribute("aria-pressed", String(item === b)); + }); + filterCards(); + }); + $("search").addEventListener("input", filterCards); + $("cards").addEventListener("click", async (e) => { + const target = e.target.closest("[data-action]"); + if (!target) return; + const action = actions.get(target.dataset.action); + if (!action) return; + target.disabled = true; + try { + await action.handler(); + } catch (error) { + fail(action.id, error); + } finally { + target.disabled = false; + } + }); + $("haptic-selection").addEventListener("change", () => { + try { + call("haptics", "HapticFeedback.selectionChanged"); + } catch (error) { + fail("haptics", error); + } + }); + $("explore").addEventListener("click", () => { + navigate("all"); + $("section-title").scrollIntoView({ behavior: "smooth", block: "start" }); + }); + $("show-session").addEventListener("click", () => navigate("security")); + $("notice-close").addEventListener( + "click", + () => ($("mode-notice").hidden = true), + ); + $("theme-toggle").addEventListener("click", () => { + themeOverride = true; + for (const property of ["--bg", "--text", "--muted", "--panel"]) + document.body.style.removeProperty(property); + document.body.classList.toggle("dark"); + refreshInspector(); + toast( + document.body.classList.contains("dark") + ? "تم تیره فعال شد." + : "تم روشن فعال شد.", + ); + }); + document.addEventListener("keydown", (e) => { + if ( + e.key === "/" && + !/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName) + ) { + e.preventDefault(); + $("search").focus(); + } + }); + + function syncTheme() { + if (!themeOverride) + document.body.classList.toggle( + "dark", + native + ? sdk.colorScheme === "dark" + : matchMedia("(prefers-color-scheme: dark)").matches, + ); + const theme = native ? sdk.themeParams || {} : {}; + $("theme-swatches").replaceChildren(); + for (const [key, color] of Object.entries(theme)) { + if (!/^#[0-9a-f]{6}$/i.test(color)) continue; + const swatch = document.createElement("span"); + swatch.className = "swatch"; + swatch.style.backgroundColor = color; + swatch.title = `${key}: ${color}`; + swatch.setAttribute("aria-label", swatch.title); + $("theme-swatches").append(swatch); + } + if (native && !themeOverride) { + for (const [key, variable] of [ + ["bg_color", "--bg"], + ["text_color", "--text"], + ["hint_color", "--muted"], + ["section_bg_color", "--panel"], + ]) { + const color = theme[key]; + if (/^#[0-9a-f]{6}$/i.test(color || "")) + document.body.style.setProperty(variable, color); + } + } + } + function refreshInspector() { + if (!$("state-inspector")) return; + const data = { + environment: native ? "Eitaa" : "Browser preview", + version: sdk?.version ?? null, + platform: native ? sdk.platform : "browser", + colorScheme: native + ? sdk.colorScheme + : document.body.classList.contains("dark") + ? "dark" + : "light", + initDataPresent: Boolean(sdk?.initData), + initDataUnsafe: "Untrusted — never used for authentication", + }; + if (native) { + for (const key of [ + "themeParams", + "isExpanded", + "isActive", + "isFullscreen", + "isOrientationLocked", + "bottomBarColor", + "viewportHeight", + "viewportStableHeight", + "headerColor", + "backgroundColor", + "isClosingConfirmationEnabled", + "isVerticalSwipesEnabled", + "safeAreaInset", + "contentSafeAreaInset", + ]) + data[key] = sdk[key] ?? null; + for (const key of [ + "MainButton", + "SecondaryButton", + "BackButton", + "SettingsButton", + "Accelerometer", + "Gyroscope", + "DeviceOrientation", + ]) { + data[key] = {}; + for (const prop of [ + "type", + "text", + "color", + "textColor", + "isVisible", + "isActive", + "hasShineEffect", + "position", + "isProgressVisible", + "isStarted", + "x", + "y", + "z", + "alpha", + "beta", + "gamma", + "absolute", + ]) + if (sdk[key]?.[prop] !== undefined) data[key][prop] = sdk[key][prop]; + } + } else data.viewport = { width: innerWidth, height: innerHeight }; + $("state-inspector").textContent = compact(data); + } + const events = [ + "themeChanged", + "viewportChanged", + "activated", + "deactivated", + "safeAreaChanged", + "contentSafeAreaChanged", + "mainButtonClicked", + "secondaryButtonClicked", + "backButtonClicked", + "settingsButtonClicked", + "popupClosed", + "qrTextReceived", + "scanQrPopupClosed", + "writeAccessRequested", + "contactRequested", + "fullscreenChanged", + "fullscreenFailed", + "homeScreenAdded", + "homeScreenChecked", + ]; + $("event-names").textContent = events.join("\n"); + for (const event of events) { + subscriptions.push([ + event, + (data) => { + if (event === "themeChanged") syncTheme(); + refreshInspector(); + log( + event, + event === "qrTextReceived" + ? "محتوای QR در گزارش ذخیره نمی‌شود." + : event === "contactRequested" + ? { status: data?.status } + : (data ?? "received"), + ); + }, + ]); + } + function listen(enabled) { + if (!native) { + $("event-toggle").textContent = "نیازمند ایتا"; + return; + } + if (listening === enabled) return; + for (const [name, handler] of subscriptions) { + try { + sdk[enabled ? "onEvent" : "offEvent"](name, handler); + } catch (error) { + log(name, "اتصال رویداد در این نسخه ممکن نیست.", true); + } + } + listening = enabled; + $("event-toggle").textContent = enabled ? "توقف شنیدن" : "ادامهٔ شنیدن"; + } + $("event-toggle").addEventListener("click", () => listen(!listening)); + $("clear-events").addEventListener("click", () => { + $("event-log").replaceChildren(); + eventTotal = 0; + $("event-count").textContent = "۰"; + }); + const sensors = ["Accelerometer", "Gyroscope", "DeviceOrientation"]; + function stopSensors() { + if (!native) return; + for (const kind of sensors) { + try { + if (sdk[kind]?.isStarted) sdk[kind].stop(); + } catch { + /* Client may already be closing. */ + } + } + } + function updateSensors() { + for (const kind of sensors) { + const sensor = native ? sdk[kind] : null; + if (!sensor) continue; + const id = kind.toLowerCase(); + const keys = + kind === "DeviceOrientation" + ? ["alpha", "beta", "gamma"] + : ["x", "y", "z"]; + const numbers = keys.map((key) => Number(sensor[key] ?? 0)); + $(`${id}-values`).textContent = + keys + .map((key, index) => `${key}: ${numbers[index].toFixed(2)}`) + .join(" ") + + (kind === "DeviceOrientation" + ? ` | absolute: ${Boolean(sensor.absolute)}` + : ""); + $(`${id}-ball`).style.transform = + `translate(${Math.max(-65, Math.min(65, numbers[0] * 9))}px,${Math.max(-35, Math.min(35, numbers[1] * 9))}px)`; + } + } + document.addEventListener("visibilitychange", () => { + if (document.hidden) stopSensors(); + }); + window.addEventListener("pagehide", () => { + stopSensors(); + listen(false); + for (const [kind, handler] of clickHandlers) { + try { + sdk?.[kind]?.offClick(handler); + } catch {} + } + }); + setInterval(() => { + if (document.hidden) return; + updateSensors(); + if (authenticated && Date.now() >= authExpiry) { + authenticated = false; + updateAuth(); + result( + "identity", + "نشست منقضی شد. برنامه را دوباره از ایتا باز کنید.", + true, + ); + } + }, 250); + $("environment").innerHTML = + `${native ? "متصل به ایتا" : "پیش‌نمایش مرورگر"}`; + $("environment").classList.toggle("connected", native); + $("sdk-version").textContent = native ? sdk.version : "Preview"; + if (native) { + $("mode-notice").querySelector("p").textContent = + "به مدار خوش آمدید. قابلیت‌های وابسته به نسخه و دستگاه هنگام اجرا بررسی می‌شوند."; + for (const [kind, handler] of clickHandlers) { + try { + sdk[kind]?.onClick(handler); + } catch {} + } + try { + sdk.ready(); + } catch (error) { + log("ready", error.message, true); + } + listen(true); + } + syncTheme(); + refreshInspector(); + filterCards(); + if (native) authenticate().catch((error) => fail("identity", error)); +})(); diff --git a/public/assets/brand.css b/public/assets/brand.css new file mode 100644 index 0000000..ce3023c --- /dev/null +++ b/public/assets/brand.css @@ -0,0 +1,2 @@ +@font-face{font-family:Vazir;src:url('Vazirmatn-Regular.ttf') format('truetype');font-display:swap} +*{box-sizing:border-box}body{margin:0;background:#f6f7f9;color:#163e37;font:15px/1.7 Vazir,Arial,sans-serif}a{color:inherit;text-decoration:none}header,main{max-width:1120px;margin:auto}header{display:flex;align-items:center;justify-content:space-between;padding:30px 24px;border-bottom:1px solid #dce4dd}header a{display:flex;align-items:center;gap:13px;letter-spacing:4px;font-weight:bold}header>span,.eyebrow{font-size:11px;letter-spacing:2px;color:#738578}main{padding:0 24px}.intro{padding:65px 0 50px}.intro h1{font-size:clamp(32px,5vw,60px);font-weight:normal;line-height:1.18;letter-spacing:-2px;margin:18px 0 24px}.intro p{color:#738578}.marks{display:grid;grid-template-columns:repeat(3,1fr);gap:18px}.marks article{min-height:300px;border-radius:18px;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:25px;padding:30px}.marks img{max-width:100%;height:auto}.marks span{font-size:9px;letter-spacing:2px}.dark{background:#163e37;color:#d7f68a}.light{border:1px solid #dce4dd}.app-icon{background:#e8efdf}.app-icon img{box-shadow:0 14px 28px #163e3720;border-radius:23%}.palette{display:grid;grid-template-columns:repeat(4,1fr);gap:18px;margin:30px 0 60px}.palette div{display:grid;grid-template-columns:40px 1fr;column-gap:12px;align-items:center}.palette i{grid-row:span 2;background:var(--swatch);height:40px;width:40px;border-radius:50%;border:1px solid #163e3715}.palette b{font-size:11px;font-weight:normal}.palette code{font-size:10px;color:#738578}.downloads{display:grid;grid-template-columns:1fr 1fr;gap:60px;margin-bottom:50px}.downloads h2{font-size:32px;line-height:1.3;font-weight:normal;margin:15px 0}.downloads p{font-size:13px;color:#738578;max-width:370px}.downloads nav a{display:flex;justify-content:space-between;padding:16px 0;border-bottom:1px solid #dce4dd;font-size:13px;gap:12px}.downloads a span{font-size:11px;color:#738578}.social{width:100%;height:auto;border-radius:18px;display:block}footer{display:flex;justify-content:space-between;padding:30px 0;font-size:10px;letter-spacing:1px;color:#738578}a:focus-visible{outline:3px solid #84a851;outline-offset:5px}@media(max-width:650px){.marks{grid-template-columns:1fr}.marks article{min-height:260px}.palette{grid-template-columns:1fr 1fr}.downloads{grid-template-columns:1fr;gap:20px}.intro{padding:40px 0}header>span{font-size:9px}} diff --git a/public/assets/brand/icon-1024.png b/public/assets/brand/icon-1024.png new file mode 100644 index 0000000..5b97ef2 Binary files /dev/null and b/public/assets/brand/icon-1024.png differ diff --git a/public/assets/brand/icon-192.png b/public/assets/brand/icon-192.png new file mode 100644 index 0000000..f25332e Binary files /dev/null and b/public/assets/brand/icon-192.png differ diff --git a/public/assets/brand/icon-32.png b/public/assets/brand/icon-32.png new file mode 100644 index 0000000..dfe00b9 Binary files /dev/null and b/public/assets/brand/icon-32.png differ diff --git a/public/assets/brand/icon-512.png b/public/assets/brand/icon-512.png new file mode 100644 index 0000000..3855a3a Binary files /dev/null and b/public/assets/brand/icon-512.png differ diff --git a/public/assets/brand/icon-maskable-512.png b/public/assets/brand/icon-maskable-512.png new file mode 100644 index 0000000..f0545c2 Binary files /dev/null and b/public/assets/brand/icon-maskable-512.png differ diff --git a/public/assets/brand/icon-maskable.svg b/public/assets/brand/icon-maskable.svg new file mode 100644 index 0000000..6079bbf --- /dev/null +++ b/public/assets/brand/icon-maskable.svg @@ -0,0 +1,7 @@ + + Madar app icon + + + + + diff --git a/public/assets/brand/icon.svg b/public/assets/brand/icon.svg new file mode 100644 index 0000000..b265f65 --- /dev/null +++ b/public/assets/brand/icon.svg @@ -0,0 +1,7 @@ + + Madar app icon + + + + + diff --git a/public/assets/brand/social.png b/public/assets/brand/social.png new file mode 100644 index 0000000..7c9180c Binary files /dev/null and b/public/assets/brand/social.png differ diff --git a/public/assets/brand/social.svg b/public/assets/brand/social.svg new file mode 100644 index 0000000..051d247 --- /dev/null +++ b/public/assets/brand/social.svg @@ -0,0 +1,15 @@ + + Madar — a space to explore + + + + + + + + + + + MADAR + A SPACE TO EXPLORE + diff --git a/public/assets/brand/symbol-dark.svg b/public/assets/brand/symbol-dark.svg new file mode 100644 index 0000000..ce12ffa --- /dev/null +++ b/public/assets/brand/symbol-dark.svg @@ -0,0 +1,6 @@ + + Madar orbital symbol for light backgrounds + + + + diff --git a/public/assets/brand/symbol.svg b/public/assets/brand/symbol.svg new file mode 100644 index 0000000..ccf5166 --- /dev/null +++ b/public/assets/brand/symbol.svg @@ -0,0 +1,6 @@ + + Madar orbital symbol + + + + diff --git a/public/brand.html b/public/brand.html new file mode 100644 index 0000000..1940046 --- /dev/null +++ b/public/brand.html @@ -0,0 +1,25 @@ + + + + + + Madar — Brand assets + + + + +
MADARIDENTITY / 01
+
+
A SPACE TO EXPLORE

A little orbit.
A world of possibilities.

Madar · مدار
A body, an orbit, a satellite. A symbol of curiosity in motion.

+
+
Ivory orbit and lime satellite on deep green01 / PRIMARY SYMBOL
+
Deep green orbit on a light background02 / LIGHT BACKGROUND
+
Madar rounded app icon03 / APP ICON
+
+
Deep green#163E37
Satellite lime#D7F68A
Soft ivory#E8F5D6
Cloud#F6F7F9
+
READY TO USE

One identity.
Every little surface.

Vector originals and export-ready assets for your app, home screen, browser and EitaaYar profile.

+ +
MADAR · مدارMade for discovery.
+
+ + diff --git a/public/favicon.ico b/public/favicon.ico new file mode 100644 index 0000000..6a2184a Binary files /dev/null and b/public/favicon.ico differ diff --git a/public/favicon.svg b/public/favicon.svg new file mode 100644 index 0000000..b265f65 --- /dev/null +++ b/public/favicon.svg @@ -0,0 +1,7 @@ + + Madar app icon + + + + + diff --git a/public/index.php b/public/index.php new file mode 100644 index 0000000..856a9d8 --- /dev/null +++ b/public/index.php @@ -0,0 +1,11 @@ +render(); +} catch (Throwable $error) { + Response::error($error, json: false); +} diff --git a/public/sample.php b/public/sample.php new file mode 100644 index 0000000..0d8b482 --- /dev/null +++ b/public/sample.php @@ -0,0 +1,8 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + مدار — آزمایشگاه برنامک ایتا + + + + + + + +
+
در حال شناسایی محیط
+
+
+
یک زمین بازی برای ایده‌های شما

امکانات ایتا،
در مدارِ تجربه.

لمس کن، امتحان کن، نتیجه را ببین.
قابلیت‌های برنامک ایتا را در یک فضای زنده کشف کن.

✦⌘◎ از یک کلیک ساده تا ارتباطی امن
+ +
+
⌘

—آزمایش تعاملی

آمادهٔ کشف
◈

—نسخهٔ SDK

◎

مهمانهنوز وارد نشده‌اید

↯

۰رویداد دریافت‌شده

+
ⓘ

در مرورگر هستید؛ ظاهر آزمایشگاه را ببینید. برای اجرای قابلیت‌های بومی و ورود امن، برنامه را از داخل ایتا باز کنید.

+
کشف. آزمایش. ساختن.

از اینجا شروع کنید ✦

چند تجربهٔ منتخب برای اولین دور در مدار.

+

نبضِ مدار

رویدادها و نتیجهٔ آزمایش‌ها

اولین آزمایش را اجرا کنید؛ نتیجه همین‌جا ظاهر می‌شود.

+
مدار · برای تجربه کردن ساخته شده.PHP + Eitaa SDK ✳
+
+
+ +
✦

آزمایش در مرورگر

+ + + diff --git a/resources/views/postcard.php b/resources/views/postcard.php new file mode 100644 index 0000000..42773b6 --- /dev/null +++ b/resources/views/postcard.php @@ -0,0 +1,4 @@ + ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], $pipes); + if (!is_resource($process)) { + throw new RuntimeException('Could not start brand renderer.'); + } + fclose($pipes[0]); + stream_get_contents($pipes[1]); + $error = stream_get_contents($pipes[2]); + fclose($pipes[1]); + fclose($pipes[2]); + if (proc_close($process) !== 0) { + throw new RuntimeException('Brand export failed: ' . $error); + } +} + +$brand = base_path('public/assets/brand'); +$icon = file_get_contents($brand . '/icon.svg'); +copy($brand . '/icon.svg', base_path('public/favicon.svg')); +foreach ([32, 192, 512, 1024] as $size) { + renderCommand(['rsvg-convert', '-w', (string) $size, '-h', (string) $size, '-o', $brand . '/icon-' . $size . '.png', $brand . '/icon.svg']); +} +// Full-bleed background with the symbol inside the maskable safe area. +$maskable = str_replace('', + '', $icon); +$maskable = str_replace('', '', $maskable); +file_put_contents($brand . '/icon-maskable.svg', $maskable); +renderCommand(['rsvg-convert', '-w', '512', '-h', '512', '-o', $brand . '/icon-maskable-512.png', $brand . '/icon-maskable.svg']); +renderCommand(['rsvg-convert', '-w', '180', '-h', '180', '-o', base_path('public/apple-touch-icon.png'), $brand . '/icon-maskable.svg']); +renderCommand(['rsvg-convert', '-o', $brand . '/social.png', $brand . '/social.svg']); +renderCommand(['magick', $brand . '/icon-512.png', '-define', 'icon:auto-resize=64,48,32,16', base_path('public/favicon.ico')]); +echo "Exported Madar icons, favicons, Apple touch icon, maskable icon and social preview.\n"; diff --git a/scripts/package.php b/scripts/package.php new file mode 100644 index 0000000..2b0ef0a --- /dev/null +++ b/scripts/package.php @@ -0,0 +1,45 @@ +isLink() || !in_array($entry->getExtension(), ['php', 'js', 'css', 'ttf', 'svg', 'png', 'ico', 'webmanifest', 'html'], true)) { + throw new RuntimeException('Unexpected deployment file: ' . $entry->getFilename()); + } + $files[] = substr($entry->getPathname(), strlen(base_path()) + 1); + } +} +sort($files, SORT_STRING); +$zip = new ZipArchive(); +if ($zip->open(base_path('dist/madar-cpanel.zip'), ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) { + throw new RuntimeException('Could not create archive.'); +} +foreach ($files as $file) { + if (!$zip->addFile(base_path($file), $file)) { + throw new RuntimeException('Could not package: ' . $file); + } +} +if (!$zip->close()) { + throw new RuntimeException('Could not finalize archive.'); +} +echo "Created dist/madar-cpanel.zip — set the document root to public/. No credentials included.\n"; diff --git a/storage/cache/.gitkeep b/storage/cache/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/storage/cache/.gitkeep @@ -0,0 +1 @@ + diff --git a/storage/secrets/.gitkeep b/storage/secrets/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/storage/secrets/.gitkeep @@ -0,0 +1 @@ + diff --git a/storage/sessions/.gitkeep b/storage/sessions/.gitkeep new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/storage/sessions/.gitkeep @@ -0,0 +1 @@ + diff --git a/tests/browser.mjs b/tests/browser.mjs new file mode 100644 index 0000000..5f7c3be --- /dev/null +++ b/tests/browser.mjs @@ -0,0 +1,326 @@ +import assert from "node:assert/strict"; +import { pathToFileURL } from "node:url"; +const { chromium } = await import( + pathToFileURL( + process.env.PLAYWRIGHT_MODULE || + "/tmp/app-browser-check/node_modules/playwright/index.mjs", + ).href +); +const browser = await chromium.launch({ + executablePath: process.env.CHROMIUM_PATH || "/usr/bin/chromium", + headless: true, + args: ["--no-sandbox"], +}); +const base = process.env.APP_URL || "http://127.0.0.1:8080"; +let checks = 0; +function check(value, label) { + assert.ok(value, label); + console.log("PASS:", label); + checks++; +} +try { + const context = await browser.newContext({ + viewport: { width: 1440, height: 1100 }, + colorScheme: "light", + }); + await context.route("https://developer.eitaa.com/**", (route) => + route.fulfill({ contentType: "application/javascript", body: "" }), + ); + const page = await context.newPage(); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.goto(base); + await page.waitForSelector(".feature-card"); + await page.evaluate(() => document.fonts.ready); + check( + (await page.locator(".feature-card:visible").count()) === 6, + "Six curated experiments on overview", + ); + check( + (await page.locator("#environment").textContent()) === "پیش‌نمایش مرورگر", + "Browser clearly labeled as preview", + ); + await page.screenshot({ path: "/tmp/app-desktop.png", fullPage: true }); + await page + .locator("#card-dialogs button") + .filter({ hasText: "تأیید" }) + .click(); + check( + await page.locator("#demo-dialog").isVisible(), + "Browser dialog preview opens", + ); + await page.locator("#dialog-buttons button[value=yes]").click(); + await page.waitForFunction(() => + document.querySelector("#dialogs-result").textContent.includes("yes"), + ); + check( + (await page.locator("#dialogs-result").textContent()).includes("yes"), + "Dialog selection returned", + ); + await page.locator("[data-category=all]").click(); + check( + (await page.locator(".feature-card:visible").count()) === 22, + "All documented experiment cards accessible", + ); + await page.locator("#search").fill("Gyroscope"); + check( + (await page.locator(".feature-card:visible").count()) === 1, + "Search resolves SDK object name", + ); + await page.locator("#search").fill("not-a-real-feature"); + check(await page.locator("#empty").isVisible(), "Search has empty state"); + await page.locator("[data-category=security]").click(); + await page.locator("#card-messages button").click(); + check( + (await page.locator("#messages-result").textContent()).includes("ابتدا"), + "Unauthenticated messaging blocked in UI", + ); + await page.locator("#theme-toggle").click(); + check( + await page.locator("body").evaluate((e) => e.classList.contains("dark")), + "Dark theme toggle works", + ); + await page.locator("#theme-toggle").click(); + await page.setViewportSize({ width: 390, height: 844 }); + await page.locator("[data-category=overview]").click(); + check( + await page.evaluate( + () => document.documentElement.scrollWidth <= innerWidth, + ), + "Mobile layout has no horizontal page overflow", + ); + await page.screenshot({ path: "/tmp/app-mobile.png", fullPage: true }); + check(errors.length === 0, "No browser runtime errors"); + await context.close(); + + // Contract tests use a deterministic SDK double, never the real Eitaa API. + const nativeContext = await browser.newContext({ + viewport: { width: 1000, height: 900 }, + }); + await nativeContext.route("https://developer.eitaa.com/**", (route) => + route.fulfill({ contentType: "application/javascript", body: "" }), + ); + await nativeContext.addInitScript(() => { + window.sdkCalls = []; + const methods = [ + "ready", + "expand", + "close", + "setHeaderColor", + "setBackgroundColor", + "setBottomBarColor", + "enableClosingConfirmation", + "disableClosingConfirmation", + "enableVerticalSwipes", + "disableVerticalSwipes", + "lockOrientation", + "unlockOrientation", + "requestFullscreen", + "exitFullscreen", + "openLink", + "openEitaaLink", + "addToHomeScreen", + "closeScanQrPopup", + ]; + const app = { + initData: "fake-signed-launch", + platform: "android", + version: "1.4", + colorScheme: "light", + themeParams: {}, + isVersionAtLeast: (v) => parseFloat(v) <= 1.4, + onEvent: () => {}, + offEvent: () => {}, + }; + for (const method of methods) + app[method] = (...args) => window.sdkCalls.push({ method, args }); + for (const kind of [ + "MainButton", + "SecondaryButton", + "BackButton", + "SettingsButton", + ]) { + app[kind] = {}; + for (const method of [ + "setParams", + "setText", + "show", + "hide", + "enable", + "disable", + "showProgress", + "hideProgress", + "onClick", + "offClick", + ]) + app[kind][method] = (...args) => + window.sdkCalls.push({ + method: kind + "." + method, + args: args.filter((arg) => typeof arg !== "function"), + }); + } + for (const kind of ["Accelerometer", "Gyroscope", "DeviceOrientation"]) { + app[kind] = { + isStarted: false, + x: 1, + y: 2, + z: 3, + alpha: 0.1, + beta: 0.2, + gamma: 0.3, + start(params, cb) { + this.isStarted = true; + window.sdkCalls.push({ method: kind + ".start", args: [params] }); + cb?.(true); + }, + stop(cb) { + this.isStarted = false; + cb?.(true); + }, + }; + } + app.requestContact = (cb) => + cb(true, { + response: "signed-contact-fixture", + responseUnsafe: { phone_number: "PRIVATE_PHONE" }, + }); + app.showScanQrPopup = (params, cb) => cb(""); + window.Eitaa = { WebApp: app }; + }); + const calls = []; + await nativeContext.route("**/api.php", async (route) => { + const data = route.request().postDataJSON(); + calls.push(data); + const result = + data.action === "authenticate" + ? { + ok: true, + user: { id: 123, first_name: "آزمایشی" }, + context: { start_param: "test" }, + expires: Math.floor(Date.now() / 1000) + 3600, + } + : data.action === "contact" + ? { + ok: true, + contact: { user_id: 123, phone_number: "PRIVATE_PHONE" }, + } + : { ok: true, message: "sent" }; + await route.fulfill({ + contentType: "application/json", + body: JSON.stringify(result), + }); + }); + const nativePage = await nativeContext.newPage(); + nativePage.on("pageerror", (error) => errors.push(error.message)); + await nativePage.goto(base); + await nativePage.waitForFunction( + () => document.querySelector("#auth-status").textContent === "تأییدشده", + ); + check( + calls.some( + (c) => c.action === "authenticate" && c.initData === "fake-signed-launch", + ), + "Launch authentication POST wired", + ); + await nativePage.locator("[data-category=interface]").click(); + await nativePage.locator("#main-button-text").fill("تست"); + await nativePage + .locator("#card-main-button button") + .filter({ hasText: "نمایش و اعمال" }) + .click(); + check( + await nativePage.evaluate(() => + sdkCalls.some( + (c) => c.method === "MainButton.setParams" && c.args[0].text === "تست", + ), + ), + "Native button configuration dispatched", + ); + await nativePage.locator("[data-category=device]").click(); + await nativePage + .locator("#card-viewport button") + .filter({ hasText: "تمام‌صفحه" }) + .click(); + check( + await nativePage.evaluate(() => + sdkCalls.some((c) => c.method === "requestFullscreen"), + ), + "Fullscreen documentation alias maps to current SDK", + ); + await nativePage + .locator("#card-accelerometer button") + .filter({ hasText: "شروع حسگر" }) + .click(); + check( + await nativePage.evaluate(() => Eitaa.WebApp.Accelerometer.isStarted), + "Sensor started with parameters", + ); + await nativePage.waitForFunction(() => + document + .querySelector("#accelerometer-values") + .textContent.includes("1.00"), + ); + check( + (await nativePage.locator("#accelerometer-values").textContent()).includes( + "1.00", + ), + "Sensor live values rendered", + ); + await nativePage + .locator("#card-accelerometer button") + .filter({ hasText: "توقف" }) + .click(); + check( + await nativePage.evaluate(() => !Eitaa.WebApp.Accelerometer.isStarted), + "Sensor stopped", + ); + await nativePage.locator("[data-category=interaction]").click(); + await nativePage + .locator("#card-qr button") + .filter({ hasText: "شروع اسکن" }) + .click(); + check( + (await nativePage.locator("#qr-result img").count()) === 0 && + (await nativePage.locator("#qr-result").textContent()).includes(" + document + .querySelector("#permissions-result") + .textContent.includes("PRIVATE_PHONE"), + ); + check( + calls.some( + (c) => + c.action === "contact" && c.contactData === "signed-contact-fixture", + ), + "Current SDK contact response sent for server verification", + ); + check( + !(await nativePage.locator("#event-log").textContent()).includes( + "PRIVATE_PHONE", + ), + "Contact excluded from event log", + ); + await nativePage.locator("#card-messages button").click(); + await nativePage.waitForFunction( + () => document.querySelector("#messages-result").textContent === "sent", + ); + const send = calls.find((c) => c.action === "sendMessage"); + check( + send && send.text && !("chat_id" in send), + "Message request contains no client-selected recipient", + ); + check(errors.length === 0, "No runtime errors with simulated native bridge"); + await nativeContext.close(); + console.log( + `\n${checks} browser checks passed. Screenshots: /tmp/app-desktop.png and /tmp/app-mobile.png`, + ); +} finally { + await browser.close(); +} diff --git a/tests/http.php b/tests/http.php new file mode 100644 index 0000000..aceb385 --- /dev/null +++ b/tests/http.php @@ -0,0 +1,100 @@ +getPathname(), strlen($root) + 1); + $entry->isDir() ? mkdir($destination, 0700) : copy($entry->getPathname(), $destination); + } +} +copy($root . '/config/app.php', $temp . '/config/app.php'); +mkdir($temp . '/public/assets/brand', 0700, true); +copy($root . '/public/assets/brand/social.svg', $temp . '/public/assets/brand/social.svg'); +foreach (['index.php', 'api.php', 'sample.php'] as $file) { + copy($root . '/public/' . $file, $temp . '/public/' . $file); +} +file_put_contents($temp . '/config/local.php', " 'TEST_ONLY_NOT_A_REAL_TOKEN', 'allow_local_http' => true];"); +file_put_contents($temp . '/storage/secrets/token.txt', 'PRIVATE_FILE_MUST_NOT_BE_SERVED'); +$port = random_int(20000, 45000); +$server = proc_open([PHP_BINARY,'-S','127.0.0.1:' . $port,'-t',$temp . '/public'], [['pipe','r'],['file',$temp . '/server.log','a'],['file',$temp . '/server.log','a']], $pipes, $temp, array_merge(getenv(), ['EITAA_APP_TOKEN' => 'TEST_ONLY_NOT_A_REAL_TOKEN'])); +if (!is_resource($server)) { + throw new RuntimeException('Cannot start PHP test server.'); +} +$curl = curl_init(); +curl_setopt_array($curl, [CURLOPT_RETURNTRANSFER=>true,CURLOPT_COOKIEFILE=>'',CURLOPT_TIMEOUT=>5]); +$base = 'http://127.0.0.1:' . $port; +function request(string $path, ?array $body = null, ?string $csrf = null, ?string $raw = null): array +{ + global $curl, $base; + curl_setopt_array($curl, [CURLOPT_URL=>$base.$path,CURLOPT_HTTPGET=>true,CURLOPT_HTTPHEADER=>[]]); + if ($body !== null || $raw !== null) { + curl_setopt_array($curl, [CURLOPT_POST=>true,CURLOPT_POSTFIELDS=>$raw ?? json_encode($body),CURLOPT_HTTPHEADER=>['Content-Type: application/json','X-CSRF-Token: '.($csrf??'')]]); + } + $response = curl_exec($curl); + return [curl_getinfo($curl,CURLINFO_RESPONSE_CODE),$response,json_decode($response ?: '',true)]; +} +try { + for ($i=0;$i<30;$i++) { + [$status,$html] = request('/'); + if ($status === 200) break; + usleep(100000); + } + check($status===200,'Page loads from isolated installation'); + preg_match('/name="csrf-token" content="([a-f0-9]+)"/', $html, $matches); + $csrf = $matches[1] ?? ''; + check(strlen($csrf)===64,'CSRF token provided'); + check(!str_contains($html,'TEST_ONLY_NOT_A_REAL_TOKEN'),'App token absent from page'); + check(request('/api.php')[0]===405,'API rejects GET'); + check(request('/api.php',['action'=>'authenticate'])[0]===403,'API rejects missing CSRF'); + check(request('/api.php',null,$csrf,'{broken')[0]===400,'API rejects malformed JSON'); + check(request('/api.php',null,$csrf,str_repeat('x',20001))[0]===413,'API rejects large request'); + check(request('/api.php',['action'=>'sendMessage','text'=>'hello'],$csrf)[0]===401,'Message requires verified session'); + $launch = signFixture(['auth_date'=>(string)time(),'user'=>'{"id":12345,"first_name":"تست"}'], 'TEST_ONLY_NOT_A_REAL_TOKEN'); + check(request('/api.php',['action'=>'authenticate','initData'=>$launch.'x'],$csrf)[0]===401,'Forged launch rejected over HTTP'); + [$status,,$data]=request('/api.php',['action'=>'authenticate','initData'=>$launch],$csrf); + check($status===200 && $data['user']['id']===12345,'Valid launch creates authenticated session'); + check(!isset($data['hash'])&&!isset($data['token']),'Authentication response excludes secrets'); + check(request('/api.php',['action'=>'sendMessage','text'=>''],$csrf)[0]===400,'Empty message blocked before network call'); + $contact = signFixture(['auth_date'=>(string)time(),'contact'=>'{"user_id":12345,"phone_number":"+989000000000"}'], 'TEST_ONLY_NOT_A_REAL_TOKEN'); + check(request('/api.php',['action'=>'contact','contactData'=>$contact],$csrf)[0]===200,'Signed contact accepted for current user'); + $otherContact = signFixture(['auth_date'=>(string)time(),'contact'=>'{"user_id":54321,"phone_number":"+989000000000"}'], 'TEST_ONLY_NOT_A_REAL_TOKEN'); + check(request('/api.php',['action'=>'contact','contactData'=>$otherContact],$csrf)[0]===401,'Other user contact rejected'); + [$status,,$data]=request('/api.php',['action'=>'logout'],$csrf); + check($status===200&&$data['csrf']!==$csrf,'Logout rotates CSRF'); + check(request('/api.php',['action'=>'sendMessage','text'=>'test'],$data['csrf'])[0]===401,'Logout removes authenticated user'); + // PHP's development server may fall back to index.php for unknown paths. + [$status,$privateBody] = request('/storage/secrets/token.txt'); + check(!str_contains($privateBody, 'PRIVATE_FILE_MUST_NOT_BE_SERVED'), 'Private file never served from document root'); + file_put_contents($temp . '/config/local.php', " 'TEST_ONLY_NOT_A_REAL_TOKEN', 'allow_local_http' => false];"); + check(request('/api.php',['action'=>'authenticate','initData'=>$launch],$data['csrf'])[0]===403, 'Production configuration refuses HTTP'); + [$status, $svg] = request('/sample.php'); + check($status === 200 && str_contains($svg, ' 0];"); + [$status, $html] = request('/'); + check($status === 500 && !str_contains($html, 'RuntimeException') && !str_contains($html, $temp), 'Invalid configuration fails without exposing paths or exceptions'); + file_put_contents($temp . '/config/local.php', " 'https://example.com/demo'];"); + [$status, $html] = request('/'); + check($status === 200 && str_contains($html, 'https://example.com/demo/assets/brand/social.png'), 'Configured share URL supports subdirectory deployment'); + file_put_contents($temp . '/config/local.php', " 'https://user:pass@example.com'];"); + check(request('/')[0] === 500, 'Share base URL rejects embedded credentials'); + echo "\n$tests total security and HTTP checks passed.\n"; +} finally { + proc_terminate($server); + fclose($pipes[0]); + proc_close($server); + // Remove only the uniquely generated test fixture, never user data. + $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($temp, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST); + foreach ($iterator as $entry) { + $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); + } + rmdir($temp); +} diff --git a/tests/security.php b/tests/security.php new file mode 100644 index 0000000..fb61af4 --- /dev/null +++ b/tests/security.php @@ -0,0 +1,75 @@ +status === $status, $name); + return; + } + throw new RuntimeException('FAIL: accepted ' . $name); +} +function signFixture(array $data, string $token): string +{ + ksort($data, SORT_STRING); + $pairs = []; + foreach ($data as $k => $v) { + $pairs[] = $k . '=' . $v; + } + $data['hash'] = hash_hmac('sha256', implode("\n", $pairs), hash_hmac('sha256', $token, 'WebAppData', true)); + return http_build_query($data, '', '&', PHP_QUERY_RFC3986); +} +$token = 'TEST_ONLY_NOT_A_REAL_TOKEN'; +$now = 1800000000; +$data = ['auth_date' => (string) $now, 'user' => '{"id":279058397,"first_name":"مهدی + & =","allows_write_to_pm":true}', 'start_param' => 'hello+world']; +$signed = signFixture($data, $token); +$validated = InitDataValidator::validate($signed, $token, 300, $now); +check($validated['start_param'] === 'hello+world', 'URL decoding preserves encoded plus'); +check(InitDataValidator::user($validated)['first_name'] === 'مهدی + & =', 'Persian user data is preserved'); +check(InitDataValidator::validate(str_replace('%20', '+', $signed), $token, 300, $now)['user'] === $data['user'], 'Form-encoded spaces supported'); +rejects(fn() => InitDataValidator::validate(str_replace('hello%2Bworld', 'changed', $signed), $token, 300, $now), 'Tampered data'); +rejects(fn() => InitDataValidator::validate($signed, 'WRONG', 300, $now), 'Wrong token'); +rejects(fn() => InitDataValidator::validate($signed . '&auth_date=' . $now, $token, 300, $now), 'Duplicate key'); +rejects(fn() => InitDataValidator::validate($signed . '&%61uth_date=' . $now, $token, 300, $now), 'Encoded duplicate key'); +rejects(fn() => InitDataValidator::validate($signed . '&user.name=x', $token, 300, $now), 'PHP key normalization ambiguity'); +rejects(fn() => InitDataValidator::validate($signed . '&x=%ZZ', $token, 300, $now), 'Malformed URL encoding'); +rejects(fn() => InitDataValidator::validate($signed, $token, 300, $now + 301), 'Expired launch'); +rejects(fn() => InitDataValidator::validate($signed, $token, 300, $now - 31), 'Future launch'); +rejects(fn() => InitDataValidator::validate(signFixture(['user' => $data['user']], $token), $token, 300, $now), 'Missing auth_date'); +rejects(fn() => InitDataValidator::validate(signFixture(['auth_date' => 'abc'], $token), $token, 300, $now), 'Invalid auth_date'); +rejects(fn() => InitDataValidator::validate(str_repeat('x', 16385), $token, 300, $now), 'Oversized payload'); +rejects(fn() => InitDataValidator::validate('auth_date=1&hash=123', $token, 300, $now), 'Invalid hash format'); +rejects(fn() => InitDataValidator::user(['user' => '{"id":-1}']), 'Invalid recipient ID'); +rejects(fn() => InitDataValidator::user(['user' => 'not-json']), 'Malformed user JSON'); +check(InitDataValidator::user(['user' => '{"id":4503599627370495}'])['id'] === 4503599627370495, '52-bit Eitaa ID preserved'); +check(!isset(InitDataValidator::user(['user' => '{"id":12,"extra":"secret"}'])['extra']), 'User response is allowlisted'); +// Published HMAC intermediate value is independent of our fixture signer. +check(hash_hmac('sha256', '5768337691:AAGDAe6rjxu1cUgxK4BizYi--Utc3J9v5AU', 'WebAppData') === 'aa492a44bdf019c759defb1698c1d77690189973945491a756051cdc1207a449', 'Documentation HMAC reference vector'); +$file = tempnam(sys_get_temp_dir(), 'app-limits-'); +try { + (new RateLimiter($file))->hit('user-1', 2, 3600); + (new RateLimiter($file))->hit('user-1', 2, 3600); + rejects(fn() => (new RateLimiter($file))->hit('user-1', 2, 3600), 'Persistent quota blocks third request', 429); + (new RateLimiter($file))->hit('user-2', 2, 3600); + check(count(json_decode(file_get_contents($file), true)) === 2, 'Independent user quotas'); +} finally { + unlink($file); +} +echo "\n$tests security checks passed.\n";