Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9a74cca685
|
||
|
|
0deafa4cdf
|
||
|
|
b2386acdd1
|
||
|
|
7a3dab88c8
|
||
|
|
752c972669
|
||
|
|
9ba610d081
|
No files matched your search
+17
-2
@@ -94,6 +94,17 @@ MAX_UPLOAD_MB=200
|
||||
# (POST /admin/users/{email}/plan). Leave empty to disable the admin surface.
|
||||
ADMIN_API_KEY=
|
||||
|
||||
# --- Dashboard session cookie ---
|
||||
# The web dashboard signs in with an httpOnly cookie instead of keeping the
|
||||
# API token in localStorage. It reaches the API through its own /api path,
|
||||
# so the cookie is first-party on any host. AUTH_COOKIE_SECURE=auto marks it
|
||||
# Secure whenever the browser uses HTTPS (directly or via a proxy setting
|
||||
# X-Forwarded-Proto); true/false force it. SameSite=none (with HTTPS) is only
|
||||
# needed when NEXT_PUBLIC_API_BASE points at an API on a different site.
|
||||
AUTH_COOKIE_SECURE=auto
|
||||
AUTH_COOKIE_SAMESITE=lax
|
||||
AUTH_COOKIE_MAX_AGE_DAYS=30
|
||||
|
||||
# --- LLM summaries (optional) ---
|
||||
# Any OpenAI-compatible chat-completions endpoint works.
|
||||
# Set SUMMARY_ENABLED=true and provide a key to turn summaries on.
|
||||
@@ -113,8 +124,12 @@ WEB_BASE_URL=http://localhost:3000
|
||||
API_BASE_URL=http://localhost:8000
|
||||
|
||||
# --- Web ---
|
||||
# Browser-facing API base URL used by the Next.js app.
|
||||
NEXT_PUBLIC_API_BASE=http://localhost:8000
|
||||
# Browser-facing API base URL, baked into the web build. Leave empty: the
|
||||
# dashboard then calls /api on its own origin, which the web server proxies
|
||||
# to API_PROXY_TARGET. Set it only when the API is served from its own host
|
||||
# (that also needs SOKHAN_CORS_ORIGINS and AUTH_COOKIE_SAMESITE=none).
|
||||
NEXT_PUBLIC_API_BASE=
|
||||
API_PROXY_TARGET=http://api:8000
|
||||
|
||||
# --- Job-completion webhooks (optional) ---
|
||||
# Jobs uploaded with a callback_url get a POST when they finish. The payload
|
||||
|
||||
+40
-5
@@ -5,6 +5,30 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Security
|
||||
|
||||
- Sign-in through the dashboard flows (register, login, connect code) now
|
||||
also sets the token as an `HttpOnly; SameSite=lax` session cookie
|
||||
(`Secure` whenever the browser uses HTTPS), and the API accepts it in place of a bearer header. Every
|
||||
cookie-authenticated write must send the session's CSRF token in
|
||||
`X-CSRF-Token` (403 otherwise); the token is an HMAC of the session
|
||||
token, so nothing extra is stored. `GET /auth/session` returns the
|
||||
signed-in account and its CSRF token, and logout clears the cookie.
|
||||
Bearer auth (bot, API scripts, OpenAI-compatible clients) is unchanged
|
||||
and needs no CSRF token. New settings: `AUTH_COOKIE_SECURE`
|
||||
(`auto`/`true`/`false`), `AUTH_COOKIE_SAMESITE`,
|
||||
`AUTH_COOKIE_MAX_AGE_DAYS`. CORS now allows credentials for the
|
||||
configured `SOKHAN_CORS_ORIGINS` (#33).
|
||||
- The dashboard no longer keeps the API token in `localStorage`, where an
|
||||
XSS could read it (CodeQL `js/clear-text-storage-of-sensitive-data`). It
|
||||
relies on the httpOnly session cookie, sends the CSRF token on writes,
|
||||
learns who is signed in from `GET /auth/session`, and wipes the token
|
||||
earlier versions left in `localStorage`. The dashboard reaches the API
|
||||
through its own `/api` path, proxied by the web server to
|
||||
`API_PROXY_TARGET`, so the cookie is first-party on localhost, 127.0.0.1,
|
||||
a LAN address or a domain alike; `NEXT_PUBLIC_API_BASE` now defaults to
|
||||
empty and is only for an API on its own host (#33).
|
||||
|
||||
### Added
|
||||
|
||||
- **Persian accuracy stack (v2)** — measured on the 12-clip Common Voice
|
||||
@@ -37,11 +61,6 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
fine-tuned 0.75 / medium 0.5625); the weekly benchmark workflow now
|
||||
guards `small` **and** `medium`; regression-gate test updated to the
|
||||
committed baseline.
|
||||
- Dashboard dark mode: a sun/moon toggle in the header, defaulting to the OS
|
||||
preference until the user picks one (saved in localStorage, applied before
|
||||
first paint so there is no flash). Implemented by remapping the Tailwind
|
||||
palette under `html.dark` in `globals.css`, so existing pages needed no
|
||||
per-class changes.
|
||||
- Brand refresh: a hero banner in both READMEs (`docs/assets/banner.png`),
|
||||
a redesigned 1280x640 social preview (`docs/assets/social-preview.png` —
|
||||
upload it once in Settings → General → Social preview) and a 512px app
|
||||
@@ -57,6 +76,15 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
and duration caps: 30 min on WebGPU, 10 min on WASM, 60 MB per file —
|
||||
no input can wedge the demo at an eternal "processing" state anymore.
|
||||
|
||||
- `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
|
||||
|
||||
- **Demo hang fix**: audio was decoded inside an `AudioContext` forced to
|
||||
@@ -79,6 +107,13 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
pyproject.toml files, web/package.json, the landing site copy, the demo
|
||||
Space metadata and the fine-tuned model card.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 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
|
||||
|
||||
### Security
|
||||
|
||||
+6
-5
@@ -177,10 +177,10 @@ docker pull ghcr.io/abolfazlrwm/sokhan-web:latest
|
||||
خودش نوشته: با `up -d --build` لوکال بسازید، یا با
|
||||
`docker compose -f deploy/docker-compose.yml pull` و `up -d --no-build`
|
||||
ایمیجهای منتشرشده را اجرا کنید. نسخههای پینشده تابع تگهای گیت هستند
|
||||
(مثل `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). توجه: ایمیج وب مقدار
|
||||
`NEXT_PUBLIC_API_BASE` (پیشفرض `http://localhost:8000`) را موقع build
|
||||
میگیرد — دیپلویهایی که داشبورد را از origin دیگری سرو میکنند باید خودشان
|
||||
این build argument را بدهند.
|
||||
(مثل `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). داشبورد API را از
|
||||
مسیر `/api` روی همان origin خودش صدا میزند و وبسرور آن را به
|
||||
`API_PROXY_TARGET` (پیشفرض `http://api:8000`، موقع build) پراکسی میکند؛
|
||||
برای همین یک ایمیج روی هر هاست یا دامنهای کار میکند.
|
||||
|
||||
## توسعه
|
||||
|
||||
@@ -230,7 +230,8 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py
|
||||
| `TELEGRAM_BOT_TOKEN` | خالی | فعالسازی فرایند ربات |
|
||||
| `WEB_BASE_URL` | `http://localhost:3000` | لینکهایی که ربات میفرستد |
|
||||
| `API_BASE_URL` | `http://localhost:8000` | آدرس API که ربات صدا میزند |
|
||||
| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | آدرس API که اپ وب صدا میزند (زمان build) |
|
||||
| `NEXT_PUBLIC_API_BASE` | خالی (همان origin، `/api`) | آدرس API که اپ وب صدا میزند، فقط وقتی API روی هاست جدا است (زمان build) |
|
||||
| `API_PROXY_TARGET` | `http://api:8000` | مقصد پراکسی `/api` در وبسرور (زمان build) |
|
||||
|
||||
فهرست کامنتدار در [.env.example](.env.example).
|
||||
|
||||
|
||||
@@ -176,10 +176,10 @@ docker pull ghcr.io/abolfazlrwm/sokhan-web:latest
|
||||
`build:` blocks: keep `up -d --build` to build locally, or
|
||||
`docker compose -f deploy/docker-compose.yml pull` and
|
||||
`up -d --no-build` to run the published images. Pinned versions follow the
|
||||
git tags (e.g. `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). Note the web image
|
||||
bakes `NEXT_PUBLIC_API_BASE` (default `http://localhost:8000`) at build
|
||||
time — deployments serving the dashboard from another origin pass the
|
||||
build argument themselves.
|
||||
git tags (e.g. `ghcr.io/abolfazlrwm/sokhan-api:1.2.0`). The dashboard calls
|
||||
the API through its own `/api` path, which the web server proxies to
|
||||
`API_PROXY_TARGET` (default `http://api:8000`, baked at build time), so one
|
||||
image works on any host or domain.
|
||||
|
||||
## Development
|
||||
|
||||
@@ -229,7 +229,8 @@ SOKHAN_REAL_MODEL_TEST=1 pytest backend/tests/test_real_model.py
|
||||
| `TELEGRAM_BOT_TOKEN` | empty | enables the bot process |
|
||||
| `WEB_BASE_URL` | `http://localhost:3000` | links the bot sends |
|
||||
| `API_BASE_URL` | `http://localhost:8000` | API address the bot calls |
|
||||
| `NEXT_PUBLIC_API_BASE` | `http://localhost:8000` | API address the web app calls (build-time) |
|
||||
| `NEXT_PUBLIC_API_BASE` | empty (same-origin `/api`) | API address the web app calls, only for an API on its own host (build-time) |
|
||||
| `API_PROXY_TARGET` | `http://api:8000` | Where the web server proxies `/api` (build-time) |
|
||||
|
||||
See [.env.example](.env.example) for the commented list.
|
||||
|
||||
|
||||
+2
-1
@@ -38,7 +38,8 @@ silence:
|
||||
which uses scrypt).
|
||||
3. **Track as an issue** — when a fix needs design work (for example
|
||||
moving the dashboard token from localStorage to an httpOnly cookie
|
||||
implies a CSRF layer and is roadmap work, not a drive-by patch).
|
||||
implied a CSRF layer: it was tracked as #33 and has since shipped, so
|
||||
the dashboard no longer keeps the token in script-readable storage).
|
||||
|
||||
Dismissed alerts stay visible in the Security tab with their
|
||||
justification, so the reasoning is auditable rather than hidden.
|
||||
@@ -1,29 +1,59 @@
|
||||
"""Shared FastAPI dependencies: database session, current user and admin key."""
|
||||
"""Shared FastAPI dependencies: database session, current user and admin key.
|
||||
|
||||
A request authenticates in one of two ways:
|
||||
|
||||
- `Authorization: Bearer <token>`: API clients, the bot and scripts. A
|
||||
browser never attaches this header on its own, so no CSRF check applies.
|
||||
- the httpOnly session cookie set at sign-in: the web dashboard. Browsers
|
||||
send it automatically, so every unsafe method must also carry the
|
||||
matching X-CSRF-Token header (see `sokhan.auth.csrf_token_for`).
|
||||
"""
|
||||
|
||||
import secrets
|
||||
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
from fastapi import Depends, Header, HTTPException, Request, status
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from sokhan.auth import token_hash
|
||||
from sokhan.auth import csrf_token_for, token_hash
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.db import get_db
|
||||
from sokhan.models import User
|
||||
|
||||
_bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
SESSION_COOKIE = "sokhan_session"
|
||||
CSRF_HEADER = "X-CSRF-Token"
|
||||
_SAFE_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
|
||||
|
||||
|
||||
def get_request_token(
|
||||
request: Request,
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
) -> str:
|
||||
"""The caller's raw token, from the bearer header or the session cookie.
|
||||
|
||||
Cookie-authenticated unsafe requests must send the CSRF token; a
|
||||
missing or wrong one is a 403 before the token is even looked up.
|
||||
"""
|
||||
if credentials is not None and credentials.credentials:
|
||||
return credentials.credentials
|
||||
token = request.cookies.get(SESSION_COOKIE)
|
||||
if not token:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token")
|
||||
if request.method not in _SAFE_METHODS:
|
||||
sent = request.headers.get(CSRF_HEADER, "")
|
||||
if not secrets.compare_digest(sent, csrf_token_for(token)):
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN, "missing or invalid CSRF token")
|
||||
return token
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials | None = Depends(_bearer),
|
||||
token: str = Depends(get_request_token),
|
||||
session: Session = Depends(get_db),
|
||||
) -> User:
|
||||
if credentials is None or not credentials.credentials:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token")
|
||||
user = session.scalar(
|
||||
select(User).where(User.token_hash == token_hash(credentials.credentials))
|
||||
)
|
||||
user = session.scalar(select(User).where(User.token_hash == token_hash(token)))
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid token")
|
||||
return user
|
||||
|
||||
@@ -7,19 +7,34 @@ 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
|
||||
- GET /auth/session tells the dashboard who is signed in
|
||||
|
||||
Sign-in through the web flows (register, login, token-login) also sets the
|
||||
token as an httpOnly session cookie, so the dashboard never has to keep it
|
||||
in script-readable storage. The JSON body still carries `api_token` for API
|
||||
clients and the bot.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, 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.auth import generate_token, hash_password, token_hash, verify_password
|
||||
from sokhan.api.deps import SESSION_COOKIE, get_current_user, get_request_token
|
||||
from sokhan.auth import (
|
||||
csrf_token_for,
|
||||
generate_token,
|
||||
hash_password,
|
||||
token_hash,
|
||||
verify_password,
|
||||
)
|
||||
from sokhan.config import get_settings
|
||||
from sokhan.db import get_db
|
||||
from sokhan.models import User
|
||||
from sokhan.schemas import AuthResponse
|
||||
from sokhan.schemas import AuthResponse, SessionOut
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
@@ -59,8 +74,58 @@ def _validate_credentials(email: str, password: str) -> str:
|
||||
return email
|
||||
|
||||
|
||||
def _cookie_is_secure(request: Request) -> bool:
|
||||
"""Whether the session cookie gets the Secure attribute.
|
||||
|
||||
`auto` (the default) follows the scheme the browser used: HTTPS directly
|
||||
or behind a proxy that sets X-Forwarded-Proto. Browsers drop a Secure
|
||||
cookie that arrives over plain http (Safari even on localhost), which
|
||||
left plain-http installs unable to stay signed in.
|
||||
"""
|
||||
mode = get_settings().auth_cookie_secure.strip().lower()
|
||||
if mode in ("true", "1", "yes"):
|
||||
return True
|
||||
if mode in ("false", "0", "no"):
|
||||
return False
|
||||
forwarded = request.headers.get("x-forwarded-proto", "").split(",")[0].strip().lower()
|
||||
return request.url.scheme == "https" or forwarded == "https"
|
||||
|
||||
|
||||
def _start_session(request: Request, response: Response, user: User, token: str) -> AuthResponse:
|
||||
"""Set the httpOnly session cookie and answer with the CSRF token."""
|
||||
settings = get_settings()
|
||||
response.set_cookie(
|
||||
SESSION_COOKIE,
|
||||
token,
|
||||
max_age=settings.auth_cookie_max_age_days * 24 * 3600,
|
||||
path="/",
|
||||
httponly=True,
|
||||
secure=_cookie_is_secure(request),
|
||||
samesite=settings.auth_cookie_samesite,
|
||||
)
|
||||
return AuthResponse(
|
||||
id=user.id, email=user.email, api_token=token, csrf_token=csrf_token_for(token)
|
||||
)
|
||||
|
||||
|
||||
def _end_session(request: Request, response: Response) -> None:
|
||||
settings = get_settings()
|
||||
response.delete_cookie(
|
||||
SESSION_COOKIE,
|
||||
path="/",
|
||||
httponly=True,
|
||||
secure=_cookie_is_secure(request),
|
||||
samesite=settings.auth_cookie_samesite,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/register", response_model=AuthResponse)
|
||||
def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
def register(
|
||||
payload: Credentials,
|
||||
request: Request,
|
||||
response: Response,
|
||||
session: Session = Depends(get_db),
|
||||
) -> AuthResponse:
|
||||
email = _validate_credentials(payload.email, payload.password)
|
||||
if session.scalar(select(User).where(User.email == email)):
|
||||
raise HTTPException(status.HTTP_409_CONFLICT, "email already registered")
|
||||
@@ -73,11 +138,16 @@ def register(payload: Credentials, session: Session = Depends(get_db)) -> AuthRe
|
||||
)
|
||||
session.add(user)
|
||||
session.commit()
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=token)
|
||||
return _start_session(request, response, user, token)
|
||||
|
||||
|
||||
@router.post("/login", response_model=AuthResponse)
|
||||
def login(payload: Credentials, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
def login(
|
||||
payload: Credentials,
|
||||
request: Request,
|
||||
response: Response,
|
||||
session: Session = Depends(get_db),
|
||||
) -> AuthResponse:
|
||||
email = payload.email.strip().lower()
|
||||
user = session.scalar(select(User).where(User.email == email))
|
||||
if user is None or not verify_password(payload.password, user.password_hash):
|
||||
@@ -86,15 +156,52 @@ def login(payload: Credentials, session: Session = Depends(get_db)) -> AuthRespo
|
||||
token = generate_token()
|
||||
user.token_hash = token_hash(token)
|
||||
session.commit()
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=token)
|
||||
return _start_session(request, response, user, token)
|
||||
|
||||
|
||||
@router.post("/token-login", response_model=AuthResponse)
|
||||
def token_login(payload: TokenLogin, session: Session = Depends(get_db)) -> AuthResponse:
|
||||
def token_login(
|
||||
payload: TokenLogin,
|
||||
request: Request,
|
||||
response: Response,
|
||||
session: Session = Depends(get_db),
|
||||
) -> AuthResponse:
|
||||
user = session.scalar(select(User).where(User.token_hash == token_hash(payload.api_token)))
|
||||
if user is None:
|
||||
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "invalid connect code")
|
||||
return AuthResponse(id=user.id, email=user.email, api_token=payload.api_token)
|
||||
return _start_session(request, response, user, payload.api_token)
|
||||
|
||||
|
||||
@router.get("/session", response_model=SessionOut)
|
||||
def current_session(
|
||||
user: User = Depends(get_current_user), token: str = Depends(get_request_token)
|
||||
) -> SessionOut:
|
||||
"""Who is signed in, plus the CSRF token for this session.
|
||||
|
||||
The dashboard cannot read its httpOnly cookie, so it asks here after a
|
||||
reload; a 401 means signed out.
|
||||
"""
|
||||
return SessionOut(id=user.id, email=user.email, csrf_token=csrf_token_for(token))
|
||||
|
||||
|
||||
@router.post("/logout", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def logout(
|
||||
request: Request,
|
||||
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()
|
||||
response = Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
_end_session(request, response)
|
||||
return response
|
||||
|
||||
|
||||
@router.post("/telegram", response_model=AuthResponse)
|
||||
|
||||
@@ -40,3 +40,13 @@ def generate_token() -> str:
|
||||
|
||||
def token_hash(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def csrf_token_for(token: str) -> str:
|
||||
"""The CSRF token bound to a session token (stateless double submit).
|
||||
|
||||
It is an HMAC keyed by the session token itself, so the server can
|
||||
recompute it from the cookie without storing anything, and a cross-site
|
||||
page that cannot read the cookie cannot derive it either.
|
||||
"""
|
||||
return hmac.new(token.encode("utf-8"), b"sokhan-csrf-v1", hashlib.sha256).hexdigest()
|
||||
@@ -74,6 +74,15 @@ class Settings(BaseSettings):
|
||||
# Leave empty to disable the admin endpoints entirely.
|
||||
admin_api_key: str = ""
|
||||
|
||||
# Dashboard session cookie (httpOnly). AUTH_COOKIE_SECURE=auto sets the
|
||||
# Secure attribute whenever the browser came in over HTTPS (directly or
|
||||
# via X-Forwarded-Proto); true/false force it. The web app proxies the
|
||||
# API under its own origin (/api), so SameSite=lax always applies; a
|
||||
# separately hosted API on another site needs "none" plus HTTPS.
|
||||
auth_cookie_secure: str = "auto"
|
||||
auth_cookie_samesite: str = "lax"
|
||||
auth_cookie_max_age_days: int = 30
|
||||
|
||||
# LLM summaries (optional, behind a feature flag)
|
||||
summary_enabled: bool = False
|
||||
llm_api_base: str = ""
|
||||
|
||||
@@ -55,7 +55,9 @@ def create_app() -> FastAPI:
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_origins,
|
||||
allow_credentials=False,
|
||||
# The dashboard's session cookie rides on credentialed requests; the
|
||||
# origins above are an explicit list, never a wildcard.
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
@@ -9,6 +9,15 @@ class AuthResponse(BaseModel):
|
||||
id: str
|
||||
email: str
|
||||
api_token: str
|
||||
# Sent back as X-CSRF-Token on cookie-authenticated writes; absent for
|
||||
# flows that set no cookie (the Telegram bot).
|
||||
csrf_token: str | None = None
|
||||
|
||||
|
||||
class SessionOut(BaseModel):
|
||||
id: str
|
||||
email: str
|
||||
csrf_token: str
|
||||
|
||||
|
||||
class JobCreated(BaseModel):
|
||||
|
||||
@@ -62,3 +62,40 @@ def test_telegram_register_or_login(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
|
||||
@@ -0,0 +1,113 @@
|
||||
"""httpOnly cookie sessions for the dashboard, with CSRF on writes (#33)."""
|
||||
|
||||
import pytest
|
||||
from sokhan.auth import csrf_token_for
|
||||
from sokhan.config import get_settings
|
||||
|
||||
CREDENTIALS = {"email": "nima@example.com", "password": "parool-1234"}
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def cookie_client(client, monkeypatch):
|
||||
"""The test client speaks plain http, which never sends Secure cookies."""
|
||||
monkeypatch.setenv("AUTH_COOKIE_SECURE", "false")
|
||||
get_settings.cache_clear()
|
||||
return client
|
||||
|
||||
|
||||
def _sign_in(client) -> dict:
|
||||
client.post("/auth/register", json=CREDENTIALS)
|
||||
return client.post("/auth/login", json=CREDENTIALS).json()
|
||||
|
||||
|
||||
def test_login_sets_an_httponly_session_cookie(cookie_client):
|
||||
response = cookie_client.post("/auth/register", json=CREDENTIALS)
|
||||
|
||||
cookie = response.headers["set-cookie"]
|
||||
assert cookie.startswith("sokhan_session=")
|
||||
assert "HttpOnly" in cookie
|
||||
assert "SameSite=lax" in cookie
|
||||
body = response.json()
|
||||
assert body["csrf_token"] == csrf_token_for(body["api_token"])
|
||||
|
||||
|
||||
def test_cookie_secure_follows_the_scheme_by_default(client):
|
||||
# Plain http: a Secure cookie would be dropped by the browser.
|
||||
plain = client.post("/auth/register", json=CREDENTIALS).headers["set-cookie"]
|
||||
assert "Secure" not in plain
|
||||
|
||||
# HTTPS terminated by a reverse proxy in front of the API.
|
||||
behind_tls = client.post(
|
||||
"/auth/login", json=CREDENTIALS, headers={"X-Forwarded-Proto": "https"}
|
||||
).headers["set-cookie"]
|
||||
assert "Secure" in behind_tls
|
||||
|
||||
|
||||
def test_cookie_secure_can_be_forced(client, monkeypatch):
|
||||
monkeypatch.setenv("AUTH_COOKIE_SECURE", "true")
|
||||
get_settings.cache_clear()
|
||||
|
||||
cookie = client.post("/auth/register", json=CREDENTIALS).headers["set-cookie"]
|
||||
|
||||
assert "Secure" in cookie
|
||||
|
||||
|
||||
def test_cookie_authenticates_reads_without_a_bearer_header(cookie_client):
|
||||
_sign_in(cookie_client)
|
||||
|
||||
assert cookie_client.get("/quota").status_code == 200
|
||||
session = cookie_client.get("/auth/session")
|
||||
assert session.status_code == 200
|
||||
assert session.json()["email"] == CREDENTIALS["email"]
|
||||
|
||||
|
||||
def test_cookie_writes_need_the_csrf_header(cookie_client):
|
||||
body = _sign_in(cookie_client)
|
||||
|
||||
missing = cookie_client.post("/auth/logout")
|
||||
wrong = cookie_client.post("/auth/logout", headers={"X-CSRF-Token": "forged"})
|
||||
|
||||
assert missing.status_code == 403
|
||||
assert wrong.status_code == 403
|
||||
# The session survived both forged attempts.
|
||||
assert cookie_client.get("/quota").status_code == 200
|
||||
|
||||
ok = cookie_client.post("/auth/logout", headers={"X-CSRF-Token": body["csrf_token"]})
|
||||
assert ok.status_code == 204
|
||||
|
||||
|
||||
def test_logout_clears_the_cookie_and_revokes_the_token(cookie_client):
|
||||
body = _sign_in(cookie_client)
|
||||
|
||||
response = cookie_client.post("/auth/logout", headers={"X-CSRF-Token": body["csrf_token"]})
|
||||
|
||||
assert 'sokhan_session=""' in response.headers["set-cookie"]
|
||||
assert cookie_client.get("/auth/session").status_code == 401
|
||||
bearer = {"Authorization": f"Bearer {body['api_token']}"}
|
||||
assert cookie_client.get("/quota", headers=bearer).status_code == 401
|
||||
|
||||
|
||||
def test_bearer_clients_need_no_csrf_token(client):
|
||||
token = client.post("/auth/register", json=CREDENTIALS).json()["api_token"]
|
||||
client.cookies.clear()
|
||||
bearer = {"Authorization": f"Bearer {token}"}
|
||||
|
||||
assert client.get("/auth/session", headers=bearer).status_code == 200
|
||||
assert client.post("/auth/logout", headers=bearer).status_code == 204
|
||||
|
||||
|
||||
def test_session_without_any_credentials_is_401(client):
|
||||
assert client.get("/auth/session").status_code == 401
|
||||
|
||||
|
||||
def test_telegram_flow_sets_no_cookie(client, monkeypatch):
|
||||
monkeypatch.setenv("BOT_API_SECRET", "s3cret")
|
||||
get_settings.cache_clear()
|
||||
|
||||
response = client.post(
|
||||
"/auth/telegram", json={"telegram_id": 7}, headers={"X-Bot-Secret": "s3cret"}
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert "set-cookie" not in response.headers
|
||||
assert response.json()["csrf_token"] is None
|
||||
@@ -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",
|
||||
@@ -64,6 +73,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":
|
||||
@@ -81,6 +91,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()
|
||||
@@ -90,6 +101,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()
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -88,3 +88,20 @@ def test_get_plans_parses_catalogue():
|
||||
plans = client.get_plans()
|
||||
assert [plan["code"] for plan in plans] == ["free", "pro"]
|
||||
assert plans[1]["max_file_minutes"] == 180
|
||||
|
||||
|
||||
@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)
|
||||
@@ -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-<n>`."""
|
||||
|
||||
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)]
|
||||
@@ -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
|
||||
@@ -53,6 +53,9 @@ services:
|
||||
PLAN_PRO_MAX_FILE_MINUTES: ${PLAN_PRO_MAX_FILE_MINUTES:-180}
|
||||
PLAN_PRO_MONTHLY_MINUTES: ${PLAN_PRO_MONTHLY_MINUTES:-1200}
|
||||
ADMIN_API_KEY: ${ADMIN_API_KEY:-}
|
||||
AUTH_COOKIE_SECURE: ${AUTH_COOKIE_SECURE:-auto}
|
||||
AUTH_COOKIE_SAMESITE: ${AUTH_COOKIE_SAMESITE:-lax}
|
||||
AUTH_COOKIE_MAX_AGE_DAYS: ${AUTH_COOKIE_MAX_AGE_DAYS:-30}
|
||||
MAX_UPLOAD_MB: ${MAX_UPLOAD_MB:-200}
|
||||
SUMMARY_ENABLED: ${SUMMARY_ENABLED:-false}
|
||||
LLM_API_BASE: ${LLM_API_BASE:-}
|
||||
@@ -92,7 +95,10 @@ services:
|
||||
build:
|
||||
context: ../web
|
||||
args:
|
||||
NEXT_PUBLIC_API_BASE: ${NEXT_PUBLIC_API_BASE:-http://localhost:8000}
|
||||
# Empty: the browser calls /api on the web origin, proxied to the api
|
||||
# service, so the session cookie is first-party on any host.
|
||||
NEXT_PUBLIC_API_BASE: ${NEXT_PUBLIC_API_BASE:-}
|
||||
API_PROXY_TARGET: ${API_PROXY_TARGET:-http://api:8000}
|
||||
ports:
|
||||
- "${SOKHAN_WEB_PORT:-3000}:3000"
|
||||
depends_on:
|
||||
|
||||
+7
-3
@@ -5,10 +5,14 @@ COPY package.json package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY . .
|
||||
# NEXT_PUBLIC_ variables are inlined into the client bundle at build time,
|
||||
# so the API base URL is provided as a build argument.
|
||||
ARG NEXT_PUBLIC_API_BASE=http://localhost:8000
|
||||
# Both are baked into the build. The browser calls the API through this
|
||||
# app's own /api path, proxied to API_PROXY_TARGET (the compose service by
|
||||
# default). NEXT_PUBLIC_API_BASE stays empty unless the API is served from
|
||||
# its own host.
|
||||
ARG NEXT_PUBLIC_API_BASE=
|
||||
ARG API_PROXY_TARGET=http://api:8000
|
||||
ENV NEXT_PUBLIC_API_BASE=$NEXT_PUBLIC_API_BASE
|
||||
ENV API_PROXY_TARGET=$API_PROXY_TARGET
|
||||
|
||||
RUN npm run build
|
||||
|
||||
|
||||
@@ -16,8 +16,10 @@
|
||||
"archive": "Archive",
|
||||
"switchToEn": "English",
|
||||
"switchToFa": "فارسی",
|
||||
"themeToDark": "Switch to dark 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",
|
||||
|
||||
@@ -16,8 +16,10 @@
|
||||
"archive": "آرشیو",
|
||||
"switchToEn": "English",
|
||||
"switchToFa": "فارسی",
|
||||
"themeToDark": "تم تیره",
|
||||
"themeToLight": "تم روشن"
|
||||
"signIn": "ورود",
|
||||
"signOut": "خروج",
|
||||
"signedInAs": "واردشده با {email}",
|
||||
"signOutOf": "خروج از حساب {email}"
|
||||
},
|
||||
"landing": {
|
||||
"headline": "از گفتار به متن، در چند لحظه",
|
||||
|
||||
@@ -1,8 +1,22 @@
|
||||
import createNextIntlPlugin from "next-intl/plugin";
|
||||
|
||||
// The dashboard talks to the API through its own origin (/api/*), so the
|
||||
// httpOnly session cookie is always first-party: it works on localhost,
|
||||
// 127.0.0.1, a LAN address or a real domain alike, without CORS. The
|
||||
// target is baked into the build (standalone output); compose passes the
|
||||
// in-network address, `next dev` defaults to a local API.
|
||||
const apiProxyTarget = (process.env.API_PROXY_TARGET || "http://localhost:8000").replace(/\/$/, "");
|
||||
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
output: "standalone",
|
||||
async rewrites() {
|
||||
return [{ source: "/api/:path*", destination: `${apiProxyTarget}/:path*` }];
|
||||
},
|
||||
experimental: {
|
||||
// Uploads and transcript downloads can outlast the 30 s proxy default.
|
||||
proxyTimeout: 10 * 60 * 1000,
|
||||
},
|
||||
};
|
||||
|
||||
const withNextIntl = createNextIntlPlugin("./src/i18n/request.ts");
|
||||
|
||||
@@ -10,10 +10,10 @@ import {
|
||||
deleteJob,
|
||||
downloadTranscript,
|
||||
getJob,
|
||||
getToken,
|
||||
type JobDetail,
|
||||
type TranscriptFormat,
|
||||
} from "@/lib/api";
|
||||
import { useRequireSignIn } from "@/lib/session";
|
||||
import { ProgressBar, StatusBadge } from "@/components/job-bits";
|
||||
|
||||
const POLL_INTERVAL_MS = 3000;
|
||||
@@ -80,12 +80,9 @@ export default function JobDetailPage() {
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) {
|
||||
router.replace("/login");
|
||||
return;
|
||||
}
|
||||
useRequireSignIn();
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { Clock, Search } from "lucide-react";
|
||||
import { Link, useRouter } from "@/i18n/navigation";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import {
|
||||
ApiError,
|
||||
getToken,
|
||||
listJobs,
|
||||
searchJobs,
|
||||
type JobListItem,
|
||||
} from "@/lib/api";
|
||||
import { useRequireSignIn } from "@/lib/session";
|
||||
import { ProgressBar, StatusBadge } from "@/components/job-bits";
|
||||
|
||||
function formatDate(iso: string, locale: string): string {
|
||||
@@ -29,16 +29,13 @@ export default function JobsPage() {
|
||||
const tc = useTranslations("common");
|
||||
const te = useTranslations("errors");
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const nf = new Intl.NumberFormat(locale);
|
||||
|
||||
const [query, setQuery] = useState("");
|
||||
const [items, setItems] = useState<JobListItem[] | null>(null);
|
||||
const [listError, setListError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) router.replace("/login");
|
||||
}, [router]);
|
||||
useRequireSignIn();
|
||||
|
||||
const seqRef = useRef(0);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -5,7 +5,6 @@ import { getTranslations, setRequestLocale } from "next-intl/server";
|
||||
import localFont from "next/font/local";
|
||||
import { routing } from "@/i18n/routing";
|
||||
import { SiteHeader } from "@/components/site-header";
|
||||
import { themeInitScript } from "@/lib/theme";
|
||||
import "../globals.css";
|
||||
|
||||
// Fonts are self-hosted (see src/fonts/README.txt): builds must never depend
|
||||
@@ -48,10 +47,7 @@ export async function generateMetadata({
|
||||
}
|
||||
|
||||
export const viewport: Viewport = {
|
||||
themeColor: [
|
||||
{ media: "(prefers-color-scheme: light)", color: "#0f766e" },
|
||||
{ media: "(prefers-color-scheme: dark)", color: "#134e4a" },
|
||||
],
|
||||
themeColor: "#0f766e",
|
||||
};
|
||||
|
||||
export default async function LocaleLayout({
|
||||
@@ -68,10 +64,7 @@ export default async function LocaleLayout({
|
||||
const t = await getTranslations("common");
|
||||
|
||||
return (
|
||||
<html lang={locale} dir={locale === "fa" ? "rtl" : "ltr"} suppressHydrationWarning>
|
||||
<head>
|
||||
<script dangerouslySetInnerHTML={{ __html: themeInitScript }} />
|
||||
</head>
|
||||
<html lang={locale} dir={locale === "fa" ? "rtl" : "ltr"}>
|
||||
<body
|
||||
className={`${vazirmatn.variable} ${inter.variable} flex min-h-screen flex-col bg-stone-50 text-stone-900 antialiased`}
|
||||
>
|
||||
|
||||
@@ -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 { ApiError, login, register, startSession, 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<Mode>("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");
|
||||
startSession(result);
|
||||
} catch (error) {
|
||||
setPending(false);
|
||||
if (error instanceof ApiError) {
|
||||
|
||||
@@ -4,7 +4,8 @@ import { useEffect, useRef, useState, type DragEvent, type FormEvent } from "rea
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { ChevronDown, FileText, Mic, Square, Upload } from "lucide-react";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import { ApiError, getQuota, getToken, uploadJob, type QuotaInfo } from "@/lib/api";
|
||||
import { ApiError, getQuota, uploadJob, type QuotaInfo } from "@/lib/api";
|
||||
import { useRequireSignIn } from "@/lib/session";
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
@@ -43,9 +44,7 @@ export default function NewJobPage() {
|
||||
const recorderRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<Blob[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) router.replace("/login");
|
||||
}, [router]);
|
||||
useRequireSignIn();
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
@@ -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")}
|
||||
<ArrowRight className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
</Link>
|
||||
<Link
|
||||
href="/login"
|
||||
className="inline-flex min-h-11 items-center rounded-xl border border-stone-300 bg-white px-6 text-sm font-bold text-stone-800 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
|
||||
>
|
||||
<LoginCta className="inline-flex min-h-11 items-center rounded-xl border border-stone-300 bg-white px-6 text-sm font-bold text-stone-800 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2">
|
||||
{t("loginCta")}
|
||||
</Link>
|
||||
</LoginCta>
|
||||
</div>
|
||||
<svg
|
||||
viewBox="0 0 200 48"
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@custom-variant dark (&:where(.dark, .dark *));
|
||||
|
||||
@theme {
|
||||
--font-vazir: var(--font-vazirmatn, Vazirmatn), var(--font-inter, Inter), ui-sans-serif,
|
||||
system-ui, sans-serif;
|
||||
@@ -23,75 +21,3 @@ html[lang="en"] body {
|
||||
background-color: #99f6e4;
|
||||
color: #134e4a;
|
||||
}
|
||||
|
||||
html.dark {
|
||||
color-scheme: dark;
|
||||
|
||||
--color-stone-50: oklch(14.7% 0.004 49.25);
|
||||
--color-stone-100: oklch(26.8% 0.007 34.298);
|
||||
--color-stone-200: oklch(30% 0.007 34.298);
|
||||
--color-stone-300: oklch(40% 0.01 67.558);
|
||||
--color-stone-400: oklch(55.3% 0.013 58.071);
|
||||
--color-stone-500: oklch(70.9% 0.01 56.259);
|
||||
--color-stone-600: oklch(80% 0.005 56.366);
|
||||
--color-stone-700: oklch(86.9% 0.005 56.366);
|
||||
--color-stone-800: oklch(92.3% 0.003 48.717);
|
||||
--color-stone-900: oklch(97% 0.001 106.424);
|
||||
--color-stone-950: oklch(98.5% 0.001 106.423);
|
||||
|
||||
--color-teal-50: oklch(27.7% 0.046 192.524);
|
||||
--color-teal-100: oklch(32% 0.055 190);
|
||||
--color-teal-200: oklch(38.6% 0.063 188.416);
|
||||
--color-teal-800: oklch(85.5% 0.138 181.071);
|
||||
--color-teal-900: oklch(91% 0.096 180.426);
|
||||
--color-teal-950: oklch(95.3% 0.051 180.801);
|
||||
|
||||
--color-red-50: oklch(25.8% 0.092 26.042);
|
||||
--color-red-100: oklch(30% 0.11 26);
|
||||
--color-red-200: oklch(39.6% 0.141 25.723);
|
||||
--color-red-700: oklch(80.8% 0.114 19.571);
|
||||
--color-red-800: oklch(88.5% 0.062 18.334);
|
||||
--color-red-900: oklch(93.6% 0.032 17.717);
|
||||
|
||||
--color-amber-100: oklch(27.9% 0.077 45.635);
|
||||
--color-amber-800: oklch(92.4% 0.12 95.746);
|
||||
|
||||
--color-emerald-100: oklch(26.2% 0.051 172.552);
|
||||
--color-emerald-800: oklch(90.5% 0.093 164.15);
|
||||
|
||||
--sokhan-surface: oklch(19% 0.005 56);
|
||||
}
|
||||
|
||||
html.dark body {
|
||||
background-color: var(--color-stone-50);
|
||||
color: var(--color-stone-900);
|
||||
}
|
||||
|
||||
html.dark ::selection {
|
||||
background-color: #115e59;
|
||||
color: #f0fdfa;
|
||||
}
|
||||
|
||||
html.dark .bg-white {
|
||||
background-color: var(--sokhan-surface);
|
||||
}
|
||||
html.dark .bg-white\/90 {
|
||||
background-color: color-mix(in oklab, var(--sokhan-surface) 90%, transparent);
|
||||
}
|
||||
html.dark .supports-\[backdrop-filter\]\:bg-white\/75 {
|
||||
@supports (backdrop-filter: var(--tw)) {
|
||||
background-color: color-mix(in oklab, var(--sokhan-surface) 75%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
html.dark .text-teal-600,
|
||||
html.dark .text-teal-700 {
|
||||
color: oklch(77.7% 0.152 181.912);
|
||||
}
|
||||
html.dark .text-teal-700\/60 {
|
||||
color: color-mix(in oklab, oklch(77.7% 0.152 181.912) 60%, transparent);
|
||||
}
|
||||
|
||||
html.dark * {
|
||||
--tw-ring-offset-color: var(--sokhan-surface);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
/** The landing page's sign-in button; hidden once the visitor is signed in. */
|
||||
export function LoginCta({ className, children }: { className: string; children: ReactNode }) {
|
||||
const { ready, signedIn } = useSession();
|
||||
if (!ready || signedIn) return null;
|
||||
return (
|
||||
<Link href="/login" className={className}>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
@@ -1,15 +1,26 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { AudioLines } from "lucide-react";
|
||||
import { AudioLines, LogIn, LogOut } from "lucide-react";
|
||||
import { Link, usePathname, useRouter } from "@/i18n/navigation";
|
||||
import { ThemeToggle } from "@/components/theme-toggle";
|
||||
import { logout } from "@/lib/api";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
export function SiteHeader() {
|
||||
const t = useTranslations("nav");
|
||||
const locale = useLocale();
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const { ready, signedIn, email } = useSession();
|
||||
const [signingOut, setSigningOut] = useState(false);
|
||||
|
||||
async function handleSignOut() {
|
||||
setSigningOut(true);
|
||||
await logout();
|
||||
setSigningOut(false);
|
||||
router.replace("/login");
|
||||
}
|
||||
|
||||
const otherLocale = locale === "fa" ? "en" : "fa";
|
||||
|
||||
@@ -61,7 +72,38 @@ export function SiteHeader() {
|
||||
>
|
||||
{otherLocale === "en" ? "EN" : "فا"}
|
||||
</button>
|
||||
<ThemeToggle />
|
||||
{ready && signedIn && (
|
||||
<>
|
||||
{email && (
|
||||
<span
|
||||
className="hidden max-w-48 truncate text-sm text-stone-500 md:inline"
|
||||
title={t("signedInAs", { email })}
|
||||
>
|
||||
{email}
|
||||
</span>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSignOut}
|
||||
disabled={signingOut}
|
||||
aria-label={email ? t("signOutOf", { email }) : t("signOut")}
|
||||
className="inline-flex items-center gap-1.5 rounded-lg px-2 py-2 text-sm font-medium text-stone-600 transition-colors hover:bg-stone-100 hover:text-stone-900 focus-visible:ring-2 focus-visible:ring-teal-700 disabled:opacity-60 sm:px-3"
|
||||
>
|
||||
<LogOut className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
<span className="hidden sm:inline">{t("signOut")}</span>
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{ready && !signedIn && pathname !== "/login" && (
|
||||
<Link
|
||||
href="/login"
|
||||
className="inline-flex items-center gap-1.5 rounded-lg bg-teal-700 px-3 py-2 text-sm font-medium text-white transition-colors hover:bg-teal-600 focus-visible:ring-2 focus-visible:ring-teal-700 focus-visible:ring-offset-2"
|
||||
>
|
||||
<LogIn className="h-4 w-4 rtl:-scale-x-100" aria-hidden="true" />
|
||||
<span className="hidden sm:inline">{t("signIn")}</span>
|
||||
<span className="sr-only sm:hidden">{t("signIn")}</span>
|
||||
</Link>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { Moon, Sun } from "lucide-react";
|
||||
import { THEME_STORAGE_KEY, type Theme } from "@/lib/theme";
|
||||
|
||||
function applyTheme(theme: Theme) {
|
||||
document.documentElement.classList.toggle("dark", theme === "dark");
|
||||
}
|
||||
|
||||
export function ThemeToggle() {
|
||||
const t = useTranslations("nav");
|
||||
const [theme, setTheme] = useState<Theme | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setTheme(document.documentElement.classList.contains("dark") ? "dark" : "light");
|
||||
|
||||
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const onChange = (event: MediaQueryListEvent) => {
|
||||
let saved: string | null = null;
|
||||
try {
|
||||
saved = window.localStorage.getItem(THEME_STORAGE_KEY);
|
||||
} catch {
|
||||
}
|
||||
if (saved === "light" || saved === "dark") return;
|
||||
const next: Theme = event.matches ? "dark" : "light";
|
||||
applyTheme(next);
|
||||
setTheme(next);
|
||||
};
|
||||
media.addEventListener("change", onChange);
|
||||
return () => media.removeEventListener("change", onChange);
|
||||
}, []);
|
||||
|
||||
const isDark = theme === "dark";
|
||||
|
||||
function toggle() {
|
||||
const next: Theme = isDark ? "light" : "dark";
|
||||
applyTheme(next);
|
||||
setTheme(next);
|
||||
try {
|
||||
window.localStorage.setItem(THEME_STORAGE_KEY, next);
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
|
||||
const label = isDark ? t("themeToLight") : t("themeToDark");
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggle}
|
||||
aria-label={label}
|
||||
title={label}
|
||||
className="flex h-9 w-9 items-center justify-center rounded-lg border border-stone-300 text-stone-700 transition-colors hover:border-teal-700 hover:text-teal-800 focus-visible:ring-2 focus-visible:ring-teal-700"
|
||||
>
|
||||
{isDark ? (
|
||||
<Sun className="h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<Moon className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
+116
-31
@@ -1,10 +1,19 @@
|
||||
// Browser client for the Sokhan REST API. Authenticated requests carry the
|
||||
// stored API token as a Bearer header; a 401 clears the token and bounces
|
||||
// the user back to the login screen.
|
||||
// Browser client for the Sokhan REST API. The dashboard authenticates with
|
||||
// the httpOnly session cookie the API sets at sign-in: script never sees the
|
||||
// token, every request goes out with credentials, and writes carry the
|
||||
// session's CSRF token. A 401 marks the session signed out and bounces the
|
||||
// user back to the login screen.
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:8000";
|
||||
// Same-origin by default: next.config.mjs proxies /api/* to the backend, so
|
||||
// the session cookie is first-party wherever the dashboard is served from.
|
||||
// Set NEXT_PUBLIC_API_BASE only for an API on its own host.
|
||||
const API_BASE = (process.env.NEXT_PUBLIC_API_BASE || "/api").replace(/\/$/, "");
|
||||
|
||||
export const TOKEN_STORAGE_KEY = "sokhan_token";
|
||||
/** Fired on this tab whenever the session state changes. */
|
||||
export const SESSION_CHANGE_EVENT = "sokhan:session-change";
|
||||
// Earlier versions kept the token in localStorage; it is wiped on load.
|
||||
const LEGACY_STORAGE_KEYS = ["sokhan_token", "sokhan_email"];
|
||||
const SAFE_METHODS = new Set(["GET", "HEAD"]);
|
||||
|
||||
export type JobStatus = "queued" | "processing" | "completed" | "failed";
|
||||
export type TranscriptFormat = "txt" | "srt" | "vtt" | "json" | "docx";
|
||||
@@ -13,6 +22,14 @@ export interface AuthResponse {
|
||||
id: string;
|
||||
email: string;
|
||||
api_token: string;
|
||||
csrf_token: string | null;
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
/** "unknown" until GET /auth/session has answered once. */
|
||||
status: "unknown" | "signedIn" | "signedOut";
|
||||
email: string | null;
|
||||
csrfToken: string | null;
|
||||
}
|
||||
|
||||
export interface QuotaInfo {
|
||||
@@ -92,19 +109,93 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return window.localStorage.getItem(TOKEN_STORAGE_KEY);
|
||||
const UNKNOWN_SESSION: SessionState = { status: "unknown", email: null, csrfToken: null };
|
||||
const SIGNED_OUT: SessionState = { status: "signedOut", email: null, csrfToken: null };
|
||||
|
||||
let session: SessionState = UNKNOWN_SESSION;
|
||||
let sessionRequest: Promise<void> | null = null;
|
||||
let otherTabs: BroadcastChannel | null = null;
|
||||
|
||||
function setSession(next: SessionState, broadcast = true): void {
|
||||
session = next;
|
||||
if (typeof window === "undefined") return;
|
||||
window.dispatchEvent(new Event(SESSION_CHANGE_EVENT));
|
||||
if (broadcast) otherTabs?.postMessage("changed");
|
||||
}
|
||||
|
||||
export function setToken(token: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.setItem(TOKEN_STORAGE_KEY, token);
|
||||
/** The current session snapshot; a new object only when it changes. */
|
||||
export function getSessionState(): SessionState {
|
||||
return session;
|
||||
}
|
||||
|
||||
export function clearToken(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.removeItem(TOKEN_STORAGE_KEY);
|
||||
/** The server snapshot: nothing is known before hydration. */
|
||||
export function getUnknownSessionState(): SessionState {
|
||||
return UNKNOWN_SESSION;
|
||||
}
|
||||
|
||||
/** Ask the API who is signed in (deduplicated while a request is in flight). */
|
||||
export function loadSession(): Promise<void> {
|
||||
if (typeof window === "undefined") return Promise.resolve();
|
||||
if (!otherTabs && "BroadcastChannel" in window) {
|
||||
otherTabs = new BroadcastChannel("sokhan-session");
|
||||
otherTabs.onmessage = () => {
|
||||
sessionRequest = null;
|
||||
void loadSession();
|
||||
};
|
||||
for (const key of LEGACY_STORAGE_KEYS) {
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch {
|
||||
// Storage disabled: nothing to clean up.
|
||||
}
|
||||
}
|
||||
}
|
||||
sessionRequest ??= (async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/auth/session`, { credentials: "include" });
|
||||
if (!response.ok) {
|
||||
setSession(SIGNED_OUT, false);
|
||||
return;
|
||||
}
|
||||
const body = (await response.json()) as { email: string; csrf_token: string };
|
||||
setSession({ status: "signedIn", email: body.email, csrfToken: body.csrf_token }, false);
|
||||
} catch {
|
||||
setSession(SIGNED_OUT, false);
|
||||
} finally {
|
||||
sessionRequest = null;
|
||||
}
|
||||
})();
|
||||
return sessionRequest;
|
||||
}
|
||||
|
||||
/** Record a successful sign-in; the API has already set the cookie. */
|
||||
export function startSession(auth: AuthResponse): void {
|
||||
setSession({ status: "signedIn", email: auth.email, csrfToken: auth.csrf_token });
|
||||
}
|
||||
|
||||
function csrfHeaders(method: string, headers: Headers): Headers {
|
||||
if (!SAFE_METHODS.has(method) && session.csrfToken) {
|
||||
headers.set("X-CSRF-Token", session.csrfToken);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the session on the server (which also clears the cookie), then
|
||||
* mark it signed out locally. The local sign-out happens even when the API
|
||||
* is unreachable, so signing out always works from the user's point of view.
|
||||
*/
|
||||
export async function logout(): Promise<void> {
|
||||
try {
|
||||
await fetch(`${API_BASE}/auth/logout`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: csrfHeaders("POST", new Headers()),
|
||||
});
|
||||
} catch {
|
||||
// Offline or API down: the local sign-out below still happens.
|
||||
}
|
||||
setSession(SIGNED_OUT);
|
||||
}
|
||||
|
||||
function redirectToLogin(): void {
|
||||
@@ -116,7 +207,7 @@ function redirectToLogin(): void {
|
||||
|
||||
function handleAuthFailure(response: Response): void {
|
||||
if (response.status === 401) {
|
||||
clearToken();
|
||||
setSession(SIGNED_OUT);
|
||||
redirectToLogin();
|
||||
}
|
||||
}
|
||||
@@ -131,15 +222,16 @@ interface RequestOptions {
|
||||
async function requestJson<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { method = "GET", body, headers: extraHeaders, authenticated = false } = options;
|
||||
|
||||
const headers = new Headers(extraHeaders);
|
||||
if (authenticated) {
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
}
|
||||
const headers = csrfHeaders(method, new Headers(extraHeaders));
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${API_BASE}${path}`, { method, headers, body });
|
||||
response = await fetch(`${API_BASE}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "network error");
|
||||
}
|
||||
@@ -229,15 +321,12 @@ export async function searchJobs(query: string): Promise<JobListResponse> {
|
||||
}
|
||||
|
||||
export async function deleteJob(id: string): Promise<void> {
|
||||
const headers = new Headers();
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${API_BASE}/jobs/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers,
|
||||
headers: csrfHeaders("DELETE", new Headers()),
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "network error");
|
||||
@@ -248,15 +337,11 @@ export async function deleteJob(id: string): Promise<void> {
|
||||
}
|
||||
|
||||
export async function downloadTranscript(id: string, format: TranscriptFormat): Promise<Blob> {
|
||||
const headers = new Headers();
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(
|
||||
`${API_BASE}/jobs/${encodeURIComponent(id)}/transcript?format=${format}`,
|
||||
{ headers },
|
||||
{ credentials: "include" },
|
||||
);
|
||||
} catch {
|
||||
throw new ApiError(0, "network error");
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// Reactive view of the dashboard session for client components. The token
|
||||
// itself lives in an httpOnly cookie the page cannot read, so the state
|
||||
// comes from GET /auth/session (see api.ts) and is kept in sync across this
|
||||
// tab (SESSION_CHANGE_EVENT) and other tabs (a BroadcastChannel).
|
||||
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import {
|
||||
SESSION_CHANGE_EVENT,
|
||||
getSessionState,
|
||||
getUnknownSessionState,
|
||||
loadSession,
|
||||
} from "@/lib/api";
|
||||
|
||||
// Accounts created by the Telegram bot get a synthetic address that means
|
||||
// nothing to the user, so it is not shown.
|
||||
const SYNTHETIC_EMAIL_SUFFIX = "@telegram.sokhan.local";
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
window.addEventListener(SESSION_CHANGE_EVENT, onChange);
|
||||
if (getSessionState().status === "unknown") void loadSession();
|
||||
return () => window.removeEventListener(SESSION_CHANGE_EVENT, onChange);
|
||||
}
|
||||
|
||||
export interface Session {
|
||||
/** False during SSR and until the API has said who is signed in. */
|
||||
ready: boolean;
|
||||
signedIn: boolean;
|
||||
/** The account email, or null when unknown or a Telegram placeholder. */
|
||||
email: string | null;
|
||||
}
|
||||
|
||||
export function useSession(): Session {
|
||||
const state = useSyncExternalStore(subscribe, getSessionState, getUnknownSessionState);
|
||||
const email =
|
||||
state.email && !state.email.endsWith(SYNTHETIC_EMAIL_SUFFIX) ? state.email : null;
|
||||
return { ready: state.status !== "unknown", signedIn: state.status === "signedIn", email };
|
||||
}
|
||||
|
||||
/** Send a signed-out visitor to the login page once the session is known. */
|
||||
export function useRequireSignIn(): void {
|
||||
const { ready, signedIn } = useSession();
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
if (ready && !signedIn) router.replace("/login");
|
||||
}, [ready, signedIn, router]);
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
export const THEME_STORAGE_KEY = "sokhan-theme";
|
||||
|
||||
export type Theme = "light" | "dark";
|
||||
|
||||
export const themeInitScript = `(function(){try{var t=localStorage.getItem("${THEME_STORAGE_KEY}");if(t!=="light"&&t!=="dark"){t=matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}document.documentElement.classList.toggle("dark",t==="dark")}catch(e){}})();`;
|
||||
@@ -4,5 +4,6 @@ import { routing } from "./i18n/routing";
|
||||
export default createMiddleware(routing);
|
||||
|
||||
export const config = {
|
||||
matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)"],
|
||||
// /api is the proxied backend: it must not get a locale prefix.
|
||||
matcher: ["/((?!api/|_next/static|_next/image|favicon.ico|.*\\..*).*)"],
|
||||
};
|
||||
Reference in new issue
Block a user