Skip to content

[RELEASE] Alpha Web v0.1.0: Implement Web client with QR auth#136

Open
konard wants to merge 4 commits intomainfrom
issue-135-0f2d02a22cbb
Open

[RELEASE] Alpha Web v0.1.0: Implement Web client with QR auth#136
konard wants to merge 4 commits intomainfrom
issue-135-0f2d02a22cbb

Conversation

@konard
Copy link
Copy Markdown
Collaborator

@konard konard commented Apr 27, 2026

Fixes #135

Summary

  • Adds the web/ React 18 + Vite + TypeScript alpha client with TailwindCSS styling and PWA assets.
  • Implements TDWeb service bindings for phone/code/password auth, native Telegram QR auth, chat loading, message loading/sending, and proxy application.
  • Adds Teleton Agent integration with the issue's JSON-RPC 2.0 WebSocket contract plus explicit Management API status support for the current teleton-agent HTTPS API.
  • Adds encrypted browser storage helpers for opt-in session persistence and encrypted proxy/agent settings, with no Telegram session written to localStorage by default.
  • Adds TON balance/transaction panels, proxy settings UI, docs, deployment script, release tests, and screenshots.

QR Auth Follow-Up

  • Adds a QR sign-in mode alongside the existing phone/code flow.
  • Uses TDLib requestQrCodeAuthentication and renders authorizationStateWaitOtherDeviceConfirmation.link locally as a QR image.
  • Keeps QR payloads in memory only and documents the flow in docs/AUTH.md.
  • Hides the mobile bottom navigation during unauthenticated sign-in so QR controls are not covered.

Reproduction And Verification

Before this PR, the new test/web-alpha-release.test.mjs failed because web/package.json and the alpha web project did not exist. The test now verifies the web release structure and critical service contracts, including the QR auth path added after review feedback.

Screenshots

Desktop auth/error state:

Desktop auth screen

Mobile settings state:

Mobile settings screen

Desktop QR auth state:

Desktop QR auth screen

Mobile QR auth state:

Mobile QR auth screen

Tests

  • cd web && npm run test
  • cd web && npm run build
  • node --test test/web-alpha-release.test.mjs
  • npm test
  • npm run validate:secrets
  • npm run audit:security
  • npm run validate:foundation
  • npm run validate:release
  • npm run build:debug-artifacts
  • npm run decompose:dry-run
  • Playwright QR auth render check at http://localhost:5173/app/ with a mocked TDWeb client for desktop and mobile screenshots

Risk / Follow-Up

  • Live Telegram auth, messaging, and QR login require valid VITE_TELEGRAM_API_ID and VITE_TELEGRAM_API_HASH plus TDWeb runtime assets copied by npm install.
  • npm audit --omit=dev in web/ reports two moderate findings inherited from tdweb@1.8.0 -> uuid, with no upstream fix available from tdweb today. This is documented in web/README.md for release review.
  • Browser access to the agent Management API may require local TLS/CORS configuration because the current agent API uses self-signed HTTPS on localhost:7778.

Adding .gitkeep for PR creation (default mode).
This file will be removed when the task is complete.

Issue: #135
@konard konard self-assigned this Apr 27, 2026
@konard konard changed the title [WIP] [RELEASE] Alpha Web v0.1.0: Полная реализация и деплой Web-клиента [RELEASE] Alpha Web v0.1.0: Implement Web client Apr 28, 2026
@konard konard marked this pull request as ready for review April 28, 2026 00:17
@konard
Copy link
Copy Markdown
Collaborator Author

konard commented Apr 28, 2026

Solution summary

Implemented and pushed the alpha web client.

PR 136 is ready for review and CI is passing: #136

What changed:

  • Added full web/ React 18 + Vite + TypeScript app.
  • Added TDWeb service layer, auth/chat/message/proxy methods.
  • Added Teleton Agent WebSocket JSON-RPC support plus Management API status checks.
  • Added encrypted settings/session helpers using AES-GCM + IndexedDB key storage.
  • Added proxy, agent, TON, chat, and auth UI.
  • Added PWA manifest, service worker, offline page, icons, docs, deploy script, and screenshots.
  • Added root regression test and web service tests.

Verified:

  • cd web && npm run test
  • cd web && npm run build
  • npm test
  • npm run validate:secrets
  • npm run audit:security
  • npm run validate:foundation
  • npm run validate:release
  • npm run build:debug-artifacts
  • npm run decompose:dry-run
  • Playwright desktop/mobile render checks

Local preview is running at http://localhost:4173/app/.

Notes:

  • Live Telegram auth/message sending was not exercised because it requires real VITE_TELEGRAM_API_ID / VITE_TELEGRAM_API_HASH.
  • web/ has a documented npm audit --omit=dev caveat: tdweb@1.8.0 depends on vulnerable uuid, with no upstream fix available.

This summary was automatically extracted from the AI working session output.

@konard
Copy link
Copy Markdown
Collaborator Author

konard commented Apr 28, 2026

🤖 Solution Draft Log

This log file contains the complete execution trace of the AI solution draft process.

💰 Cost estimation:

  • Model: GPT-5.5
  • Provider: OpenAI
  • Public pricing estimate: $31.674899

📊 Context and tokens usage:

  • 22.9M / 1.1M (2184%) input tokens, 62.7K / 128K (49%) output tokens

Total: (657.5K + 22.3M cached) input tokens, 62.7K output tokens, $31.674899 cost

🤖 Models used:

  • Tool: OpenAI Codex
  • Requested: gpt-5.5
  • Model: GPT-5.5 (gpt-5.5)

📎 Log file uploaded as Repository (2 chunks) (102494KB)


Now working session is ended, feel free to review and add any feedback on the solution draft.

@konard
Copy link
Copy Markdown
Collaborator Author

konard commented Apr 28, 2026

✅ Ready to merge

This pull request is now ready to be merged:

  • All CI checks have passed
  • No merge conflicts
  • No pending changes

Monitored by hive-mind with --auto-restart-until-mergeable flag

@xlabtg
Copy link
Copy Markdown
Owner

xlabtg commented Apr 28, 2026

🔄 Предложение: Добавить альтернативную авторизацию через Telegram QR-код

@konard Отличная работа над текущей реализацией авторизации! 🎉

Предложение: Добавить альтернативный метод входа через QR-код Telegram как опцию к существующей авторизации.


🎯 Зачем это нужно

Преимущество Описание
Удобство для мобильных пользователей Не нужно копировать токены — просто отсканировать код
Безопасность Токен никогда не отображается в интерфейсе, передаётся напрямую от Telegram
Совместимость с Telegram Mini Apps Нативная интеграция с экосистемой Telegram
Быстрый онбординг Новый пользователь может начать работу за 10 секунд

🏗️ Предлагаемая реализация

1. Новый эндпоинт для генерации QR-кода

// POST /api/auth/qr/initiate
interface QRInitiateRequest {
  clientId?: string; // опционально, для привязки сессии
}

interface QRInitiateResponse {
  qrCodeData: string; // строка для генерации QR (t.me/login?token=...)
  sessionId: string;  // уникальный ID сессии для опроса статуса
  expiresAt: Date;    // время жизни кода (рекомендуется 5 минут)
}

2. Эндпоинт для проверки статуса авторизации

// GET /api/auth/qr/status/:sessionId
interface QRStatusResponse {
  status: 'pending' | 'authorized' | 'expired' | 'cancelled';
  authData?: {
    token: string;      // JWT или сессионный токен
    user: {
      id: number;
      username?: string;
      first_name?: string;
      is_premium?: boolean;
    };
  };
}

3. WebUI-компонент

┌─────────────────────────────────────────┐
│ 🔐 Авторизация                          │
│                                         │
│ [●] Войти через токен                   │
│ [○] Войти через Telegram QR-код         │
│                                         │
│ ┌─────────────────────────────────┐     │
│ │                                 │     │
│ │        [███████████]           │     │
│ │        [██ QR-код ██]          │     │
│ │        [███████████]           │     │
│ │                                 │     │
│ │  Откройте Telegram →           │     │
│ │  Настройки → Устройства →      │     │
│ │  Подключить устройство         │     │
│ │                                 │     │
│ └─────────────────────────────────┘     │
│                                         │
│ Статус: ⏳ Ожидание сканирования...    │
│ [🔄 Обновить]  [❌ Отменить]            │
└─────────────────────────────────────────┘

🔧 Техническая интеграция

Вариант A: Через Telegram Login Widget (официальный)

// Использовать https://core.telegram.org/widgets/login
// После успешного входа получать auth_date, hash, user data
// Верифицировать hash через bot token (HMAC-SHA256)

function verifyTelegramLogin(data: TelegramLoginData, botToken: string): boolean {
  const { auth_date, hash, ...userData } = data;
  const dataCheckString = Object.entries(userData)
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([k, v]) => `${k}=${v}`)
    .join('\n');
  
  const secret = crypto.createHash('sha256').update(botToken).digest();
  const expectedHash = crypto.createHmac('sha256', secret)
    .update(dataCheckString + '\n' + auth_date)
    .digest('hex');
  
  return hash === expectedHash && (Date.now() / 1000 - auth_date) < 86400;
}

Вариант B: Через Telegram Bot API + Deep Linking

// 1. Генерируем unique token и сохраняем в Redis с TTL 5 мин
// 2. Формируем deep link: t.me/YourBot?start=auth_{token}
// 3. Пользователь нажимает на ссылку → бот получает /start auth_{token}
// 4. Бот связывает telegram_user_id с token → обновляет статус в Redis
// 5. WebUI опрашивает статус → получает подтверждение → выдаёт сессию

📋 Чеклист для реализации

  • Создать эндпоинты /api/auth/qr/initiate и /api/auth/qr/status/:id
  • Реализовать генерацию и валидацию QR-данных (HMAC-подпись)
  • Добавить компонент QR-авторизации в WebUI (с fallback на токен)
  • Интегрировать с Telegram Bot API для обработки /start auth_*
  • Добавить защиту от brute-force (rate limit на создание QR)
  • Реализовать автоматическое обновление статуса в реальном времени (SSE/WebSocket)
  • Обновить документацию: docs/AUTH.md с разделом про QR-авторизацию

⚠️ Важные замечания по безопасности

  1. TTL QR-кода: не более 5 минут, чтобы минимизировать окно атаки
  2. Одноразовость: каждый код действителен только для одной авторизации
  3. Rate limiting: не более 3 попыток генерации кода в минуту на один IP
  4. Логирование: все успешные/неуспешные попытки авторизации должны логироваться
  5. Не хранить токены в URL: передавать токены только в теле ответа или через secure cookies

🔄 Обратная совместимость

  • Существующая авторизация через токен остаётся рабочей
  • Пользователь может выбрать метод входа при первом запуске
  • Настройки сохраняются для последующих сессий (remember_method)

💬 Заключение

Добавление QR-авторизации через Telegram:

  • 🚀 Упростит онбординг для новых пользователей
  • 🔐 Повысит безопасность (токен не виден пользователю)
  • 📱 Улучшит опыт на мобильных устройствах
  • 🔗 Укрепит интеграцию с экосистемой Telegram

@konard
Copy link
Copy Markdown
Collaborator Author

konard commented Apr 28, 2026

🤖 AI Work Session Started

Starting automated work session at 2026-04-28T00:23:06.199Z

The PR has been converted to draft mode while work is in progress.

This comment marks the beginning of an AI work session. Please wait for the session to finish, and provide your feedback.

@konard konard marked this pull request as draft April 28, 2026 00:23
@konard konard changed the title [RELEASE] Alpha Web v0.1.0: Implement Web client [RELEASE] Alpha Web v0.1.0: Implement Web client with QR auth Apr 28, 2026
@konard konard marked this pull request as ready for review April 28, 2026 00:35
@konard
Copy link
Copy Markdown
Collaborator Author

konard commented Apr 28, 2026

Solution summary

Implemented and pushed the PR follow-up for Telegram QR login.

PR: #136
Commit: 2f05b36 feat(web): add Telegram QR login

What changed:

  • Added native TDLib QR auth via requestQrCodeAuthentication.
  • Store now tracks authorizationStateWaitOtherDeviceConfirmation.link as an in-memory QR payload.
  • Auth UI now has Phone / QR modes and renders a real QR code.
  • Added docs/AUTH.md, QR screenshots, license-matrix entry for qrcode, and release-test coverage.
  • Updated PR title/body and marked PR 136 ready for review.

Verification:

  • cd web && npm run test
  • cd web && npm run build
  • node --test test/web-alpha-release.test.mjs
  • npm test
  • npm run validate:secrets
  • npm run audit:security
  • npm run validate:foundation
  • npm run validate:release
  • npm run build:debug-artifacts
  • npm run decompose:dry-run
  • Playwright desktop/mobile QR render check with mocked TDWeb

CI is passing on the pushed SHA and the PR merge state is clean. Local preview is running at http://localhost:4173/app/.

Live Telegram QR auth still requires valid VITE_TELEGRAM_API_ID and VITE_TELEGRAM_API_HASH. I based the QR implementation on TDLib’s official docs for requestQrCodeAuthentication and authorizationStateWaitOtherDeviceConfirmation.


This summary was automatically extracted from the AI working session output.

@konard
Copy link
Copy Markdown
Collaborator Author

konard commented Apr 28, 2026

🤖 Solution Draft Log

This log file contains the complete execution trace of the AI solution draft process.

💰 Cost estimation:

  • Model: GPT-5.5
  • Provider: OpenAI
  • Public pricing estimate: $12.978883

📊 Context and tokens usage:

  • 8.8M / 1.1M (837%) input tokens, 30.1K / 128K (23%) output tokens

Total: (315.2K + 8.5M cached) input tokens, 30.1K output tokens, $12.978883 cost

🤖 Models used:

  • Tool: OpenAI Codex
  • Requested: gpt-5.5
  • Model: GPT-5.5 (gpt-5.5)

📎 Log file uploaded as Gist (23239KB)


Now working session is ended, feel free to review and add any feedback on the solution draft.

@konard
Copy link
Copy Markdown
Collaborator Author

konard commented Apr 28, 2026

✅ Ready to merge

This pull request is now ready to be merged:

  • All CI checks have passed
  • No merge conflicts
  • No pending changes

Monitored by hive-mind with --auto-restart-until-mergeable flag

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[RELEASE] Alpha Web v0.1.0: Полная реализация и деплой Web-клиента

2 participants