diff --git a/CHANGELOG.md b/CHANGELOG.md index 7c4bbb4..b97791c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -97,6 +97,14 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje - `CONTRIBUTING.fa.md`: a Persian translation of the contribution guide, with a language switcher in both files like the READMEs (#31). +- `POST /auth/logout` revokes the caller's token (204). An account has a + single active token, so it signs out every client holding it. + +- The dashboard header shows the sign-in state: a **Sign in** button when + signed out, the account email and **Sign out** when signed in. Sign out + revokes the token on the server and works even when the API is + unreachable. The landing page's sign-in button is hidden and the login + page redirects to the upload page for a signed-in user. ### Changed @@ -134,6 +142,10 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje kept as is; a comma in a list of numbers (`4090,4080`) still becomes `،`. The edge cases from #30 (slash dates, Latin digits in Persian sentences, abbreviations, ellipses, repeated marks) are pinned by tests. +- The Telegram bot recovers when the API revokes the token it cached for a + chat (a newer sign-in or a logout of the same account). Every request + used to fail from then on; the bot now drops the token, re-registers + once and retries, and `/start` only shows a connect code that works. ## [1.4.1] - 2026-11-26 diff --git a/backend/sokhan/api/routes_auth.py b/backend/sokhan/api/routes_auth.py index 96ca82c..d08ca94 100644 --- a/backend/sokhan/api/routes_auth.py +++ b/backend/sokhan/api/routes_auth.py @@ -7,16 +7,17 @@ Deliberately lightweight for v1: - POST /auth/telegram lets the bot create or resume an account per Telegram id - POST /auth/token-login lets a user paste the connect code shown by the bot to link their browser session +- POST /auth/logout revokes the caller's token """ import re -from fastapi import APIRouter, Depends, HTTPException, Request, status +from fastapi import APIRouter, Depends, HTTPException, Request, Response, status from pydantic import BaseModel from sqlalchemy import select from sqlalchemy.orm import Session -from sokhan.api.deps import require_bot +from sokhan.api.deps import get_current_user, require_bot from sokhan.auth import generate_token, hash_password, token_hash, verify_password from sokhan.config import get_settings from sokhan.core.throttle import FailureThrottle @@ -132,6 +133,20 @@ def token_login(payload: TokenLogin, session: Session = Depends(get_db)) -> Auth return AuthResponse(id=user.id, email=user.email, api_token=payload.api_token) +@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT) +def logout(user: User = Depends(get_current_user), session: Session = Depends(get_db)) -> Response: + """Revoke the caller's token so it stops working everywhere. + + An account has a single active token, so this signs out every client + that holds it: other browsers, API scripts and, for Telegram accounts, + the bot (which re-registers on its next request). The new token is + never returned; signing in again issues a fresh one. + """ + user.token_hash = token_hash(generate_token()) + session.commit() + return Response(status_code=status.HTTP_204_NO_CONTENT) + + @router.post("/telegram", response_model=AuthResponse, dependencies=[Depends(require_bot)]) def telegram_login(payload: TelegramLogin, session: Session = Depends(get_db)) -> AuthResponse: """Register-or-login used by the Telegram bot. diff --git a/backend/tests/test_auth_flow.py b/backend/tests/test_auth_flow.py index 9489a42..382ec5d 100644 --- a/backend/tests/test_auth_flow.py +++ b/backend/tests/test_auth_flow.py @@ -92,3 +92,40 @@ def test_telegram_login_is_disabled_without_a_configured_secret(client): def test_jobs_require_token(client): response = client.get("/jobs") assert response.status_code == 401 + + +def _bearer(token): + return {"Authorization": f"Bearer {token}"} + + +def test_logout_revokes_the_token(client): + token = client.post("/auth/register", json=REGISTER).json()["api_token"] + assert client.get("/quota", headers=_bearer(token)).status_code == 200 + + response = client.post("/auth/logout", headers=_bearer(token)) + + assert response.status_code == 204 + assert client.get("/quota", headers=_bearer(token)).status_code == 401 + # The revoked token is no longer a valid connect code either. + assert client.post("/auth/token-login", json={"api_token": token}).status_code == 401 + + +def test_logout_twice_with_the_same_token_is_rejected(client): + token = client.post("/auth/register", json=REGISTER).json()["api_token"] + client.post("/auth/logout", headers=_bearer(token)) + + assert client.post("/auth/logout", headers=_bearer(token)).status_code == 401 + + +def test_logout_requires_a_token(client): + assert client.post("/auth/logout").status_code == 401 + + +def test_signing_in_after_logout_issues_a_working_token(client): + first = client.post("/auth/register", json=REGISTER).json()["api_token"] + client.post("/auth/logout", headers=_bearer(first)) + + second = client.post("/auth/login", json=REGISTER).json()["api_token"] + + assert second != first + assert client.get("/quota", headers=_bearer(second)).status_code == 200 diff --git a/bot/sokhan_bot/client.py b/bot/sokhan_bot/client.py index b34331f..57b9edf 100644 --- a/bot/sokhan_bot/client.py +++ b/bot/sokhan_bot/client.py @@ -9,6 +9,10 @@ class BackendError(Exception): pass +class AuthError(BackendError): + """The API rejected the token (401): revoked by a logout or a newer sign-in.""" + + class QuotaError(BackendError): """The user's monthly allowance is exhausted (402, code=quota_exceeded).""" @@ -46,6 +50,11 @@ class SokhanClient: def _headers(self, token: str) -> dict[str, str]: return {"Authorization": f"Bearer {token}"} + @staticmethod + def _raise_for_auth(response: httpx.Response) -> None: + if response.status_code == 401: + raise AuthError("token rejected") + def register_telegram(self, telegram_id: int, username: str | None) -> str: response = self._client.post( f"{self.settings.api_base_url}/auth/telegram", @@ -65,6 +74,7 @@ class SokhanClient: files={"file": (filename, content)}, headers=self._headers(token), ) + self._raise_for_auth(response) if response.status_code == 402: detail = response.json().get("detail", {}) if detail.get("code") == "file_too_long": @@ -82,6 +92,7 @@ class SokhanClient: f"{self.settings.api_base_url}/jobs/{job_id}", headers=self._headers(token), ) + self._raise_for_auth(response) if response.status_code != 200: raise BackendError(f"job fetch failed with status {response.status_code}") return response.json() @@ -91,6 +102,7 @@ class SokhanClient: f"{self.settings.api_base_url}/quota", headers=self._headers(token), ) + self._raise_for_auth(response) if response.status_code != 200: raise BackendError(f"quota fetch failed with status {response.status_code}") return response.json() diff --git a/bot/sokhan_bot/handlers.py b/bot/sokhan_bot/handlers.py index 8982878..bb22620 100644 --- a/bot/sokhan_bot/handlers.py +++ b/bot/sokhan_bot/handlers.py @@ -3,6 +3,8 @@ import io import logging import time +from collections.abc import Callable +from typing import TypeVar from aiogram import Bot, F, Router from aiogram.filters import Command, CommandObject, CommandStart @@ -11,10 +13,17 @@ from aiogram.types import ( InlineKeyboardButton, InlineKeyboardMarkup, Message, + User, ) from sokhan_bot import texts -from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient +from sokhan_bot.client import ( + AuthError, + BackendError, + FileTooLongError, + QuotaError, + SokhanClient, +) from sokhan_bot.split import split_message from sokhan_bot.store import TokenStore @@ -22,6 +31,8 @@ logger = logging.getLogger(__name__) _RATE_LIMIT_SECONDS = 10.0 +T = TypeVar("T") + def _job_keyboard(job_id: str, web_base_url: str) -> InlineKeyboardMarkup: return InlineKeyboardMarkup( @@ -82,10 +93,35 @@ class Handlers: self.store.set(message.chat.id, token) return token + def _authed(self, chat_id: int, user: User, call: Callable[[str], T]) -> T: + """Run `call(token)`, re-registering once if the API revoked the token. + + A web logout or a newer sign-in revokes the token cached for this + chat; without the retry every later request would fail. Raises + BackendError when the backend is unreachable or rejects again. + """ + token = self.store.get(chat_id) + if token: + try: + return call(token) + except AuthError: + logger.info("token for chat %s was revoked; re-registering", chat_id) + self.store.forget(chat_id) + token = self.client.register_telegram(user.id, user.username) + self.store.set(chat_id, token) + return call(token) + async def start(self, message: Message) -> None: token = await self._ensure_token(message) if not token: return + # The cached token doubles as the connect code, so make sure it still + # works before showing it; a backend outage keeps the cached one. + try: + self._authed(message.chat.id, message.from_user, self.client.get_quota) + except BackendError: + pass + token = self.store.get(message.chat.id) or token await message.answer(texts.WELCOME.format(connect_code=token)) async def quota(self, message: Message) -> None: @@ -93,7 +129,7 @@ class Handlers: if not token: return try: - info = self.client.get_quota(token) + info = self._authed(message.chat.id, message.from_user, self.client.get_quota) except BackendError: await message.answer(texts.SERVER_UNREACHABLE) return @@ -137,7 +173,9 @@ class Handlers: await message.answer("شناسهٔ پردازش را بنویس، مثلاً: /track 3f2a…") return try: - job = self.client.get_job(token, job_id) + job = self._authed( + message.chat.id, message.from_user, lambda t: self.client.get_job(t, job_id) + ) except BackendError: await message.answer(texts.UNKNOWN_JOB) return @@ -196,7 +234,11 @@ class Handlers: return try: - job_id = self.client.upload_audio(token, filename, content) + job_id = self._authed( + message.chat.id, + message.from_user, + lambda t: self.client.upload_audio(t, filename, content), + ) except FileTooLongError as exc: await message.answer( texts.FILE_TOO_LONG.format( @@ -229,7 +271,11 @@ class Handlers: job_id = callback.data.split(":", 1)[1] try: - job = self.client.get_job(token, job_id) + job = self._authed( + callback.message.chat.id, + callback.from_user, + lambda t: self.client.get_job(t, job_id), + ) except BackendError: await callback.answer(texts.UNKNOWN_JOB, show_alert=True) return diff --git a/bot/sokhan_bot/notify.py b/bot/sokhan_bot/notify.py index 7d248a8..09b087e 100644 --- a/bot/sokhan_bot/notify.py +++ b/bot/sokhan_bot/notify.py @@ -19,7 +19,7 @@ import time from aiogram import Bot from sokhan_bot import texts -from sokhan_bot.client import SokhanClient +from sokhan_bot.client import AuthError, SokhanClient from sokhan_bot.split import split_message from sokhan_bot.store import TokenStore @@ -75,6 +75,14 @@ class CompletionNotifier: try: job = await asyncio.to_thread(self.client.get_job, token, job_id) + except AuthError: + # Revoked by a web logout or a newer sign-in. The poller has + # no Telegram user to re-register with, so it asks for /start. + logger.warning("token for chat %s was revoked; untracking job %s", chat_id, job_id) + self.store.forget(chat_id) + self.store.untrack(job_id) + await self._send(chat_id, texts.NEED_START) + continue except Exception: logger.exception("job fetch failed (%s); will retry", job_id) continue diff --git a/bot/sokhan_bot/store.py b/bot/sokhan_bot/store.py index cc95b8a..8f7a05a 100644 --- a/bot/sokhan_bot/store.py +++ b/bot/sokhan_bot/store.py @@ -42,6 +42,12 @@ class TokenStore: self._tokens[str(chat_id)] = token self._save() + def forget(self, chat_id: int) -> None: + """Drop a chat's token, e.g. after the API revoked it.""" + with self._lock: + if self._tokens.pop(str(chat_id), None) is not None: + self._save() + def track(self, job_id: str, chat_id: int) -> None: """Watch a job so the notifier can push its transcript when it finishes.""" with self._lock: diff --git a/bot/tests/test_client_errors.py b/bot/tests/test_client_errors.py index d7aa50f..4323918 100644 --- a/bot/tests/test_client_errors.py +++ b/bot/tests/test_client_errors.py @@ -2,7 +2,7 @@ import httpx import pytest -from sokhan_bot.client import BackendError, FileTooLongError, QuotaError, SokhanClient +from sokhan_bot.client import AuthError, BackendError, FileTooLongError, QuotaError, SokhanClient from sokhan_bot.config import BotSettings @@ -106,3 +106,20 @@ def test_register_telegram_sends_the_bot_secret(): with SokhanClient(settings, transport=httpx.MockTransport(handler)) as client: assert client.register_telegram(42, None) == "tok" assert seen["secret"] == "shared" + + +@pytest.mark.parametrize( + "call", + [ + lambda client: client.upload_audio("tok", "voice.ogg", b"bytes"), + lambda client: client.get_job("tok", "job-1"), + lambda client: client.get_quota("tok"), + ], +) +def test_revoked_token_raises_auth_error(call): + def handler(request: httpx.Request) -> httpx.Response: + return httpx.Response(401, json={"detail": "invalid token"}) + + with _client(handler) as client: + with pytest.raises(AuthError): + call(client) diff --git a/bot/tests/test_revoked_token.py b/bot/tests/test_revoked_token.py new file mode 100644 index 0000000..bdc6770 --- /dev/null +++ b/bot/tests/test_revoked_token.py @@ -0,0 +1,128 @@ +"""The bot recovers when the API revokes a chat's cached token (web logout).""" + +import asyncio +from types import SimpleNamespace + +from sokhan_bot import texts +from sokhan_bot.client import AuthError, BackendError +from sokhan_bot.handlers import Handlers +from sokhan_bot.notify import CompletionNotifier +from sokhan_bot.store import TokenStore + + +class FakeClient: + """Accepts only `valid_token`; /auth/telegram hands out `fresh-`.""" + + def __init__(self, valid_token: str) -> None: + self.valid_token = valid_token + self.registrations = 0 + self.settings = SimpleNamespace(web_base_url="http://web.test") + + def _check(self, token: str) -> None: + if token != self.valid_token: + raise AuthError("token rejected") + + def register_telegram(self, telegram_id: int, username: str | None) -> str: + self.registrations += 1 + self.valid_token = f"fresh-{self.registrations}" + return self.valid_token + + def get_quota(self, token: str) -> dict: + self._check(token) + return { + "plan": "free", + "used_minutes": 1.0, + "limit_minutes": 30, + "remaining_minutes": 29.0, + "max_file_minutes": 10, + } + + def get_job(self, token: str, job_id: str) -> dict: + self._check(token) + return {"status": "processing", "progress": 50.0} + + +class FakeMessage: + def __init__(self, chat_id: int = 42) -> None: + self.chat = SimpleNamespace(id=chat_id) + self.from_user = SimpleNamespace(id=chat_id, username="sara") + self.answers: list[str] = [] + + async def answer(self, text: str, **_: object) -> None: + self.answers.append(text) + + +def _handlers(tmp_path, cached_token: str, client: FakeClient) -> Handlers: + store = TokenStore(str(tmp_path / "store.json")) + store.set(42, cached_token) + return Handlers(client, store) + + +def test_quota_re_registers_once_after_the_token_was_revoked(tmp_path): + client = FakeClient(valid_token="current") + handlers = _handlers(tmp_path, "revoked", client) + message = FakeMessage() + + asyncio.run(handlers.quota(message)) + + assert client.registrations == 1 + assert handlers.store.get(42) == "fresh-1" + assert message.answers and texts.SERVER_UNREACHABLE not in message.answers + + +def test_a_valid_token_is_used_without_re_registering(tmp_path): + client = FakeClient(valid_token="current") + handlers = _handlers(tmp_path, "current", client) + + asyncio.run(handlers.quota(FakeMessage())) + + assert client.registrations == 0 + assert handlers.store.get(42) == "current" + + +def test_start_shows_a_working_connect_code_after_revocation(tmp_path): + client = FakeClient(valid_token="current") + handlers = _handlers(tmp_path, "revoked", client) + message = FakeMessage() + + asyncio.run(handlers.start(message)) + + assert "fresh-1" in message.answers[-1] + assert "revoked" not in message.answers[-1] + + +def test_backend_outage_still_reports_unreachable(tmp_path): + client = FakeClient(valid_token="current") + + def unreachable(token: str) -> dict: + raise BackendError("down") + + client.get_quota = unreachable + handlers = _handlers(tmp_path, "current", client) + message = FakeMessage() + + asyncio.run(handlers.quota(message)) + + assert message.answers == [texts.SERVER_UNREACHABLE] + assert client.registrations == 0 + + +def test_poller_untracks_and_asks_for_start_when_revoked(tmp_path): + client = FakeClient(valid_token="current") + store = TokenStore(str(tmp_path / "store.json")) + store.set(42, "revoked") + store.track("job-1", 42) + sent: list[tuple[int, str]] = [] + + notifier = CompletionNotifier(bot=None, client=client, store=store) + + async def fake_send(chat_id: int, text: str) -> bool: + sent.append((chat_id, text)) + return True + + notifier._send = fake_send + asyncio.run(notifier.poll_once()) + + assert store.tracked() == [] + assert store.get(42) is None + assert sent == [(42, texts.NEED_START)] diff --git a/bot/tests/test_store.py b/bot/tests/test_store.py index 6ad6f2a..a88d192 100644 --- a/bot/tests/test_store.py +++ b/bot/tests/test_store.py @@ -47,3 +47,15 @@ def test_legacy_token_file_is_migrated(tmp_path): reloaded = TokenStore(str(path)) assert reloaded.get(123) == "legacy-token" assert [job_id for job_id, _, _ in reloaded.tracked()] == ["job-x"] + + +def test_forget_drops_a_token_and_persists(tmp_path): + path = str(tmp_path / "store.json") + store = TokenStore(path) + store.set(42, "old-token") + + store.forget(42) + store.forget(99) # unknown chats are a no-op + + assert store.get(42) is None + assert TokenStore(path).get(42) is None diff --git a/web/messages/en.json b/web/messages/en.json index 93ba6fd..f7bc669 100644 --- a/web/messages/en.json +++ b/web/messages/en.json @@ -17,7 +17,11 @@ "switchToEn": "English", "switchToFa": "فارسی", "themeToDark": "Switch to dark theme", - "themeToLight": "Switch to light theme" + "themeToLight": "Switch to light theme", + "signIn": "Sign in", + "signOut": "Sign out", + "signedInAs": "Signed in as {email}", + "signOutOf": "Sign out of {email}" }, "landing": { "headline": "From speech to text, in moments", diff --git a/web/messages/fa.json b/web/messages/fa.json index b0653e9..234092a 100644 --- a/web/messages/fa.json +++ b/web/messages/fa.json @@ -17,7 +17,11 @@ "switchToEn": "English", "switchToFa": "فارسی", "themeToDark": "تم تیره", - "themeToLight": "تم روشن" + "themeToLight": "تم روشن", + "signIn": "ورود", + "signOut": "خروج", + "signedInAs": "واردشده با {email}", + "signOutOf": "خروج از حساب {email}" }, "landing": { "headline": "از گفتار به متن، در چند لحظه", diff --git a/web/src/app/[locale]/login/page.tsx b/web/src/app/[locale]/login/page.tsx index 9fa181c..1971d47 100644 --- a/web/src/app/[locale]/login/page.tsx +++ b/web/src/app/[locale]/login/page.tsx @@ -1,9 +1,10 @@ "use client"; -import { useState, type FormEvent } from "react"; +import { useEffect, useState, type FormEvent } from "react"; import { useTranslations } from "next-intl"; import { useRouter } from "@/i18n/navigation"; import { ApiError, login, register, setToken, tokenLogin } from "@/lib/api"; +import { useSession } from "@/lib/session"; type Mode = "login" | "register" | "code"; @@ -13,6 +14,12 @@ export default function LoginPage() { const t = useTranslations("login"); const te = useTranslations("errors"); const router = useRouter(); + const { ready, signedIn } = useSession(); + + // Already signed in: the login form has nothing to offer. + useEffect(() => { + if (ready && signedIn) router.replace("/new"); + }, [ready, signedIn, router]); const [mode, setMode] = useState("login"); const [email, setEmail] = useState(""); @@ -71,8 +78,7 @@ export default function LoginPage() { : mode === "register" ? await register(email.trim(), password) : await tokenLogin(code.trim()); - setToken(result.api_token); - router.push("/new"); + setToken(result.api_token, result.email); } catch (error) { setPending(false); if (error instanceof ApiError) { diff --git a/web/src/app/[locale]/page.tsx b/web/src/app/[locale]/page.tsx index daf34fb..4a4a69e 100644 --- a/web/src/app/[locale]/page.tsx +++ b/web/src/app/[locale]/page.tsx @@ -1,6 +1,7 @@ import { getTranslations, setRequestLocale } from "next-intl/server"; import { ArrowRight, GraduationCap, TextSearch, Voicemail, type LucideIcon } from "lucide-react"; import { Link } from "@/i18n/navigation"; +import { LoginCta } from "@/components/login-cta"; const waveBars = [12, 20, 30, 22, 34, 40, 28, 16, 26, 36, 20, 30, 14, 24, 32, 18, 26, 12, 22, 16]; @@ -69,12 +70,9 @@ export default async function LandingPage({ {t("startCta")}