--- title: Task 5.2 Telegram Identity Linking and Session Model tags: [taskmaster, telegram, identity, session] created: 2026-05-24 status: implemented-foundation --- # Task 5.2 Telegram Identity Linking and Session Model This document captures the first backend implementation pass for Task 5.2. ## Implemented foundation - `TelegramLink` model maps one active Telegram user ID to one Amanat user. - `TelegramSession` model stores Mini App session tokens, Telegram user ID, optional Amanat user ID, initData fingerprint, auth date, source, expiry, and active state. - `/api/telegram/miniapp/verify` validates Telegram Mini App `initData` without creating an Amanat session. - `/api/telegram/miniapp/session` creates a Telegram session after verified `initData`. - `/api/telegram/link` lets an authenticated Amanat user link, read, or unlink a Telegram account. ## Security model - Backend verifies Mini App `initData` with Telegram's server-side signature scheme before trusting Telegram identity. - `initDataUnsafe` remains client-only display context and is not trusted for backend authorization. - Bot accounts are rejected. - Stale `auth_date` values are rejected by configured TTL. - Replayed Mini App payloads are rejected inside the configured replay window. - Duplicate active Telegram-to-Amanat links are rejected. ## Configuration | Variable | Purpose | |---|---| | `TELEGRAM_FEATURE_ENABLED` | Master feature flag | | `TELEGRAM_MINIAPP_ENABLED` | Mini App session/linking flag | | `TELEGRAM_BOT_TOKEN` | Server-side token used to verify Mini App signatures | | `TELEGRAM_INITDATA_MAX_AGE_SEC` | Maximum accepted `auth_date` age | | `TELEGRAM_INITDATA_REPLAY_WINDOW_MS` | Replay window for duplicate Mini App submissions | | `TELEGRAM_SESSION_TTL_SEC` | Telegram session lifetime | ## Tests - `backend/__tests__/telegram-service.test.ts` - `backend/__tests__/telegram-routes.test.ts` Coverage includes valid/invalid signature, expired initData, replay detection, session persistence, link/unlink behavior, duplicate link rejection, route-level Mini App validation, and secret non-leakage. ## Remaining work - Move replay protection from in-memory maps to Redis or another shared store for multi-instance deployments. - Bind Telegram session tokens to first-party web session controls once the final session architecture is implemented. - Add admin/support controls for revoking or blocking Telegram links.