diff --git a/.agents/skills/eitaa-mini-app/SKILL.md b/.agents/skills/eitaa-mini-app/SKILL.md new file mode 100644 index 0000000..3f5db02 --- /dev/null +++ b/.agents/skills/eitaa-mini-app/SKILL.md @@ -0,0 +1,57 @@ +--- +name: eitaa-mini-app +description: Build, integrate, review, debug, or release secure Eitaa apps and mini apps in any web stack. Use for the Eitaa WebApp SDK, EitaaYar registration and server APIs, initData authentication, native controls, themes, permissions, messages, sensors, testing, and deployment. Do not use for unrelated web apps or Telegram-only integrations. +--- + +# Eitaa apps and mini apps + +Implement the requested Eitaa behavior in the project's existing stack. Preserve its architecture, dependency choices, design system, and deployment model unless the user asks to change them. + +## Start with the repository + +Inspect the relevant entry points, server boundary, configuration, tests, and any local Eitaa documentation before changing code. Determine whether the task is: + +- a static/browser-only experience; +- a server-backed app that authenticates Eitaa users or calls EitaaYar; +- an integration into an existing React, Vue, Next.js, PHP, WordPress, Joomla, or other web application; or +- diagnosis, testing, registration, or release of an existing Eitaa app. + +Do not introduce a wrapper package, backend, framework, or project scaffold when the existing stack can support the request directly. Treat third-party Eitaa packages and plugins as optional; verify their current interface before installing or relying on them. + +## Route to the needed guidance + +- Read [platform-and-release.md](references/platform-and-release.md) when planning architecture, distinguishing apps from mini apps, registering in EitaaYar, choosing a launch URL, or releasing. +- Read [sdk-reference.md](references/sdk-reference.md) before implementing or reviewing browser SDK calls, native UI, themes, events, sensors, QR, downloads, fullscreen, or compatibility guards. +- Read [security-and-server.md](references/security-and-server.md) before using identity, `initData`, contacts, sessions, EitaaYar verification, or message sending. +- Read [testing.md](references/testing.md) when adding tests, debugging WebViews, or preparing a release. + +Read only the references needed for the current task. + +## Implementation invariants + +1. Load `https://developer.eitaa.com/eitaa-web-app.js` directly in `
` before application scripts. Do not download, vendor, proxy, or self-host it. +2. Access the bridge through `window.Eitaa?.WebApp`. In SSR frameworks, touch `window` only in client code after mount or through a guarded adapter. +3. Call `ready()` after essential UI is renderable. Use `expand()`, closing confirmation, fullscreen, orientation lock, vertical-swipe changes, and native buttons only when the product behavior calls for them. +4. Feature-detect every optional method or object and use `isVersionAtLeast()` when the documented minimum version is relevant. A missing bridge must produce a clear browser-preview or unsupported state, not fake native success. +5. Subscribe with stable handler references and unsubscribe with the same references. Stop sensors and remove listeners on unmount, page hide, or navigation as appropriate. +6. Build the layout from Eitaa theme and safe-area variables with readable fallbacks. React to `themeChanged`, safe-area, and viewport events when the UI depends on them. +7. Treat QR text, deep links, filenames, popup content, and all client input as untrusted. Validate schemes and render untrusted text as text, never executable HTML. +8. Keep app tokens and EitaaYar calls server-side. Send raw `initData` to the server and authenticate only after server validation; `initDataUnsafe` is display-only until matched to a verified identity. +9. Never accept a message recipient or authenticated user ID from an unverified client field. Derive it from the verified launch/session identity. +10. Do not log raw `initData`, hashes, signed contact payloads, tokens, phone numbers, or unnecessary user/device identifiers. + +## Resolve documentation inconsistencies safely + +Prefer the dedicated SDK and security rules over illustrative samples. In particular: + +- The SDK must come from the official URL even if an older sample shows a local copy. +- Preserve the received `hash` if optional server authenticity verification will use it; some sample code deletes it too early. +- Compare signatures in constant time and enforce freshness; a plain string equality example is not production hardening. +- The documented fullscreen names and names observed in clients can differ in capitalization. Feature-detect both spellings as described in the SDK reference. +- Some documentation sections for cloud storage, biometrics, location, device/secure storage, stories, and emoji status are commented placeholders. Do not present them as supported merely because their names appear in source documentation. + +If local project documentation is newer or the user asks for current platform behavior, verify the changing fact against current Eitaa documentation and state any uncertainty. + +## Finish proportionally + +Run the repository's existing checks plus focused tests for the changed bridge or server behavior. For production-facing work, distinguish browser simulation from real Eitaa verification and hand off the native Android/desktop checks that cannot be completed locally. Report any EitaaYar configuration, HTTPS URL, token, permission, or device action the user must supply without exposing secrets. diff --git a/.agents/skills/eitaa-mini-app/agents/openai.yaml b/.agents/skills/eitaa-mini-app/agents/openai.yaml new file mode 100644 index 0000000..bb0484b --- /dev/null +++ b/.agents/skills/eitaa-mini-app/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Eitaa Mini App" + short_description: "Build secure Eitaa apps and mini apps" + default_prompt: "Use $eitaa-mini-app to integrate this project with Eitaa or build a secure Eitaa mini app." diff --git a/.agents/skills/eitaa-mini-app/references/platform-and-release.md b/.agents/skills/eitaa-mini-app/references/platform-and-release.md new file mode 100644 index 0000000..d021ce5 --- /dev/null +++ b/.agents/skills/eitaa-mini-app/references/platform-and-release.md @@ -0,0 +1,51 @@ +# Platform, architecture, registration, and release + +## Product model + +An Eitaa **app** is a web application launched inside Eitaa's WebView. An Eitaa **mini app** is a direct Eitaa link to a web application under an app. Both use standard HTML, CSS, and JavaScript and can use the Eitaa WebApp SDK. + +The normal request path is: + +1. The user opens an app button or mini-app link in Eitaa. +2. Eitaa opens the registered HTTPS URL in its WebView and exposes launch data through the SDK. +3. The browser UI uses the SDK for native interaction. +4. If identity or dynamic data is needed, the browser sends raw signed launch data to the developer's backend. +5. The backend validates it, establishes its own session, and performs protected work. + +A backend is optional for a purely local/static experience. It is required whenever the app trusts identity, stores private data, uses the app token, verifies authenticity remotely, or sends messages. + +## Hosting contract + +- Serve the final entry URL over valid HTTPS. +- Register the exact final URL. The documented launch URL must not redirect. +- Keep the whole app usable in a constrained mobile WebView: responsive layout, RTL where appropriate, safe-area padding, no popup-window assumptions, and explicit loading/error states. +- Make browser mode honest. It may preview layout and harmless dialogs, but must not fabricate Eitaa authentication, permission approval, sensors, message delivery, QR scans, or other native results. + +## EitaaYar registration + +Use `https://eitaayar.ir`, complete developer identity verification, and open the Apps section. An app record includes: + +- PNG/JPG profile image; +- display title and unique username; +- active/inactive status; +- description and launch-button label; +- exact HTTPS destination URL; +- launch-card image and launch message. + +The documentation snapshot says one app can contain up to five mini apps. A mini-app record includes its visible title, direct mini-app link, and destination web URL. Publication in the Eitaa mini-app center is requested from the mini-app edit page and is subject to approval. + +Treat counts, review policy, form labels, and supported clients as changing platform facts. Recheck them when doing a real release. + +## Client support + +The supplied documentation's quick-start snapshot identifies Eitaa Android and Windows desktop as supported execution targets and says iOS and ordinary browser execution are unsupported for native behavior. Other source prose is less definitive. Do not promise support based on this snapshot alone; verify current Eitaa support before release. + +## Release checklist + +- The production URL is direct HTTPS and does not redirect. +- The SDK is loaded from the official URL before app code. +- Secrets and private server files are outside the public document root and deployment artifact. +- Browser preview is clearly labeled and native-only controls degrade safely. +- Authentication, permissions, contacts, message sending, native buttons, theme changes, safe areas, links, downloads, QR, sensors, and fullscreen are tested only where used. +- The exact production URL, status, assets, button wording, and requested mini-app links are correct in EitaaYar. +- The app is opened from real Eitaa Android and desktop after deployment. diff --git a/.agents/skills/eitaa-mini-app/references/sdk-reference.md b/.agents/skills/eitaa-mini-app/references/sdk-reference.md new file mode 100644 index 0000000..14937d6 --- /dev/null +++ b/.agents/skills/eitaa-mini-app/references/sdk-reference.md @@ -0,0 +1,131 @@ +# Eitaa WebApp SDK reference + +This is a compact implementation reference distilled from the supplied Eitaa documentation. Feature-detect at runtime because client versions differ. + +## Loading and adapter + +Place this before application scripts: + +```html + +``` + +Do not self-host the SDK. A small project-local adapter is useful for SSR safety and compatibility: + +```js +export function getEitaaWebApp() { + return typeof window === "undefined" ? undefined : window.Eitaa?.WebApp; +} + +export function callFullscreen(webApp, enter) { + const method = enter + ? webApp?.requestFullscreen ?? webApp?.requestFullScreen + : webApp?.exitFullscreen ?? webApp?.exitFullScreen; + return typeof method === "function" ? method.call(webApp) : undefined; +} +``` + +The documentation spells fullscreen as `requestFullScreen` / `exitFullScreen`; current clients may expose `requestFullscreen` / `exitFullscreen`. Do not assume either spelling without detection. + +## Initialization pattern + +1. Resolve the bridge after client mount. +2. Establish event handlers with stable references. +3. Synchronize the theme and safe-area-aware layout. +4. Render the essential UI. +5. Call `ready()` once. +6. Call `expand()` or other lifecycle methods only if desired. +7. On cleanup, unregister events and stop active sensors. + +Presence of `window.Eitaa` alone is weak environment detection. For native-only actions also require `WebApp`, expected methods, and normally non-empty `initData`; still handle every call as potentially unsupported. + +## Core fields + +- Launch and environment: `initData`, `initDataUnsafe`, `version`, `platform`, `isVersionAtLeast(version)`. +- Appearance: `colorScheme`, `themeParams`, `headerColor`, `backgroundColor`, `bottomBarColor`. +- Viewport: `isExpanded`, `isActive`, `isFullscreen`, `isOrientationLocked`, `viewportHeight`, `viewportStableHeight`, `safeAreaInset`, `contentSafeAreaInset`. +- Lifecycle state: `isClosingConfirmationEnabled`, `isVerticalSwipesEnabled`. +- Native controls: `MainButton`, `SecondaryButton`, `BackButton`, `SettingsButton`, `HapticFeedback`. +- Sensors: `Accelerometer`, `DeviceOrientation`, `Gyroscope`. + +`initDataUnsafe` can contain `query_id`, `user`, `chat_type`, `chat_instance`, `start_param`, `auth_date`, `device_id`, and `hash`. `chat_type`, `chat_instance`, and `start_param` are documented as mini-app/direct-link fields. Never authenticate from this parsed object. + +User fields are `id`, `first_name`, optional `last_name`, optional `language_code`, and optional `allows_write_to_pm`. IDs may use up to 52 significant bits; preserve them safely in the server language and avoid 32-bit storage. + +## Methods by capability + +Lifecycle and viewport: + +- `ready()`, `expand()`, `close()` +- `enableClosingConfirmation()`, `disableClosingConfirmation()` +- `enableVerticalSwipes()`, `disableVerticalSwipes()` +- `requestFullScreen()` / `exitFullScreen()` with compatibility aliases above +- `lockOrientation()`, `unlockOrientation()` +- `addToHomeScreen()`, `checkHomeScreenStatus()` + +Appearance and native UI: + +- `setHeaderColor(color)`, `setBackgroundColor(color)`, `setBottomBarColor(color)` +- `showAlert(message, callback)`, `showConfirm(message, callback)` +- `showPopup(params, callback)` +- `MainButton` and `SecondaryButton`: `setText`, `setParams`, `show`, `hide`, `enable`, `disable`, `showProgress`, `hideProgress`, `onClick`, `offClick` +- `BackButton` and `SettingsButton`: `show`, `hide`, `onClick`, `offClick` +- `HapticFeedback.impactOccurred(style)`, `notificationOccurred(type)`, `selectionChanged()` + +Links, permissions, and content: + +- `openLink(url, {try_instant_view?, try_browser?})`; call only from a user interaction. +- `openEitaaLink(url)` for an Eitaa link inside Eitaa. +- `requestWriteAccess(callback)` and `requestContact(callback)`. +- `showScanQrPopup({text?}, callback)` and `closeScanQrPopup()`. +- `downloadFile({url, file_name})`; the URL must be HTTPS. + +Sensors: + +- `Accelerometer.start({refresh_rate}, callback)` and `.stop(callback)` expose `isStarted`, `x`, `y`, `z` in m/s². +- `Gyroscope.start({refresh_rate}, callback)` and `.stop(callback)` expose `isStarted`, `x`, `y`, `z` in rad/s. +- `DeviceOrientation.start({refresh_rate, need_absolute}, callback)` and `.stop(callback)` expose `isStarted`, `absolute`, `alpha`, `beta`, `gamma` in radians. +- Documented `refresh_rate` range is 20–1000 ms and the platform may choose a different actual rate. + +Always stop sensors when no longer visible or mounted. + +## Native button and popup parameters + +`BottomButton.setParams` accepts documented snake_case fields: `text`, `color`, `text_color`, `is_active`, `is_visible`, `position`, and `has_shine_effect`. Secondary positions are `left`, `right`, `top`, or `bottom`. Keep a stable callback reference for `onClick`/`offClick`. + +`showPopup` accepts a title of at most 64 characters, a required message of 1–256 characters, and one to three buttons. Button `id` and custom `text` are at most 64 characters. Types are `default`, `ok`, `close`, `cancel`, and `destructive`; custom text is required for `default` and `destructive`. + +## Theme and layout + +Use the CSS variables supplied by the client, with fallbacks: + +- `--tg-color-scheme` +- `--tg-theme-bg-color`, `--tg-theme-text-color`, `--tg-theme-hint-color`, `--tg-theme-link-color` +- `--tg-theme-button-color`, `--tg-theme-button-text-color`, `--tg-theme-secondary-bg-color` +- `--tg-theme-header-bg-color`, `--tg-theme-bottom-bar-bg-color` +- `--tg-theme-accent-text-color`, `--tg-theme-section-bg-color`, `--tg-theme-section-header-text-color` +- `--tg-theme-section-separator-color`, `--tg-theme-subtitle-text-color`, `--tg-theme-destructive-text-color` +- `--tg-safe-area-inset-{top,right,bottom,left}` +- `--tg-content-safe-area-inset-{top,right,bottom,left}` +- `--tg-viewport-height`, `--tg-viewport-stable-height` + +Use stable height for UI pinned to the bottom. Live `viewportHeight` is not updated smoothly enough for that purpose. + +## Events + +Subscribe through `onEvent(name, handler)` and remove through `offEvent(name, handler)`: + +- Environment/layout: `themeChanged`, `viewportChanged`, `activated`, `deactivated`, `safeAreaChanged`, `contentSafeAreaChanged`. +- Controls/dialogs: `mainButtonClicked`, `backButtonClicked`, `settingsButtonClicked`, `popupClosed`. +- QR/permissions: `qrTextReceived`, `scanQrPopupClosed`, `writeAccessRequested`, `contactRequested`. +- Fullscreen/home screen: `fullscreenChanged`, `fullscreenFailed`, `homeScreenAdded`, `homeScreenChecked`. + +`viewportChanged` provides `isStateStable`. Permission events return statuses such as `allowed`/`cancelled` or `sent`/`cancelled`. Fullscreen failure includes an error. Home-screen check returns a status such as `unsupported`, `unknown`, `added`, or `missed`. + +Treat event payloads as input, redact sensitive fields from telemetry, and never open QR content automatically. + +## Version notes from the documentation snapshot + +SDK 1.3 marks orientation lock state, bottom bar color, secondary button, safe areas, sensors, bottom-bar color setter, home-screen methods, orientation methods, fullscreen, and `try_browser`. `downloadFile` is marked SDK 1.4. Guard these with feature detection even when the version claims support. + +Do not implement the documentation's commented placeholders for stories, emoji status, cloud storage, biometrics, location, device storage, secure storage, or chat objects without newer authoritative documentation. diff --git a/.agents/skills/eitaa-mini-app/references/security-and-server.md b/.agents/skills/eitaa-mini-app/references/security-and-server.md new file mode 100644 index 0000000..3d0bab7 --- /dev/null +++ b/.agents/skills/eitaa-mini-app/references/security-and-server.md @@ -0,0 +1,84 @@ +# Security and server integration + +Read this before trusting identity, processing contact data, calling EitaaYar, or sending messages. + +## Trust boundary + +- Browser `initDataUnsafe`, user IDs, `allows_write_to_pm`, device IDs, chat fields, contact previews, and message recipients are untrusted. +- Send the exact raw `WebApp.initData` string to the backend over HTTPS. +- Keep the Eitaa app token only in server-side secret storage or a secret environment variable. Never embed it in HTML, JavaScript, URLs, logs, source control, or client-visible error output. +- After validation, create the application's own short-lived session and derive identity from that server session on subsequent requests. + +## Local `initData` validation + +Given raw query-string launch data and the app token: + +1. Reject an empty or unreasonably large payload, malformed percent encoding, invalid key names, and duplicate decoded keys. +2. Parse query pairs without silently overwriting duplicates. URL-decode keys and values according to form/query encoding. +3. Remove and retain the `hash` field. Require a 64-character lowercase hexadecimal SHA-256 digest. +4. Sort the remaining decoded `key=value` strings by key using ordinal/string ordering. +5. Join the pairs with a single LF (`\n`), with no trailing newline, to form `data_check_string`. +6. Compute raw bytes `secret_key = HMAC_SHA256(key="WebAppData", message=app_token)`. +7. Compute hexadecimal `expected_hash = HMAC_SHA256(key=secret_key, message=data_check_string)`. +8. Compare `expected_hash` with the received hash using a constant-time comparison. +9. Require a numeric `auth_date`, reject future dates beyond a small clock-skew allowance, and enforce a short maximum age appropriate to the application. Five minutes plus about 30 seconds of future skew is a defensible default, not a platform mandate. +10. Parse `user` JSON only after signature validation. Validate its shape, preserve the ID without 32-bit truncation, and allowlist fields the application actually needs. + +Use the documentation's published intermediate vector in tests if available in the source project, but never copy a real-looking documentation token into application configuration. + +Production hardening should also include bounded input sizes, generic client errors, rate limiting, HTTPS enforcement, secure cookies, CSRF protection for session-authenticated writes, and replay-aware session design. + +## Optional EitaaYar authenticity verification + +Endpoint: + +```text +POST https://eitaayar.ir/api/app/verify +``` + +Server-side payload fields are `token`, `hash`, and optional user request `ip`. A successful response is `{"ok": true}`. + +The documentation says verification must occur within one minute of launch and can succeed only once. It also warns of a maximum 20 requests per second before temporary IP blocking. Therefore: + +- use it only from the backend; +- prefer a POST body so the token does not enter query URLs; +- do not retry aggressively; +- preserve the received hash for this call; +- use the actual trusted peer IP unless proxy handling is explicitly configured; +- decide deliberately whether a network failure blocks login; and +- cache successful verification only within the resulting session/launch context. + +This remote check is optional according to the supplied documentation. Local HMAC proves the launch data was signed; freshness limits replay duration. The one-time remote check adds stronger replay resistance when its timing and availability constraints fit the product. + +## Contact permission + +`requestContact` requires a user decision. Documentation describes a success boolean plus a signed contact-data string that can be validated like `initData`; some clients may wrap that string in an object's `response` field. Accept only a bounded signed string, send it to the backend, validate its signature and freshness, and require `contact.user_id` to match the already authenticated session user. Do not trust or persist a client-side `responseUnsafe` preview. + +Do not log phone numbers or signed contact material. Request the permission only at a user-understandable point in the flow. + +## Sending a message + +Endpoint: + +```text +POST https://eitaayar.ir/api/app/sendMessage +``` + +Server-side fields are `token`, `chat_id`, and `text`. Success is documented as: + +```json +{"ok": true, "result": "success"} +``` + +The user must have granted write access, for example through Start, opening a direct link from their message, or `requestWriteAccess`. Permission can later fail or be unavailable, so handle the upstream result rather than relying only on `allows_write_to_pm`. + +Derive `chat_id` from the verified session identity, never a browser-selected recipient. Bound and normalize message text, rate-limit attempts (including failures), use fixed HTTPS endpoints, verify TLS, reject redirects, set timeouts and response-size limits, and return generic errors to the client. The documentation snapshot mentions an initial 50,000-message credit and purchasable additional credit; treat credit policy as mutable and check EitaaYar. + +## Server session baseline + +- Regenerate the session ID after login and use strict session mode. +- Set `HttpOnly`, `Secure`, and an embedding-compatible `SameSite` policy; test how the target Eitaa clients handle cookies. +- Give sessions an absolute expiry independent of cookie lifetime. +- Bind CSRF tokens to the session for state-changing endpoints. +- Store only allowlisted verified identity/context fields. +- Never expose raw upstream responses, stack traces, token values, filesystem paths, or signing intermediates. diff --git a/.agents/skills/eitaa-mini-app/references/testing.md b/.agents/skills/eitaa-mini-app/references/testing.md new file mode 100644 index 0000000..2cac625 --- /dev/null +++ b/.agents/skills/eitaa-mini-app/references/testing.md @@ -0,0 +1,75 @@ +# Testing, debugging, and release verification + +## Layered test strategy + +Use three distinct layers and state which layer a result came from. + +### 1. Ordinary browser preview + +Test responsive layout, RTL, theme fallbacks, navigation, form behavior, accessibility, and honest unsupported states without the native bridge. Blocking/authenticated operations must remain unavailable unless explicitly using a development-only test seam. + +### 2. Deterministic bridge contract tests + +Inject a small `window.Eitaa.WebApp` test double before application code loads. Record method calls and trigger callbacks/events to verify: + +- `ready()` timing and optional `expand()` behavior; +- native button configuration and stable subscribe/unsubscribe callbacks; +- theme, safe-area, and viewport updates; +- permission denial as well as approval; +- fullscreen spelling compatibility and version guards; +- QR payloads render as inert text; +- sensors start, update, stop, and clean up; +- sensitive event payloads are redacted; +- raw `initData` reaches the authentication endpoint; and +- message requests contain text but no client-selected recipient. + +Do not call this native Eitaa testing; it checks the application's bridge contract. + +### 3. Backend security tests + +Use fake tokens and signed fixtures. Cover: + +- a valid signature and documented HMAC reference vector; +- changed data and wrong token; +- duplicate/encoded duplicate keys and malformed encoding; +- missing, invalid, expired, and too-far-in-the-future `auth_date`; +- malformed/oversized payloads and malformed user JSON; +- Persian text plus encoded `+`, `&`, and `=` characters; +- large Eitaa IDs without truncation; +- constant-time signature comparison through the language's standard primitive; +- session regeneration/expiry, CSRF, user binding, contact/user match, and rate limits; +- mocked upstream success, rejection, timeout, invalid JSON, large response, and redirect behavior. + +Tests must never load a real token or contact Eitaa unless the user explicitly authorizes an integration test. + +## Native WebView debugging + +Android procedure from the supplied documentation: + +1. Enable USB debugging on the device. +2. In Eitaa settings, press and hold the version row, release, then press and hold it again to open the debug menu. +3. Enable WebView debugging. +4. Connect the device and open `chrome://inspect#devices` in a Chromium-based desktop browser. +5. Open the app in Eitaa and inspect its WebView. + +Windows desktop procedure: + +1. Open Eitaa Settings, then Advanced, then Experimental Settings. +2. Enable WebView inspecting. +3. Open the app, right-click, and inspect. + +Menus can change between client versions. If these steps no longer match, verify the current Eitaa client instructions. + +## Native acceptance pass + +On every supported target actually used by the product, verify: + +- launch from the real registered Eitaa entry point and correct `platform`/SDK version; +- server-authenticated identity and expired/replayed launch behavior; +- light/dark themes, safe areas, keyboard, rotation, expansion, closing, and navigation; +- each used native control, popup, link, QR/download flow, permission denial/approval, and sensor lifecycle; +- fullscreen/home-screen behavior only when supported; +- one intentional message to the authenticated tester, including denied permission and insufficient-credit errors where practical; and +- no token, raw signed launch/contact data, phone number, or private identity in browser/server logs. + +Record unsupported methods as capability results, not application crashes. A browser or test-double pass does not prove native-client support.