init
No files matched your search
@@ -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
|
||||||
@@ -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/
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -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.
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App;
|
||||||
|
|
||||||
|
use App\Eitaa\Client;
|
||||||
|
use App\Http\Controllers\DemoController;
|
||||||
|
use App\Http\Request;
|
||||||
|
use App\Http\Response;
|
||||||
|
use App\Security\RateLimiter;
|
||||||
|
use App\Security\Session;
|
||||||
|
use function App\Support\storage_path;
|
||||||
|
use function App\Support\view;
|
||||||
|
|
||||||
|
/** Composition root: dependencies are constructed once and passed explicitly. */
|
||||||
|
final class Application
|
||||||
|
{
|
||||||
|
private function __construct(
|
||||||
|
private readonly Config $config,
|
||||||
|
private readonly Request $request,
|
||||||
|
private readonly Session $session,
|
||||||
|
private readonly DemoController $controller,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function boot(): self
|
||||||
|
{
|
||||||
|
ini_set('display_errors', '0');
|
||||||
|
$request = Request::capture();
|
||||||
|
Response::securityHeaders($request->isHttps());
|
||||||
|
$config = Config::load();
|
||||||
|
$session = new Session(storage_path('sessions'), $config->get('session_lifetime'));
|
||||||
|
$session->start($request->isHttps());
|
||||||
|
$controller = new DemoController(
|
||||||
|
$config,
|
||||||
|
$session,
|
||||||
|
new RateLimiter(storage_path('cache/limits.json')),
|
||||||
|
new Client($config->get('token')),
|
||||||
|
);
|
||||||
|
return new self($config, $request, $session, $controller);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function render(): void
|
||||||
|
{
|
||||||
|
$csrf = $this->session->csrf();
|
||||||
|
$this->session->close();
|
||||||
|
$publicUrl = rtrim($this->config->get('public_url'), '/');
|
||||||
|
view('app', [
|
||||||
|
'csrf' => $csrf,
|
||||||
|
'shareImage' => $publicUrl === '' ? '' : $publicUrl . '/assets/brand/social.png',
|
||||||
|
]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function api(): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$data = $this->controller->dispatch($this->request);
|
||||||
|
} finally {
|
||||||
|
$this->session->close();
|
||||||
|
}
|
||||||
|
Response::json($data);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App;
|
||||||
|
|
||||||
|
use function App\Support\base_path;
|
||||||
|
use function App\Support\storage_path;
|
||||||
|
|
||||||
|
final class Config
|
||||||
|
{
|
||||||
|
private function __construct(private readonly array $values)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function load(): self
|
||||||
|
{
|
||||||
|
$values = require base_path('config/app.php');
|
||||||
|
if (is_file(base_path('config/local.php'))) {
|
||||||
|
$values = array_replace($values, require base_path('config/local.php'));
|
||||||
|
}
|
||||||
|
$values['token'] = getenv('EITAA_APP_TOKEN') ?: $values['token'];
|
||||||
|
if ($values['token'] === '' && is_readable(storage_path('secrets/token.txt'))) {
|
||||||
|
$values['token'] = trim(file_get_contents(storage_path('secrets/token.txt')));
|
||||||
|
}
|
||||||
|
foreach (['init_data_max_age', 'session_lifetime'] as $key) {
|
||||||
|
if (!is_int($values[$key]) || $values[$key] < 1) {
|
||||||
|
throw new \RuntimeException('Invalid duration configuration.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
foreach (['allow_local_http', 'verify_on_login', 'verify_ip'] as $key) {
|
||||||
|
if (!is_bool($values[$key])) {
|
||||||
|
throw new \RuntimeException('Invalid boolean configuration.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!is_string($values['token'])) {
|
||||||
|
throw new \RuntimeException('Invalid token configuration.');
|
||||||
|
}
|
||||||
|
$url = $values['public_url'];
|
||||||
|
if (!is_string($url) || ($url !== '' && (!filter_var($url, FILTER_VALIDATE_URL)
|
||||||
|
|| parse_url($url, PHP_URL_SCHEME) !== 'https'
|
||||||
|
|| parse_url($url, PHP_URL_USER) !== null
|
||||||
|
|| parse_url($url, PHP_URL_QUERY) !== null
|
||||||
|
|| parse_url($url, PHP_URL_FRAGMENT) !== null))) {
|
||||||
|
throw new \RuntimeException('Invalid public URL configuration.');
|
||||||
|
}
|
||||||
|
return new self($values);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function get(string $key): mixed
|
||||||
|
{
|
||||||
|
if (!array_key_exists($key, $this->values)) {
|
||||||
|
throw new \InvalidArgumentException('Unknown configuration key.');
|
||||||
|
}
|
||||||
|
return $this->values[$key];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Eitaa;
|
||||||
|
|
||||||
|
use App\Http\HttpException;
|
||||||
|
|
||||||
|
final class Client
|
||||||
|
{
|
||||||
|
public function __construct(private readonly string $token)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function verify(string $hash, ?string $ip): void
|
||||||
|
{
|
||||||
|
$payload = ['hash' => $hash];
|
||||||
|
if ($ip !== null) {
|
||||||
|
$payload['ip'] = $ip;
|
||||||
|
}
|
||||||
|
$this->post('verify', $payload);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function sendMessage(string $userId, string $text): void
|
||||||
|
{
|
||||||
|
$result = $this->post('sendMessage', ['chat_id' => $userId, 'text' => $text]);
|
||||||
|
if (($result['result'] ?? null) !== 'success') {
|
||||||
|
throw new HttpException('ارسال پیام توسط ایتایار تأیید نشد.', 502);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private function post(string $method, array $payload): array
|
||||||
|
{
|
||||||
|
if (!extension_loaded('curl')) {
|
||||||
|
throw new HttpException('افزونهٔ cURL در تنظیمات PHP هاست فعال نیست.', 503);
|
||||||
|
}
|
||||||
|
// Only the two public methods select endpoints. Credentials stay in TLS POST bodies.
|
||||||
|
$curl = curl_init('https://eitaayar.ir/api/app/' . $method);
|
||||||
|
curl_setopt_array($curl, [
|
||||||
|
CURLOPT_POST => true,
|
||||||
|
CURLOPT_POSTFIELDS => http_build_query(['token' => $this->token] + $payload),
|
||||||
|
CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => false,
|
||||||
|
CURLOPT_CONNECTTIMEOUT => 5, CURLOPT_TIMEOUT => 12,
|
||||||
|
CURLOPT_SSL_VERIFYPEER => true, CURLOPT_SSL_VERIFYHOST => 2,
|
||||||
|
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
|
||||||
|
CURLOPT_HTTPHEADER => ['Accept: application/json', 'Content-Type: application/x-www-form-urlencoded'],
|
||||||
|
]);
|
||||||
|
$raw = curl_exec($curl);
|
||||||
|
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
|
||||||
|
if ($raw === false || $status !== 200 || strlen($raw) > 65536) {
|
||||||
|
throw new HttpException('پاسخ معتبر از ایتایار دریافت نشد. بعداً تلاش کنید.', 502);
|
||||||
|
}
|
||||||
|
$data = json_decode($raw, true);
|
||||||
|
if (!is_array($data) || ($data['ok'] ?? false) !== true) {
|
||||||
|
throw new HttpException($method === 'verify'
|
||||||
|
? 'اصالت تأیید نشد؛ مهلت یک دقیقهای یا محدودیت یک بار مصرف را بررسی کنید.'
|
||||||
|
: 'ارسال انجام نشد؛ مجوز پیام و اعتبار برنامه را در ایتایار بررسی کنید.', 422);
|
||||||
|
}
|
||||||
|
return $data;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Config;
|
||||||
|
use App\Eitaa\Client;
|
||||||
|
use App\Http\HttpException;
|
||||||
|
use App\Http\Request;
|
||||||
|
use App\Security\InitDataValidator;
|
||||||
|
use App\Security\RateLimiter;
|
||||||
|
use App\Security\Session;
|
||||||
|
|
||||||
|
final class DemoController
|
||||||
|
{
|
||||||
|
public function __construct(
|
||||||
|
private readonly Config $config,
|
||||||
|
private readonly Session $session,
|
||||||
|
private readonly RateLimiter $limiter,
|
||||||
|
private readonly Client $eitaa,
|
||||||
|
) {
|
||||||
|
}
|
||||||
|
|
||||||
|
public function dispatch(Request $request): array
|
||||||
|
{
|
||||||
|
$request->requireSecurePost($this->config->get('allow_local_http'), $this->session->csrf());
|
||||||
|
$body = $request->json();
|
||||||
|
$action = $body['action'] ?? '';
|
||||||
|
if (!is_string($action)) {
|
||||||
|
throw new HttpException('عملیات نامعتبر است.');
|
||||||
|
}
|
||||||
|
$this->limiter->hit('ip:' . $request->ip(), 60, 60);
|
||||||
|
if ($action === 'logout') {
|
||||||
|
$this->session->logout();
|
||||||
|
return ['ok' => true, 'csrf' => $this->session->csrf()];
|
||||||
|
}
|
||||||
|
if ($this->config->get('token') === '') {
|
||||||
|
throw new HttpException('توکن برنامه هنوز در فضای خصوصی هاست تنظیم نشده است.', 503);
|
||||||
|
}
|
||||||
|
if ($action === 'authenticate') {
|
||||||
|
return $this->authenticate($request, $body);
|
||||||
|
}
|
||||||
|
$user = $this->session->user();
|
||||||
|
return match ($action) {
|
||||||
|
'verify' => $this->verify($request),
|
||||||
|
'contact' => $this->contact($body, $user),
|
||||||
|
'sendMessage' => $this->sendMessage($body, $user),
|
||||||
|
default => throw new HttpException('عملیات پیدا نشد.', 404),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private function authenticate(Request $request, array $body): array
|
||||||
|
{
|
||||||
|
$this->limiter->hit('login:' . $request->ip(), 20, 300);
|
||||||
|
if (!is_string($body['initData'] ?? null)) {
|
||||||
|
throw new HttpException('دادهٔ ورود وجود ندارد.', 401);
|
||||||
|
}
|
||||||
|
$data = InitDataValidator::validate(
|
||||||
|
$body['initData'], $this->config->get('token'), $this->config->get('init_data_max_age'),
|
||||||
|
);
|
||||||
|
$user = InitDataValidator::user($data);
|
||||||
|
$alreadyVerified = ($this->session->launch()['hash'] ?? '') === $data['hash']
|
||||||
|
&& $this->session->isRemoteVerified();
|
||||||
|
if ($this->config->get('verify_on_login') && !$alreadyVerified) {
|
||||||
|
$this->remoteVerify($request, $data);
|
||||||
|
}
|
||||||
|
$this->session->login($user, $data, $this->config->get('verify_on_login') || $alreadyVerified);
|
||||||
|
return [
|
||||||
|
'ok' => true,
|
||||||
|
'user' => $user,
|
||||||
|
'expires' => $this->session->expiresAt(),
|
||||||
|
'remoteVerified' => $this->session->isRemoteVerified(),
|
||||||
|
'context' => array_intersect_key($data, array_flip([
|
||||||
|
'auth_date', 'query_id', 'chat_type', 'chat_instance', 'start_param', 'device_id',
|
||||||
|
])),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function verify(Request $request): array
|
||||||
|
{
|
||||||
|
if (!$this->session->isRemoteVerified()) {
|
||||||
|
$this->remoteVerify($request, $this->session->launch());
|
||||||
|
$this->session->markRemoteVerified();
|
||||||
|
}
|
||||||
|
return ['ok' => true, 'message' => 'اصالت ورود توسط ایتایار تأیید شد.'];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function remoteVerify(Request $request, array $launch): void
|
||||||
|
{
|
||||||
|
if (time() - (int) $launch['auth_date'] > 60) {
|
||||||
|
throw new HttpException('اصالتسنجی فقط در دقیقهٔ اول ورود ممکن است.', 422);
|
||||||
|
}
|
||||||
|
$this->limiter->hit('verify-global', 10, 1);
|
||||||
|
$this->eitaa->verify($launch['hash'], $this->config->get('verify_ip') ? $request->ip() : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
private function contact(array $body, array $user): array
|
||||||
|
{
|
||||||
|
if (!is_string($body['contactData'] ?? null)) {
|
||||||
|
throw new HttpException('دادهٔ امضاشدهٔ تماس وجود ندارد.');
|
||||||
|
}
|
||||||
|
$data = InitDataValidator::validate($body['contactData'], $this->config->get('token'), 300);
|
||||||
|
$contact = json_decode($data['contact'] ?? '', true, 16, JSON_BIGINT_AS_STRING);
|
||||||
|
if (!is_array($contact) || (string) ($contact['user_id'] ?? '') !== (string) $user['id']) {
|
||||||
|
throw new HttpException('تماس متعلق به کاربر واردشده نیست.', 401);
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
'ok' => true,
|
||||||
|
'contact' => array_intersect_key($contact, array_flip(['first_name', 'last_name', 'phone_number', 'user_id'])),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
private function sendMessage(array $body, array $user): array
|
||||||
|
{
|
||||||
|
$message = $body['text'] ?? null;
|
||||||
|
if (!is_string($message) || trim($message) === '' || strlen($message) > 4000) {
|
||||||
|
throw new HttpException('متن پیام لازم است و باید کمتر از ۴۰۰۰ بایت باشد.');
|
||||||
|
}
|
||||||
|
// No client-selected recipient. Quotas persist across sessions.
|
||||||
|
$this->limiter->hit('message:' . $user['id'], 5, 3600);
|
||||||
|
$this->limiter->hit('message-global', 100, 3600);
|
||||||
|
$this->eitaa->sendMessage((string) $user['id'], trim($message));
|
||||||
|
return ['ok' => true, 'message' => 'پیام به حساب ایتای شما ارسال شد.'];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http;
|
||||||
|
|
||||||
|
final class HttpException extends \RuntimeException
|
||||||
|
{
|
||||||
|
public function __construct(string $message, public readonly int $status = 400)
|
||||||
|
{
|
||||||
|
parent::__construct($message);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http;
|
||||||
|
|
||||||
|
final class Request
|
||||||
|
{
|
||||||
|
public function __construct(private readonly array $server)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function capture(): self
|
||||||
|
{
|
||||||
|
return new self($_SERVER);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isHttps(): bool
|
||||||
|
{
|
||||||
|
return (!empty($this->server['HTTPS']) && $this->server['HTTPS'] !== 'off')
|
||||||
|
|| ($this->server['SERVER_PORT'] ?? '') == 443;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function ip(): string
|
||||||
|
{
|
||||||
|
// Forwarded headers are not trusted; configure proxies at the web server.
|
||||||
|
return $this->server['REMOTE_ADDR'] ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
public function requireSecurePost(bool $allowLocalHttp, string $csrf): void
|
||||||
|
{
|
||||||
|
if (($this->server['REQUEST_METHOD'] ?? '') !== 'POST') {
|
||||||
|
header('Allow: POST');
|
||||||
|
throw new HttpException('فقط درخواست POST پذیرفته میشود.', 405);
|
||||||
|
}
|
||||||
|
$loopback = in_array($this->ip(), ['127.0.0.1', '::1'], true);
|
||||||
|
if (!$this->isHttps() && !($allowLocalHttp && $loopback)) {
|
||||||
|
throw new HttpException('برای ورود امن از آدرس HTTPS استفاده کنید.', 403);
|
||||||
|
}
|
||||||
|
if (!hash_equals($csrf, $this->server['HTTP_X_CSRF_TOKEN'] ?? '')) {
|
||||||
|
throw new HttpException('نشست مرورگر معتبر نیست؛ صفحه را تازه کنید.', 403);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function json(): array
|
||||||
|
{
|
||||||
|
if (!str_starts_with(strtolower($this->server['CONTENT_TYPE'] ?? ''), 'application/json')) {
|
||||||
|
throw new HttpException('نوع درخواست باید JSON باشد.', 415);
|
||||||
|
}
|
||||||
|
$raw = file_get_contents('php://input', false, null, 0, 20001);
|
||||||
|
if ($raw === false || strlen($raw) > 20000) {
|
||||||
|
throw new HttpException('درخواست بیش از حد بزرگ است.', 413);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
$body = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
|
||||||
|
} catch (\JsonException $error) {
|
||||||
|
throw new HttpException('ساختار JSON معتبر نیست.', 400);
|
||||||
|
}
|
||||||
|
if (!is_array($body)) {
|
||||||
|
throw new HttpException('درخواست معتبر نیست.');
|
||||||
|
}
|
||||||
|
return $body;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Http;
|
||||||
|
|
||||||
|
use function App\Support\view;
|
||||||
|
|
||||||
|
final class Response
|
||||||
|
{
|
||||||
|
public static function securityHeaders(bool $https): void
|
||||||
|
{
|
||||||
|
header('X-Content-Type-Options: nosniff');
|
||||||
|
header('Referrer-Policy: no-referrer');
|
||||||
|
header('Cache-Control: no-store, private');
|
||||||
|
header("Content-Security-Policy: default-src 'self'; script-src 'self' https://developer.eitaa.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'");
|
||||||
|
if ($https) {
|
||||||
|
header('Strict-Transport-Security: max-age=31536000');
|
||||||
|
}
|
||||||
|
// Native Eitaa can embed the page: no frame-blocking header.
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function json(array $data, int $status = 200): void
|
||||||
|
{
|
||||||
|
http_response_code($status);
|
||||||
|
header('Content-Type: application/json; charset=utf-8');
|
||||||
|
echo json_encode($data, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function error(\Throwable $error, bool $json = true): void
|
||||||
|
{
|
||||||
|
$status = $error instanceof HttpException ? $error->status : 500;
|
||||||
|
$message = $error instanceof HttpException
|
||||||
|
? $error->getMessage()
|
||||||
|
: 'خطای داخلی سرور. تنظیمات و دسترسی پوشهٔ ذخیرهسازی را بررسی کنید.';
|
||||||
|
header('Cache-Control: no-store');
|
||||||
|
if ($json) {
|
||||||
|
self::json(['ok' => false, 'error' => $message], $status);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
http_response_code($status);
|
||||||
|
header('Content-Type: text/plain; charset=utf-8');
|
||||||
|
echo $message;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function postcard(): void
|
||||||
|
{
|
||||||
|
header('Content-Type: image/svg+xml; charset=utf-8');
|
||||||
|
header('Content-Disposition: attachment; filename="madar-postcard.svg"');
|
||||||
|
header('X-Content-Type-Options: nosniff');
|
||||||
|
header("Content-Security-Policy: default-src 'none'; style-src 'unsafe-inline'; sandbox");
|
||||||
|
view('postcard');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Security;
|
||||||
|
|
||||||
|
use App\Http\HttpException;
|
||||||
|
|
||||||
|
final class InitDataValidator
|
||||||
|
{
|
||||||
|
/** Parse without PHP parse_str's key rewriting or duplicate-key overwrite. */
|
||||||
|
public static function validate(string $raw, string $token, int $maxAge, ?int $now = null): array
|
||||||
|
{
|
||||||
|
if ($raw === '' || strlen($raw) > 16384 || $token === '') {
|
||||||
|
throw new HttpException('دادهٔ ورود معتبر نیست.', 401);
|
||||||
|
}
|
||||||
|
$values = [];
|
||||||
|
foreach (explode('&', $raw) as $pair) {
|
||||||
|
if (!str_contains($pair, '=') || preg_match('/%(?![0-9a-f]{2})/i', $pair)) {
|
||||||
|
throw new HttpException('ساختار دادهٔ امضاشده معتبر نیست.', 401);
|
||||||
|
}
|
||||||
|
[$key, $value] = array_map('urldecode', explode('=', $pair, 2));
|
||||||
|
if (!preg_match('/^[a-zA-Z0-9_]+$/D', $key) || array_key_exists($key, $values)) {
|
||||||
|
throw new HttpException('کلید تکراری یا نامعتبر است.', 401);
|
||||||
|
}
|
||||||
|
$values[$key] = $value;
|
||||||
|
}
|
||||||
|
$hash = $values['hash'] ?? '';
|
||||||
|
unset($values['hash']);
|
||||||
|
if (!preg_match('/^[a-f0-9]{64}$/D', $hash)) {
|
||||||
|
throw new HttpException('امضای داده معتبر نیست.', 401);
|
||||||
|
}
|
||||||
|
ksort($values, SORT_STRING);
|
||||||
|
$pairs = [];
|
||||||
|
foreach ($values as $key => $value) {
|
||||||
|
$pairs[] = $key . '=' . $value;
|
||||||
|
}
|
||||||
|
$key = hash_hmac('sha256', $token, 'WebAppData', true);
|
||||||
|
$expected = hash_hmac('sha256', implode("\n", $pairs), $key);
|
||||||
|
if (!hash_equals($expected, $hash)) {
|
||||||
|
throw new HttpException('امضا تأیید نشد. برنامه را از ایتا باز کنید.', 401);
|
||||||
|
}
|
||||||
|
$now ??= time();
|
||||||
|
$date = $values['auth_date'] ?? '';
|
||||||
|
if (!ctype_digit($date) || (int) $date > $now + 30 || $now - (int) $date > $maxAge) {
|
||||||
|
throw new HttpException('دادهٔ ورود منقضی شده است. برنامه را دوباره از ایتا باز کنید.', 401);
|
||||||
|
}
|
||||||
|
return $values + ['hash' => $hash];
|
||||||
|
}
|
||||||
|
|
||||||
|
public static function user(array $data): array
|
||||||
|
{
|
||||||
|
$user = json_decode($data['user'] ?? '', true, 16, JSON_BIGINT_AS_STRING);
|
||||||
|
if (!is_array($user) || !isset($user['id']) ||
|
||||||
|
!preg_match('/^[1-9][0-9]{0,15}$/D', (string) $user['id'])) {
|
||||||
|
throw new HttpException('شناسهٔ کاربر در دادهٔ امضاشده وجود ندارد.', 401);
|
||||||
|
}
|
||||||
|
return array_intersect_key($user, array_flip(['id', 'first_name', 'last_name', 'language_code', 'allows_write_to_pm']));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Security;
|
||||||
|
|
||||||
|
use App\Http\HttpException;
|
||||||
|
|
||||||
|
final class RateLimiter
|
||||||
|
{
|
||||||
|
public function __construct(private readonly string $file)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One bounded, locked file avoids session-reset bypass and unlimited file creation. */
|
||||||
|
public function hit(string $key, int $limit, int $window): void
|
||||||
|
{
|
||||||
|
$handle = @fopen($this->file, 'c+');
|
||||||
|
if (!$handle || !flock($handle, LOCK_EX)) {
|
||||||
|
throw new HttpException('ذخیرهسازی امن سرور در دسترس نیست.', 503);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
@chmod($this->file, 0600);
|
||||||
|
$rawState = stream_get_contents($handle);
|
||||||
|
$state = $rawState === '' ? [] : json_decode($rawState, true, 32, JSON_THROW_ON_ERROR);
|
||||||
|
if (!is_array($state)) {
|
||||||
|
throw new HttpException('ذخیرهسازی امن سرور معتبر نیست.', 503);
|
||||||
|
}
|
||||||
|
$now = time();
|
||||||
|
foreach ($state as $entry => $bucket) {
|
||||||
|
if (($bucket['expires'] ?? 0) <= $now) {
|
||||||
|
unset($state[$entry]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$key = hash('sha256', $key);
|
||||||
|
$bucket = $state[$key] ?? ['count' => 0, 'expires' => $now + $window];
|
||||||
|
if ($bucket['count'] >= $limit || (!isset($state[$key]) && count($state) >= 10000)) {
|
||||||
|
throw new HttpException('تعداد درخواستها زیاد است؛ کمی بعد دوباره تلاش کنید.', 429);
|
||||||
|
}
|
||||||
|
$bucket['count']++;
|
||||||
|
$state[$key] = $bucket;
|
||||||
|
$json = json_encode($state, JSON_THROW_ON_ERROR);
|
||||||
|
rewind($handle);
|
||||||
|
if (!ftruncate($handle, 0) || fwrite($handle, $json) !== strlen($json) || !fflush($handle)) {
|
||||||
|
throw new HttpException('ذخیرهسازی امن سرور در دسترس نیست.', 503);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
flock($handle, LOCK_UN);
|
||||||
|
fclose($handle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Security;
|
||||||
|
|
||||||
|
use App\Http\HttpException;
|
||||||
|
|
||||||
|
final class Session
|
||||||
|
{
|
||||||
|
public function __construct(private readonly string $directory, private readonly int $lifetime)
|
||||||
|
{
|
||||||
|
}
|
||||||
|
|
||||||
|
public function start(bool $https): void
|
||||||
|
{
|
||||||
|
if (!is_dir($this->directory) || !is_writable($this->directory)) {
|
||||||
|
throw new \RuntimeException('Session storage is unavailable.');
|
||||||
|
}
|
||||||
|
ini_set('session.use_strict_mode', '1');
|
||||||
|
ini_set('session.use_only_cookies', '1');
|
||||||
|
ini_set('session.gc_maxlifetime', (string) $this->lifetime);
|
||||||
|
session_name('app_session');
|
||||||
|
session_save_path($this->directory);
|
||||||
|
session_set_cookie_params([
|
||||||
|
'lifetime' => 0, 'path' => '/', 'secure' => $https,
|
||||||
|
'httponly' => true, 'samesite' => $https ? 'None' : 'Lax',
|
||||||
|
]);
|
||||||
|
if (!session_start()) {
|
||||||
|
throw new \RuntimeException('Could not start session.');
|
||||||
|
}
|
||||||
|
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
|
||||||
|
if (isset($_SESSION['expires']) && $_SESSION['expires'] <= time()) {
|
||||||
|
$this->logout();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public function csrf(): string
|
||||||
|
{
|
||||||
|
return $_SESSION['csrf'];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function user(): array
|
||||||
|
{
|
||||||
|
if (!isset($_SESSION['user'], $_SESSION['expires']) || $this->expiresAt() <= time()) {
|
||||||
|
throw new HttpException('ابتدا از داخل ایتا وارد شوید و هویت خود را تأیید کنید.', 401);
|
||||||
|
}
|
||||||
|
return $_SESSION['user'];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function launch(): array
|
||||||
|
{
|
||||||
|
return $_SESSION['launch'] ?? [];
|
||||||
|
}
|
||||||
|
|
||||||
|
public function expiresAt(): int
|
||||||
|
{
|
||||||
|
return $_SESSION['expires'] ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function isRemoteVerified(): bool
|
||||||
|
{
|
||||||
|
return $_SESSION['remote_verified'] ?? false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function markRemoteVerified(): void
|
||||||
|
{
|
||||||
|
$_SESSION['remote_verified'] = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function login(array $user, array $launch, bool $remoteVerified): void
|
||||||
|
{
|
||||||
|
session_regenerate_id(true);
|
||||||
|
$_SESSION['user'] = $user;
|
||||||
|
$_SESSION['launch'] = $launch;
|
||||||
|
$_SESSION['expires'] = time() + $this->lifetime;
|
||||||
|
$_SESSION['remote_verified'] = $remoteVerified;
|
||||||
|
}
|
||||||
|
|
||||||
|
public function logout(): void
|
||||||
|
{
|
||||||
|
$_SESSION = ['csrf' => bin2hex(random_bytes(32))];
|
||||||
|
session_regenerate_id(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function close(): void
|
||||||
|
{
|
||||||
|
session_write_close();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
namespace App\Support;
|
||||||
|
|
||||||
|
function base_path(string $path = ''): string
|
||||||
|
{
|
||||||
|
return dirname(__DIR__, 2) . ($path === '' ? '' : '/' . ltrim($path, '/'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function storage_path(string $path = ''): string
|
||||||
|
{
|
||||||
|
return base_path('storage' . ($path === '' ? '' : '/' . ltrim($path, '/')));
|
||||||
|
}
|
||||||
|
|
||||||
|
function e(string|int $value): string
|
||||||
|
{
|
||||||
|
return htmlspecialchars((string) $value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render within an isolated scope so data cannot overwrite the template path. */
|
||||||
|
function view(string $name, array $data = []): void
|
||||||
|
{
|
||||||
|
if (!preg_match('/^[a-zA-Z0-9_-]+$/D', $name)) {
|
||||||
|
throw new \InvalidArgumentException('Invalid view name.');
|
||||||
|
}
|
||||||
|
(static function (string $__file, array $__data): void {
|
||||||
|
extract($__data, EXTR_SKIP);
|
||||||
|
require $__file;
|
||||||
|
})(base_path('resources/views/' . $name . '.php'), $data);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use App\Application;
|
||||||
|
|
||||||
|
require_once __DIR__ . '/autoload.php';
|
||||||
|
|
||||||
|
return Application::boot();
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
spl_autoload_register(static function (string $class): void {
|
||||||
|
$prefix = 'App\\';
|
||||||
|
if (!str_starts_with($class, $prefix)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$path = dirname(__DIR__) . '/app/' . str_replace('\\', '/', substr($class, strlen($prefix))) . '.php';
|
||||||
|
if (is_file($path)) {
|
||||||
|
require $path;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
require_once dirname(__DIR__) . '/app/Support/helpers.php';
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
{
|
||||||
|
"name": "madar/eitaa-feature-lab",
|
||||||
|
"description": "A PHP feature playground for Eitaa mini apps",
|
||||||
|
"type": "project",
|
||||||
|
"require": {
|
||||||
|
"php": "^8.2",
|
||||||
|
"ext-curl": "*",
|
||||||
|
"ext-json": "*",
|
||||||
|
"ext-hash": "*",
|
||||||
|
"ext-openssl": "*",
|
||||||
|
"ext-session": "*"
|
||||||
|
},
|
||||||
|
"autoload": {
|
||||||
|
"psr-4": {
|
||||||
|
"App\\": "app/"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"app/Support/helpers.php"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"test": [
|
||||||
|
"@php tests/security.php",
|
||||||
|
"@php tests/http.php"
|
||||||
|
],
|
||||||
|
"package": "@php scripts/package.php",
|
||||||
|
"serve": "@php -S 127.0.0.1:8080 -t public"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
// Non-secret defaults. Override settings in config/local.php (ignored by Git).
|
||||||
|
return [
|
||||||
|
// Absolute deployed base URL for share images, e.g. https://example.com/demo
|
||||||
|
'public_url' => '',
|
||||||
|
'token' => '',
|
||||||
|
'init_data_max_age' => 300,
|
||||||
|
'session_lifetime' => 3600,
|
||||||
|
'allow_local_http' => false,
|
||||||
|
'verify_on_login' => false,
|
||||||
|
'verify_ip' => true,
|
||||||
|
];
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
return [
|
||||||
|
'public_url' => '',
|
||||||
|
// 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,
|
||||||
|
];
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use App\Http\Response;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$app = require dirname(__DIR__) . '/bootstrap/app.php';
|
||||||
|
$app->api();
|
||||||
|
} catch (Throwable $error) {
|
||||||
|
Response::error($error);
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 4.6 KiB |
@@ -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}}
|
||||||
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 7.9 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 192 192" fill="none">
|
||||||
|
<title>Madar app icon</title>
|
||||||
|
<rect width="192" height="192" fill="#163E37"/><g transform="translate(19.2 19.2) scale(.8)">
|
||||||
|
<ellipse cx="96" cy="96" rx="65" ry="37" transform="rotate(-35 96 96)" stroke="#E8F5D6" stroke-width="11"/>
|
||||||
|
<circle cx="96" cy="96" r="19" fill="#D7F68A"/>
|
||||||
|
<circle cx="149" cy="59" r="15" fill="#D7F68A" stroke="#163E37" stroke-width="7"/>
|
||||||
|
</g></svg>
|
||||||
|
After Width: | Height: | Size: 484 B |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 192 192" fill="none">
|
||||||
|
<title>Madar app icon</title>
|
||||||
|
<rect width="192" height="192" rx="44" fill="#163E37"/>
|
||||||
|
<ellipse cx="96" cy="96" rx="65" ry="37" transform="rotate(-35 96 96)" stroke="#E8F5D6" stroke-width="11"/>
|
||||||
|
<circle cx="96" cy="96" r="19" fill="#D7F68A"/>
|
||||||
|
<circle cx="149" cy="59" r="15" fill="#D7F68A" stroke="#163E37" stroke-width="7"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 442 B |
|
After Width: | Height: | Size: 52 KiB |
@@ -0,0 +1,15 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630" fill="none">
|
||||||
|
<title>Madar — a space to explore</title>
|
||||||
|
<rect width="1200" height="630" fill="#163E37"/>
|
||||||
|
<g stroke="#E8F5D6" opacity=".09" stroke-width="2">
|
||||||
|
<ellipse cx="600" cy="315" rx="510" ry="180" transform="rotate(-25 600 315)"/>
|
||||||
|
<ellipse cx="600" cy="315" rx="640" ry="260" transform="rotate(-25 600 315)"/>
|
||||||
|
</g>
|
||||||
|
<g transform="translate(408 75) scale(2)">
|
||||||
|
<ellipse cx="96" cy="96" rx="65" ry="37" transform="rotate(-35 96 96)" stroke="#E8F5D6" stroke-width="11"/>
|
||||||
|
<circle cx="96" cy="96" r="19" fill="#D7F68A"/>
|
||||||
|
<circle cx="149" cy="59" r="15" fill="#D7F68A" stroke="#163E37" stroke-width="7"/>
|
||||||
|
</g>
|
||||||
|
<text x="600" y="510" text-anchor="middle" fill="#E8F5D6" font-family="sans-serif" font-size="36" letter-spacing="12">MADAR</text>
|
||||||
|
<text x="600" y="552" text-anchor="middle" fill="#B5C9C1" font-family="sans-serif" font-size="16" letter-spacing="3">A SPACE TO EXPLORE</text>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 1014 B |
@@ -0,0 +1,6 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="192" height="192" viewBox="0 0 192 192" fill="none">
|
||||||
|
<title>Madar orbital symbol for light backgrounds</title>
|
||||||
|
<ellipse cx="96" cy="96" rx="65" ry="37" transform="rotate(-35 96 96)" stroke="#163E37" stroke-width="11"/>
|
||||||
|
<circle cx="96" cy="96" r="19" fill="#163E37"/>
|
||||||
|
<circle cx="149" cy="59" r="15" fill="#84A851" stroke="#F6F7F9" stroke-width="7"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 412 B |
@@ -0,0 +1,6 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="192" height="192" viewBox="0 0 192 192" fill="none">
|
||||||
|
<title>Madar orbital symbol</title>
|
||||||
|
<ellipse cx="96" cy="96" rx="65" ry="37" transform="rotate(-35 96 96)" stroke="#E8F5D6" stroke-width="11"/>
|
||||||
|
<circle cx="96" cy="96" r="19" fill="#D7F68A"/>
|
||||||
|
<circle cx="149" cy="59" r="15" fill="#D7F68A" stroke="#163E37" stroke-width="7"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 390 B |
@@ -0,0 +1,25 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<title>Madar — Brand assets</title>
|
||||||
|
<link rel="icon" href="favicon.svg" type="image/svg+xml">
|
||||||
|
<link rel="stylesheet" href="assets/brand.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header><a href="./"><img src="assets/brand/icon.svg" alt="" width="40" height="40"> MADAR</a><span>IDENTITY / 01</span></header>
|
||||||
|
<main>
|
||||||
|
<section class="intro"><span class="eyebrow">A SPACE TO EXPLORE</span><h1>A little orbit.<br>A world of possibilities.</h1><p>Madar · مدار<br>A body, an orbit, a satellite. A symbol of curiosity in motion.</p></section>
|
||||||
|
<section class="marks" aria-label="Logo variants">
|
||||||
|
<article class="dark"><img src="assets/brand/symbol.svg" width="220" height="220" alt="Ivory orbit and lime satellite on deep green"><span>01 / PRIMARY SYMBOL</span></article>
|
||||||
|
<article class="light"><img src="assets/brand/symbol-dark.svg" width="220" height="220" alt="Deep green orbit on a light background"><span>02 / LIGHT BACKGROUND</span></article>
|
||||||
|
<article class="app-icon"><img src="assets/brand/icon.svg" width="180" height="180" alt="Madar rounded app icon"><span>03 / APP ICON</span></article>
|
||||||
|
</section>
|
||||||
|
<section class="palette" aria-label="Brand colors"><div style="--swatch:#163E37"><i></i><b>Deep green</b><code>#163E37</code></div><div style="--swatch:#D7F68A"><i></i><b>Satellite lime</b><code>#D7F68A</code></div><div style="--swatch:#E8F5D6"><i></i><b>Soft ivory</b><code>#E8F5D6</code></div><div style="--swatch:#F6F7F9"><i></i><b>Cloud</b><code>#F6F7F9</code></div></section>
|
||||||
|
<section class="downloads"><div><span class="eyebrow">READY TO USE</span><h2>One identity.<br>Every little surface.</h2><p>Vector originals and export-ready assets for your app, home screen, browser and EitaaYar profile.</p></div><nav aria-label="Download brand assets"><a href="assets/brand/icon.svg" download>Vector app icon <span>SVG ↗</span></a><a href="assets/brand/icon-1024.png" download>App / EitaaYar profile <span>1024 PNG ↗</span></a><a href="assets/brand/icon-maskable-512.png" download>Home-screen icon <span>512 PNG ↗</span></a><a href="favicon.ico" download>Browser favicon <span>ICO ↗</span></a><a href="assets/brand/social.png" download>Social preview <span>1200 × 630 ↗</span></a></nav></section>
|
||||||
|
<img class="social" src="assets/brand/social.png" width="1200" height="630" alt="Madar social preview with orbital symbol and a space to explore tagline">
|
||||||
|
<footer><span>MADAR · مدار</span><span>Made for discovery.</span></footer>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
After Width: | Height: | Size: 31 KiB |
@@ -0,0 +1,7 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 192 192" fill="none">
|
||||||
|
<title>Madar app icon</title>
|
||||||
|
<rect width="192" height="192" rx="44" fill="#163E37"/>
|
||||||
|
<ellipse cx="96" cy="96" rx="65" ry="37" transform="rotate(-35 96 96)" stroke="#E8F5D6" stroke-width="11"/>
|
||||||
|
<circle cx="96" cy="96" r="19" fill="#D7F68A"/>
|
||||||
|
<circle cx="149" cy="59" r="15" fill="#D7F68A" stroke="#163E37" stroke-width="7"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 442 B |
@@ -0,0 +1,11 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use App\Http\Response;
|
||||||
|
|
||||||
|
try {
|
||||||
|
$app = require dirname(__DIR__) . '/bootstrap/app.php';
|
||||||
|
$app->render();
|
||||||
|
} catch (Throwable $error) {
|
||||||
|
Response::error($error, json: false);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use App\Http\Response;
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/bootstrap/autoload.php';
|
||||||
|
|
||||||
|
Response::postcard();
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"id": "./",
|
||||||
|
"name": "مدار | Madar",
|
||||||
|
"short_name": "مدار",
|
||||||
|
"description": "آزمایشگاه تعاملی قابلیتهای برنامک ایتا",
|
||||||
|
"lang": "fa",
|
||||||
|
"dir": "rtl",
|
||||||
|
"start_url": "./",
|
||||||
|
"scope": "./",
|
||||||
|
"display": "standalone",
|
||||||
|
"background_color": "#163E37",
|
||||||
|
"theme_color": "#163E37",
|
||||||
|
"icons": [
|
||||||
|
{"src": "assets/brand/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any"},
|
||||||
|
{"src": "assets/brand/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any"},
|
||||||
|
{"src": "assets/brand/icon-maskable-512.png", "sizes": "512x512", "type": "image/png", "purpose": "maskable"}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
<?php
|
||||||
|
use function App\Support\e;
|
||||||
|
?>
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="fa" dir="rtl">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||||
|
<meta name="theme-color" content="#163E37">
|
||||||
|
<meta name="application-name" content="Madar">
|
||||||
|
<meta name="apple-mobile-web-app-title" content="مدار">
|
||||||
|
<meta property="og:type" content="website">
|
||||||
|
<meta property="og:title" content="مدار | Madar">
|
||||||
|
<meta property="og:description" content="یک فضای تازه برای کشف و تجربهٔ قابلیتهای ایتا">
|
||||||
|
<meta name="twitter:card" content="summary_large_image">
|
||||||
|
<?php if (!empty($shareImage)): ?>
|
||||||
|
<meta property="og:image" content="<?= e($shareImage) ?>">
|
||||||
|
<meta property="og:image:width" content="1200">
|
||||||
|
<meta property="og:image:height" content="630">
|
||||||
|
<meta property="og:image:alt" content="Madar orbital identity">
|
||||||
|
<?php endif; ?>
|
||||||
|
<link rel="icon" href="favicon.ico" sizes="16x16 32x32 48x48 64x64">
|
||||||
|
<link rel="icon" href="favicon.svg" type="image/svg+xml" sizes="any">
|
||||||
|
<link rel="apple-touch-icon" href="apple-touch-icon.png" sizes="180x180">
|
||||||
|
<link rel="manifest" href="site.webmanifest">
|
||||||
|
<meta name="csrf-token" content="<?= e($csrf) ?>">
|
||||||
|
<meta name="description" content="مدار؛ آزمایشگاه تعاملی قابلیتهای برنامه و برنامک ایتا">
|
||||||
|
<title>مدار — آزمایشگاه برنامک ایتا</title>
|
||||||
|
<script src="https://developer.eitaa.com/eitaa-web-app.js"></script>
|
||||||
|
<link rel="stylesheet" href="assets/app.css">
|
||||||
|
<script src="assets/app.js" defer></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<a class="skip" href="#workspace">رفتن به محتوا</a>
|
||||||
|
<aside class="sidebar">
|
||||||
|
<a class="brand" href="./"><img class="brand-mark" src="assets/brand/icon.svg" width="47" height="47" alt=""><span>مدار<small>آزمایشگاه برنامک ایتا</small></span></a>
|
||||||
|
<div class="nav-caption">فضایی برای کشف کردن</div>
|
||||||
|
<nav id="navigation" aria-label="بخشهای آزمایشگاه"></nav>
|
||||||
|
<div class="sidebar-note"><span class="mini-orbit">✳</span><strong>کوچک شروع کن.<br>بزرگ تجربه کن.</strong><p>هر قابلیت، یک امکان تازه<br>برای ساختن تجربههای بهتر.</p><a href="https://developer.eitaa.com" target="_blank" rel="noopener noreferrer">مستندات ایتا <span>↗</span></a></div>
|
||||||
|
<div class="sidebar-footer"><span class="status-dot"></span> ساختهشده با PHP <span dir="ltr">v1.0</span></div>
|
||||||
|
</aside>
|
||||||
|
<div class="page">
|
||||||
|
<header class="topbar"><div class="breadcrumb">مدار <span>/</span> <strong id="breadcrumb">نمای کلی</strong></div><div class="top-actions"><span class="pill" id="environment"><i></i> در حال شناسایی محیط</span><button class="icon-button" id="theme-toggle" aria-label="تغییر تم روشن و تیره" title="تغییر تم">◐</button><img class="avatar" src="assets/brand/icon.svg" width="34" height="34" alt=""></div></header>
|
||||||
|
<main id="workspace">
|
||||||
|
<section class="hero" id="hero">
|
||||||
|
<div class="hero-copy"><div class="eyebrow"><span></span> یک زمین بازی برای ایدههای شما</div><h1>امکانات ایتا،<br>در مدارِ تجربه.</h1><p>لمس کن، امتحان کن، نتیجه را ببین.<br>قابلیتهای برنامک ایتا را در یک فضای زنده کشف کن.</p><div class="hero-actions"><button class="primary lime" id="explore">شروع ماجراجویی <span>↙</span></button><button class="hero-link" id="show-session">بررسی اتصال <span>↗</span></button></div><div class="hero-foot"><span class="tiny-stack"><b>✦</b><b>⌘</b><b>◎</b></span> از یک کلیک ساده تا ارتباطی امن</div></div>
|
||||||
|
<div class="orbital" aria-hidden="true"><div class="orbit orbit-one"></div><div class="orbit orbit-two"></div><div class="orbit orbit-three"></div><div class="planet"><img src="assets/brand/symbol.svg" width="137" height="137" alt=""></div><div class="satellite sat-a">⌘</div><div class="satellite sat-b">✳</div><div class="satellite sat-c">↗</div><div class="orbit-label label-a"><i></i> ایدهها در حرکتاند</div><div class="orbit-label label-b">Hello, Eitaa <span>✦</span></div><span class="star star-a">+</span><span class="star star-b">+</span><span class="star star-c">·</span></div>
|
||||||
|
</section>
|
||||||
|
<section class="metrics" aria-label="وضعیت آزمایشگاه"><div><span class="metric-icon mint">⌘</span><p><strong id="feature-count">—</strong><small>آزمایش تعاملی</small></p><span class="metric-tail">آمادهٔ کشف</span></div><div><span class="metric-icon violet">◈</span><p><strong id="sdk-version" dir="ltr">—</strong><small>نسخهٔ SDK</small></p></div><div><span class="metric-icon peach">◎</span><p><strong id="auth-status">مهمان</strong><small id="auth-caption">هنوز وارد نشدهاید</small></p></div><div><span class="metric-icon blue">↯</span><p><strong id="event-count">۰</strong><small>رویداد دریافتشده</small></p><span class="live-dot"></span></div></section>
|
||||||
|
<div class="notice" id="mode-notice"><span>ⓘ</span><p>در مرورگر هستید؛ ظاهر آزمایشگاه را ببینید. برای اجرای قابلیتهای بومی و ورود امن، برنامه را از داخل ایتا باز کنید.</p><button id="notice-close" aria-label="بستن راهنما">×</button></div>
|
||||||
|
<section class="lab"><div class="section-heading"><div><div class="eyebrow muted">کشف. آزمایش. ساختن.</div><h2 id="section-title">از اینجا شروع کنید <span>✦</span></h2><p id="section-description">چند تجربهٔ منتخب برای اولین دور در مدار.</p></div><label class="search"><span>⌕</span><input id="search" type="search" placeholder="جستجوی قابلیت یا متد…" aria-label="جستجوی قابلیت یا متد"><kbd>/</kbd></label></div><div class="filter-row"><div id="filters" aria-label="فیلتر قابلیتها"></div><span id="result-count"></span></div><div class="card-grid" id="cards"></div><div class="empty" id="empty" hidden>قابلیتی پیدا نشد. نام فارسی یا نام متد را امتحان کنید.</div></section>
|
||||||
|
<section class="event-panel" id="event-panel"><div class="event-heading"><div><span class="live-dot"></span><h2>نبضِ مدار</h2><span class="muted">رویدادها و نتیجهٔ آزمایشها</span></div><div><button class="text-button" id="event-toggle">توقف شنیدن</button><button class="text-button" id="clear-events">پاک کردن</button></div></div><div class="event-log" id="event-log" role="log" aria-live="polite" aria-relevant="additions"><p class="log-empty">اولین آزمایش را اجرا کنید؛ نتیجه همینجا ظاهر میشود.</p></div><div class="event-footer"><code>onEvent() / offEvent()</code><span>حداکثر ۸۰ رویداد · فقط در حافظهٔ همین صفحه</span></div></section>
|
||||||
|
<footer class="footer"><span><b>مدار</b> · برای تجربه کردن ساخته شده.</span><span>PHP + Eitaa SDK <span class="footer-spark">✳</span></span></footer>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
<div class="toast" id="toast" role="status" hidden></div>
|
||||||
|
<dialog id="demo-dialog"><form method="dialog"><div class="dialog-icon">✦</div><h2 id="dialog-title">آزمایش در مرورگر</h2><p id="dialog-message"></p><div id="dialog-buttons"></div></form></dialog>
|
||||||
|
<noscript><div class="noscript">برای استفاده از آزمایشگاه، جاوااسکریپت مرورگر را فعال کنید.</div></noscript>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?php
|
||||||
|
use function App\Support\base_path;
|
||||||
|
|
||||||
|
readfile(base_path('public/assets/brand/social.svg'));
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use function App\Support\base_path;
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/bootstrap/autoload.php';
|
||||||
|
|
||||||
|
/** Development-only export tool; cPanel needs only the generated assets. */
|
||||||
|
function renderCommand(array $command): void
|
||||||
|
{
|
||||||
|
$process = proc_open($command, [0 => ['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('<rect width="192" height="192" rx="44" fill="#163E37"/>',
|
||||||
|
'<rect width="192" height="192" fill="#163E37"/><g transform="translate(19.2 19.2) scale(.8)">', $icon);
|
||||||
|
$maskable = str_replace('</svg>', '</g></svg>', $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";
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
|
||||||
|
use function App\Support\base_path;
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/bootstrap/autoload.php';
|
||||||
|
|
||||||
|
if (!class_exists(ZipArchive::class)) {
|
||||||
|
throw new RuntimeException('PHP zip is needed only to build the archive.');
|
||||||
|
}
|
||||||
|
if (!is_dir(base_path('dist'))) {
|
||||||
|
mkdir(base_path('dist'), 0755);
|
||||||
|
}
|
||||||
|
$files = [
|
||||||
|
'README.md', 'FEATURES.md', 'BRANDING.md', 'composer.json',
|
||||||
|
'config/app.php', 'config/local.example.php',
|
||||||
|
'storage/secrets/.gitkeep', 'storage/sessions/.gitkeep', 'storage/cache/.gitkeep',
|
||||||
|
];
|
||||||
|
// Only code, templates and public assets are collected recursively.
|
||||||
|
// config/ and storage/ use the explicit non-secret allowlist above.
|
||||||
|
foreach (['bootstrap', 'app', 'resources/views', 'public'] as $directory) {
|
||||||
|
$iterator = new RecursiveIteratorIterator(
|
||||||
|
new RecursiveDirectoryIterator(base_path($directory), FilesystemIterator::SKIP_DOTS),
|
||||||
|
);
|
||||||
|
foreach ($iterator as $entry) {
|
||||||
|
if ($entry->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";
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
|
||||||
@@ -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("<img src=x onerror=alert(1)>");
|
||||||
|
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("<img"),
|
||||||
|
"QR content rendered as text, not executable HTML",
|
||||||
|
);
|
||||||
|
await nativePage.locator("[data-category=security]").click();
|
||||||
|
await nativePage
|
||||||
|
.locator("#card-permissions button")
|
||||||
|
.filter({ hasText: "اشتراک تماس" })
|
||||||
|
.click();
|
||||||
|
await nativePage.waitForFunction(() =>
|
||||||
|
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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
// Isolated test installation: never loads the real token or contacts Eitaa.
|
||||||
|
require __DIR__ . '/security.php';
|
||||||
|
$root = dirname(__DIR__);
|
||||||
|
$temp = sys_get_temp_dir() . '/app-http-' . bin2hex(random_bytes(6));
|
||||||
|
mkdir($temp, 0700);
|
||||||
|
foreach (['storage', 'storage/secrets', 'storage/sessions', 'storage/cache', 'config', 'public'] as $directory) {
|
||||||
|
mkdir($temp . '/' . $directory, 0700);
|
||||||
|
}
|
||||||
|
foreach (['bootstrap', 'app', 'resources'] as $directory) {
|
||||||
|
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($root . '/' . $directory, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::SELF_FIRST);
|
||||||
|
mkdir($temp . '/' . $directory, 0700);
|
||||||
|
foreach ($iterator as $entry) {
|
||||||
|
$destination = $temp . '/' . substr($entry->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', "<?php return ['token' => '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', "<?php return ['token' => '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, '<svg'), 'Postcard template served by thin download entry point');
|
||||||
|
file_put_contents($temp . '/config/local.php', "<?php return ['session_lifetime' => 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', "<?php return ['public_url' => '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', "<?php return ['public_url' => '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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
<?php
|
||||||
|
declare(strict_types=1);
|
||||||
|
use App\Http\HttpException;
|
||||||
|
use App\Security\InitDataValidator;
|
||||||
|
use App\Security\RateLimiter;
|
||||||
|
|
||||||
|
require dirname(__DIR__) . '/bootstrap/autoload.php';
|
||||||
|
|
||||||
|
$tests = 0;
|
||||||
|
function check(bool $condition, string $name): void
|
||||||
|
{
|
||||||
|
global $tests;
|
||||||
|
if (!$condition) {
|
||||||
|
throw new RuntimeException('FAIL: ' . $name);
|
||||||
|
}
|
||||||
|
$tests++;
|
||||||
|
echo 'PASS: ' . $name . PHP_EOL;
|
||||||
|
}
|
||||||
|
function rejects(callable $fn, string $name, int $status = 401): void
|
||||||
|
{
|
||||||
|
try {
|
||||||
|
$fn();
|
||||||
|
} catch (HttpException $e) {
|
||||||
|
check($e->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";
|
||||||