diff --git a/README.md b/README.md index 586a9b2..a683420 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,13 @@ **голос не передаётся** (Telethon без tgcalls): принявший вызов получает моментальный hangup; статус в RAM (после рестарта сервиса — потерян); - справочники: `contacts_list`, `chat_info`, `chat_participants`; - - текстовый логин: `account_login_start/code/password/status/cancel`. + - текстовый логин: `account_login_start/code/password/status/cancel`; если + Telegram молчит по коду (PHONE_CODE_FLOOD) — **QR-вход** + `account_login_qr_start`: тул возвращает `tg://login?token=…`, пользователь + сканирует (TG → Настройки → Устройства → Слинковать устройство), статус + тот же `account_login_status` (step `awaiting_scan`); 2FA добивается + `account_login_password` тем же маршрутом. В SPA-визарде кнопка + «Вход по QR». - **Ошибки — данные** (`{"error": code, "detail": ...}`), перс. ключи по канону `mcp.md` (≤10 на юзера, снейпшот роли, plaintext один раз, ревок вместо архива), блокировка юзера гасит ключи тем же 401, rate-limit мутаций и логинов, diff --git a/backend/app/api/accounts.py b/backend/app/api/accounts.py index 9d4b98c..21d2eed 100644 --- a/backend/app/api/accounts.py +++ b/backend/app/api/accounts.py @@ -18,6 +18,8 @@ login_cancel, login_code, login_password, + login_qr_start, + login_qr_status, login_start, login_status, ) @@ -68,6 +70,10 @@ password: str = Field(min_length=1, max_length=256) +class QRLoginStart(BaseModel): + label: str = Field(default="", max_length=60) + + @router.get("/accounts") async def list_accounts(request: Request) -> dict: """Свои аккаунты (+живость клиента из пула); гейт карточек UI.""" @@ -114,6 +120,27 @@ raise HTTPException(status_code=exc.code, detail=exc.detail) from exc +@router.post("/accounts/logins/qr") +async def start_login_qr(request: Request, payload: QRLoginStart) -> dict: + """QR-вход: вернуть login_id + tg://login?token (рендер QR на SPA); + коды Telegram не используются (обход PHONE_CODE_FLOOD).""" + session = await require_session(request) + try: + return await login_qr_start(session["user_id"], payload.label.strip()) + except DomainError as exc: + raise HTTPException(status_code=exc.code, detail=exc.detail) from exc + + +@router.get("/accounts/logins/qr/{login_id}") +async def login_qr_state(login_id: str, request: Request) -> dict: + """Poll статуса QR-логина (клиент в RAM ждёт скан непрерывно).""" + session = await require_session(request) + try: + return await login_qr_status(login_id, session["user_id"]) + except DomainError as exc: + raise HTTPException(status_code=exc.code, detail=exc.detail) from exc + + @router.post("/accounts/logins/{login_id}/code") async def submit_code(login_id: str, request: Request, payload: LoginCode) -> dict: session = await require_session(request) diff --git a/backend/app/mcp/server.py b/backend/app/mcp/server.py index 3c4a266..880dbf9 100644 --- a/backend/app/mcp/server.py +++ b/backend/app/mcp/server.py @@ -56,7 +56,7 @@ | «отправь голосовое» | `upload_voice` (base64 или `file_path`) | | «отправь кружок» | `upload_round` (base64 или `file_path`) | | «позвони ему» | `call_start` (сигналинг: ринг у абонента, без аудио) | -| «добавь мой акк / залогинь» | `account_login_start` → `code` → [`password`] | +| «добавь мой акк / залогинь» | `account_login_start` → `code` → [`password`]; если код не приходит — `account_login_qr_start` (QR-вход) | ## Добавление аккаунта (текст-режим — интерактив с человеком) Телевижн-код и пароль 2FA знает только человек; ты не догадываешься и не @@ -69,6 +69,12 @@ Cloud-пароль (2FA): попроси его у пользователя, `account_login_password`. 5. Статус/отмена — `account_login_status` / `account_login_cancel`. Лимиты: ≤3 параллельных логинов, ограничен поток кодов; код живёт ~10 минут. +Если код не приходит (ТГ молчит / PHONE_CODE_FLOOD после частых запросов) — +`account_login_qr_start`: вернёт `qr_url` (``tg://login?token=…``). Покажи +пользователю QR по этому URL или ссылку: Telegram → Настройки → Устройства → +«Слинковать устройство». Статус — тот же `account_login_status` +(step `awaiting_scan` → возможно `awaiting_password` → `done`); токен QR +обновляется сервером (~30 c), не перезапускай логин из-за этого. ## Правила - **Мутации (send/edit/delete/upload/call_start и т.п.) — только по явной diff --git a/backend/app/mcp/tools.py b/backend/app/mcp/tools.py index 1b6c00e..2793f72 100644 --- a/backend/app/mcp/tools.py +++ b/backend/app/mcp/tools.py @@ -36,6 +36,7 @@ login_cancel, login_code, login_password, + login_qr_start, login_start, login_status, ) @@ -714,6 +715,18 @@ @mcp.tool() + async def account_login_qr_start(label: str = "") -> dict: + """🆔 Начать QR-вход: вернуть login_id и qr_url (``tg://login?token=…``). + Покажи пользователю QR или ссылку — Telegram → Настройки → Устройства → + «Слинковать устройство». Коды ТГ не шлём (нет PHONE_CODE_FLOOD) — + первый вариант, если SMS/код не приходит. Статус: account_login_status + (step: awaiting_scan → awaiting_password? → done).""" + if (limited := _login_guard()) is not None: + return limited + return dict(await login_qr_start(current_user_id(), label.strip())) + + + @mcp.tool() async def account_login_code(login_id: str, code: str) -> dict: """🔢 Ввести код из Telegram (или от ошибки: вернётся attempts_left). step 'awaiting_password' — аккаунт под Cloud-паролем 2FA.""" @@ -728,14 +741,16 @@ @mcp.tool() async def account_login_status(login_id: str) -> dict: - """❓ Текущий шаг логина: awaiting_code / awaiting_password / done, - expires_in_sec, last_error. phone_code_hash наружу не отдаётся.""" + """❓ Текущий шаг логина: awaiting_scan (QR: qr_url)/awaiting_code / + awaiting_password / done, expires_in_sec, last_error. + phone_code_hash наружу не отдаётся.""" return await _tool(lambda: login_status(login_id.strip(), current_user_id())) @mcp.tool() async def account_login_cancel(login_id: str) -> dict: - """🚫 Отменить незавершённый логин (клиент disconnect, строка стирается).""" + """🚫 Отменить незавершённый логин: код инвалидидируется у ТГ + (auth.cancelCode); строка стирается, клиент disconnect.""" return await _tool(lambda: _account_login_cancel(login_id)) diff --git a/backend/app/tg/login_flow.py b/backend/app/tg/login_flow.py index 1bd832e..e9fef7c 100644 --- a/backend/app/tg/login_flow.py +++ b/backend/app/tg/login_flow.py @@ -14,6 +14,7 @@ MCP-тулы — в данные {"error": ..., "detail": ...}. """ +import asyncio import uuid from contextlib import suppress from datetime import datetime, timedelta, timezone @@ -48,7 +49,7 @@ def _phone_mask(phone: str) -> str: - return phone[:3] + "***" + phone[-3:] + return phone[:3] + "***" + phone[-3:] if phone else "" async def _require_creds() -> tuple[int, str]: @@ -147,6 +148,7 @@ await db.execute("DELETE FROM login_sessions WHERE id = ?", (login_id,)) await db.commit() await _manager().drop_pending(login_id, disconnect=with_client) + _qr_stop(login_id) # QR-вход: остановить резидентный waiter (если есть) async def login_code(login_id: str, code: str, owner_user_id: str) -> dict: @@ -245,6 +247,8 @@ "step": row["step"], "expires_in_sec": expires_in, } + if row["step"] == "awaiting_scan": + out["qr_url"] = _qr_url(login_id) if row["error"]: out["last_error"] = row["error"] return out @@ -279,6 +283,141 @@ print(f"[login] cancel_code({login_id}) failed: {type(exc).__name__}", flush=True) +# --- QR-вход (Login via QR, обходит лимиты send_code_request/PHONE_CODE_FLOOD) --- + +# токен QRLogin хранится в RAM (токен живёт ~30 с, обновляется waiter'ом); +# waiter — резидентный таск с qr.wait(): его event-хендлер должен быть активен +# ВЕСЬ период ожидания сканирования (иначе UpdateLoginToken будет пропущен). +_qr_logins: dict[str, "object"] = {} # login_id → telethon QRLogin +_qr_tasks: dict[str, asyncio.Task] = {} # login_id → waiter task + + +def _qr_url(login_id: str) -> str: + """Текущий tg://login?token=… для отображения ("" если потерян).""" + qr = _qr_logins.get(login_id) + return qr.url if qr is not None else "" + + +def _qr_stop(login_id: str) -> None: + qr = _qr_logins.pop(login_id, None) + task = _qr_tasks.pop(login_id, None) + if task is not None: + task.cancel() + del qr # token RAM-объекта собирается GC вместе с клиентом + + +async def login_qr_start(owner_user_id: str, label: str = "") -> dict: + """Начать QR-вход: свежий клиент + auth.exportLoginToken (через qr_login). + + Лимит тот же: ≤3 активных pending. Токен QR (~30 с) обновляет фоновый + waiter; после скана (Telegram → Настройки → Устройства → Слинковать) + waiter финализирует аккаунт сам. Коды ТГ не используются — флуда нет. + """ + await _require_creds() + manager = _manager() + db = get_db() + cursor = await db.execute( + "SELECT COUNT(*) AS n FROM login_sessions WHERE user_id = ?", (owner_user_id,) + ) + if (await cursor.fetchone())["n"] >= 3: + raise DomainError(409, "too many pending logins (max 3) — cancel or wait for expiry") + + client = TelegramClientWithSession(get_settings().api_id, get_settings().api_hash) + await client.connect() + if not client.is_connected(): + await client.disconnect() + raise DomainError(503, "cannot connect to telegram") + try: + qr = await client.qr_login() + except Exception as exc: # noqa: BLE001 + await client.disconnect() + raise DomainError(503, f"qr login unavailable: {type(exc).__name__}") from exc + + login_id = uuid.uuid4().hex + await db.execute( + "INSERT INTO login_sessions (id, user_id, phone, label, phone_code_hash, step," + " expires_at, created_at) VALUES (?, ?, '', ?, '', 'awaiting_scan', ?, ?)", + (login_id, owner_user_id, label[:60], _expires_iso(), now_iso()), + ) + await db.commit() + manager.put_pending(login_id, client) + _qr_logins[login_id] = qr + _qr_tasks[login_id] = asyncio.create_task( + _qr_waiter(login_id, client, owner_user_id) + ) + return { + "login_id": login_id, + "step": "awaiting_scan", + "qr_url": qr.url, + "expires_at": _expires_iso(), + "hint": "Telegram → Настройки → Устройства → Слинковать устройство (отсканируйте QR)", + } + + +async def _qr_waiter(login_id: str, client, owner_user_id: str) -> None: + """Резидентное ожидание QR: qr.wait() держит хендлер UpdateLoginToken + активным всё время (если таск спит — обновление будет пропущено). + Токен истёк/recreate — новый URL в RAM; скан принят (Success) → finalize + (телефон достаётся из get_me). 2FA → step=awaiting_password, агент/SPA + добивают через обычный login_password.""" + manager = _manager() + db = get_db() + try: + while True: + try: + qr = _qr_logins.get(login_id) + if qr is None: + return + user = await qr.wait() # блокируется до скана/истечения токена + break + except (asyncio.TimeoutError, TimeoutError): + # токен умер — сгенерировать новый и ждать дальше + try: + await qr.recreate() + except Exception as exc: # noqa: BLE001 + print(f"[login] qr recreate({login_id}): {type(exc).__name__}", flush=True) + return + except errors.SessionPasswordNeededError: + await db.execute( + "UPDATE login_sessions SET step = 'awaiting_password', error = ''," + " attempts = 0, expires_at = ? WHERE id = ?", + (_expires_iso(), login_id), + ) + await db.commit() + return # добивает login_password + except errors.FloodWaitError as exc: + print(f"[login] qr waiter flood({login_id}): {exc.seconds}s", flush=True) + return + except asyncio.CancelledError: + return # cancelled by _qr_stop (cancel/cleanup) + + cursor = await db.execute("SELECT * FROM login_sessions WHERE id = ?", (login_id,)) + row = await cursor.fetchone() + if row is None: + return # отмена/сгорание прилетели раньше скана + me = await client.get_me() + phone = str(me.phone) if getattr(me, "phone", None) else "" + await db.execute( + "UPDATE login_sessions SET phone = ? WHERE id = ?", (phone, login_id), + ) + await db.commit() + row = dict(row) + row["phone"] = phone + await _finalize(db, manager, login_id, row, client) + except asyncio.CancelledError: + pass + except Exception as exc: # noqa: BLE001 — waiter не роняет процесс + print(f"[login] qr waiter({login_id}) error: {type(exc).__name__}: {exc}", flush=True) + finally: + _qr_logins.pop(login_id, None) + _qr_tasks.pop(login_id, None) + + +async def login_qr_status(login_id: str, owner_user_id: str) -> dict: + """Текущее состояние QR-логина (SPA poll и MCP-агент).""" + return await login_status(login_id, owner_user_id) + + async def _finalize(db, manager: AccountManager, login_id: str, row, client) -> None: """Успешный логин: get_me → session_data → upsert accounts → cleanup.""" me = await client.get_me() @@ -350,6 +489,13 @@ async def send_code_request(self, phone: str): # noqa: ANN201 return await self._client.send_code_request(phone) + async def qr_login(self): # noqa: ANN201 + """auth.exportLoginToken: telethon QRLogin (url/recreate/wait).""" + return await self._client.qr_login() + + def is_connected(self) -> bool: + return self._client.is_connected() + async def sign_in(self, *args, **kwargs): # noqa: ANN002, ANN003 return await self._client.sign_in(*args, **kwargs) diff --git a/frontend/package-lock.json b/frontend/package-lock.json index d2c277c..31c50fe 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -9,6 +9,7 @@ "version": "0.1.0", "dependencies": { "gnexus-ui-kit": "git+https://git.gnexus.space/git/root/gnexus-ui-kit.git#master", + "qrcode": "^1.5.4", "vue": "^3.5.0", "vue-router": "^4.4.0" }, @@ -994,12 +995,95 @@ "integrity": "sha512-uksS7YGMR5NZyr4JNq0Rp+QyLns0ueaz20KwzIPW9R0LH1Vnt4E+XUM29PNseEbf1www2gOuhuDi5AKOIXag9Q==", "license": "MIT" }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "license": "ISC", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "license": "MIT" + }, "node_modules/csstype": { "version": "3.2.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", "license": "MIT" }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==", + "license": "MIT" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", + "license": "MIT" + }, "node_modules/entities": { "version": "7.0.1", "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz", @@ -1057,6 +1141,19 @@ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==", "license": "MIT" }, + "node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "license": "MIT", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -1072,6 +1169,15 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, "node_modules/gnexus-ui-kit": { "version": "1.0.0", "resolved": "git+https://git.gnexus.space/git/root/gnexus-ui-kit.git#e28f382b7bbf405f9f33e9f5d5b53ad64c1aabf3", @@ -1085,6 +1191,27 @@ } } }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "license": "MIT", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/magic-string": { "version": "0.30.21", "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", @@ -1112,12 +1239,66 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, + "node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "license": "MIT", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "license": "MIT", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/picocolors": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", "license": "ISC" }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "license": "MIT", + "engines": { + "node": ">=10.13.0" + } + }, "node_modules/postcss": { "version": "8.5.29", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz", @@ -1146,6 +1327,38 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/require-main-filename": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "license": "ISC" + }, "node_modules/rollup": { "version": "4.64.0", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.0.tgz", @@ -1192,6 +1405,12 @@ "fsevents": "~2.3.2" } }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", + "license": "ISC" + }, "node_modules/source-map-js": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", @@ -1201,6 +1420,32 @@ "node": ">=0.10.0" } }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, "node_modules/vite": { "version": "5.4.21", "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz", @@ -1296,6 +1541,67 @@ "peerDependencies": { "vue": "^3.5.0" } + }, + "node_modules/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==", + "license": "ISC" + }, + "node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==", + "license": "ISC" + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "license": "MIT", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "license": "ISC", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } } } } diff --git a/frontend/package.json b/frontend/package.json index 7db1b95..29089cf 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -10,6 +10,7 @@ }, "dependencies": { "gnexus-ui-kit": "git+https://git.gnexus.space/git/root/gnexus-ui-kit.git#master", + "qrcode": "^1.5.4", "vue": "^3.5.0", "vue-router": "^4.4.0" }, @@ -20,4 +21,4 @@ "allowScripts": { "esbuild@0.21.5": true } -} \ No newline at end of file +} diff --git a/frontend/src/api.js b/frontend/src/api.js index f0d1c3f..3921505 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -46,6 +46,10 @@ accounts: () => request('/accounts'), startLogin: (phone, label = '') => request('/accounts/logins', { method: 'POST', body: { phone, label } }), + // QR-вход: коды ТГ не используются (нет SMS-флуда) + startQrLogin: (label = '') => + request('/accounts/logins/qr', { method: 'POST', body: { label } }), + qrLoginState: (loginId) => request(`/accounts/logins/qr/${loginId}`), loginState: (loginId) => request(`/accounts/logins/${loginId}`), submitLoginCode: (loginId, code) => request(`/accounts/logins/${loginId}/code`, { method: 'POST', body: { code } }), diff --git a/frontend/src/i18n/messages/en.js b/frontend/src/i18n/messages/en.js index 5da6f68..cd22975 100644 --- a/frontend/src/i18n/messages/en.js +++ b/frontend/src/i18n/messages/en.js @@ -81,6 +81,8 @@ 'wizard.attemptsLeft': 'Attempts left: {n}', 'wizard.wrongCode': 'Invalid code', 'wizard.wrongPassword': 'Invalid password', + 'wizard.viaQr': 'Scan QR instead', + 'wizard.qrHint': 'Open Telegram → Settings → Devices → “Link desktop device” and scan the QR. No SMS code needed', 'wizard.cancelFailed': 'Failed to cancel the login', 'wizard.cancel': 'Cancel login', 'wizard.expired': 'Login window expired — start again', diff --git a/frontend/src/i18n/messages/ru.js b/frontend/src/i18n/messages/ru.js index 838ca24..252e07a 100644 --- a/frontend/src/i18n/messages/ru.js +++ b/frontend/src/i18n/messages/ru.js @@ -81,6 +81,8 @@ 'wizard.attemptsLeft': 'Осталось попыток: {n}', 'wizard.wrongCode': 'Неверный код', 'wizard.wrongPassword': 'Неверный пароль', + 'wizard.viaQr': 'Вход по QR', + 'wizard.qrHint': 'Открой Telegram → Настройки → Устройства → «Слинковать устройство» — и отсканируй QR. Код по SMS не нужен', 'wizard.cancelFailed': 'Не удалось отменить логин', 'wizard.cancel': 'Отменить логин', 'wizard.expired': 'Время логина истекло — начните заново', diff --git a/frontend/src/i18n/messages/uk.js b/frontend/src/i18n/messages/uk.js index 7a0c530..8cf5ecc 100644 --- a/frontend/src/i18n/messages/uk.js +++ b/frontend/src/i18n/messages/uk.js @@ -81,6 +81,8 @@ 'wizard.attemptsLeft': 'Залишилось спроб: {n}', 'wizard.wrongCode': 'Невірний код', 'wizard.wrongPassword': 'Невірний пароль', + 'wizard.viaQr': 'Вхід за QR', + 'wizard.qrHint': 'Відкрий Telegram → Налаштування → Пристрої → «Звʼязати пристрій» — і відскануй QR. Код за SMS не потрібен', 'wizard.cancelFailed': 'Не вдалося скасувати логін', 'wizard.cancel': 'Скасувати логін', 'wizard.expired': 'Час логіна минув — почніть знову', diff --git a/frontend/src/pages/LoginWizard.vue b/frontend/src/pages/LoginWizard.vue index f03057b..42720a2 100644 --- a/frontend/src/pages/LoginWizard.vue +++ b/frontend/src/pages/LoginWizard.vue @@ -1,8 +1,10 @@