35 Commits
Author SHA1 Message Date
ahp f3437ee230 Merge branch 'feat/httponly-cookie-auth'
# Conflicts:
#	backend/sokhan/config.py
#	deploy/docker-compose.yml
2026-11-26 18:42:02 +03:30
ahp 9a74cca685 fix(web): reach the API through the dashboard's own origin
Signing in returned 200, but the browser never sent the session cookie
back, so every following request was a 401. The dashboard called the API
on another origin (http://localhost:8000): opened as 127.0.0.1:3000 or a
LAN address that is a different site, so the SameSite cookie was never
stored, and browsers also drop a Secure cookie over plain http.

- the web server proxies /api/* to API_PROXY_TARGET (http://api:8000 in
  compose) and the client calls /api by default, so the cookie is
  first-party on any host; NEXT_PUBLIC_API_BASE is now only for an API
  on its own host
- /api is excluded from the locale middleware, and the proxy timeout is
  raised to 10 minutes for large uploads and downloads
- AUTH_COOKIE_SECURE defaults to auto: Secure whenever the request came
  over HTTPS, directly or via X-Forwarded-Proto; true/false force it
- .env.example, compose, both READMEs and the CHANGELOG updated
2026-11-26 18:42:01 +03:30
ahp ace0b764ba Merge branch 'feat/header-account-menu' 2026-11-26 18:05:12 +03:30
ahp 064e7a0bd5 Merge branch 'feat/landing-single-cta' 2026-11-26 18:05:11 +03:30
ahp 9d35436cce Merge branch 'feat/login-password-toggle' 2026-11-26 18:05:11 +03:30
ahp bcce7ac897 Merge branch 'fix/job-progress' 2026-11-26 18:05:11 +03:30
ahp 9ccf51e3c9 Merge branch 'feat/httponly-cookie-auth'
# Conflicts:
#	backend/sokhan/api/routes_auth.py
#	backend/sokhan/config.py
#	deploy/docker-compose.yml
2026-11-26 18:05:11 +03:30
ahp 3895219768 Merge branch 'feat/sign-in-state-and-logout'
# Conflicts:
#	backend/sokhan/api/routes_auth.py
#	bot/tests/test_client_errors.py
#	web/messages/en.json
#	web/messages/fa.json
#	web/src/components/site-header.tsx
2026-11-26 18:04:53 +03:30
ahp b22dd5d161 Merge branch 'docs/contributing-fa' 2026-11-26 18:04:36 +03:30
ahp 032b8de9e8 Merge branch 'test/punctuation-edge-cases'
# Conflicts:
#	CHANGELOG.md
2026-11-26 18:04:36 +03:30
ahp 3123e2006c Merge branch 'fix/upload-storage-errors' 2026-11-26 18:04:26 +03:30
ahp 0deafa4cdf feat(web): keep the dashboard session in the httpOnly cookie
The dashboard stops storing the API token in localStorage (CodeQL
js/clear-text-storage-of-sensitive-data).

- every request goes out with credentials; writes carry the session's
  CSRF token
- session state lives in memory and comes from GET /auth/session, kept
  in sync across tabs with a BroadcastChannel
- pages guard with useRequireSignIn instead of reading the token
- the token earlier versions left in localStorage is wiped on load
- SECURITY.md: the code-scanning example for disposition 3 now says
  the tracked issue has shipped

Closes #33
2026-11-26 18:02:11 +03:30
ahp 1219089a3c docs(contributing): add a Persian translation of the contribution guide
- CONTRIBUTING.fa.md follows the original section by section, in the
  same order, with the terminology README.fa.md already uses (رونویسی،
  ورکر، سلف‌هاست، داشبورد، فاین‌تیون)
- commands, code blocks, paths and commit prefixes stay in English so
  they remain copy-pasteable; no command or number was changed
- both files get a language switcher line, like the READMEs

Closes #31
2026-11-26 18:02:10 +03:30
ahp b2386acdd1 feat(auth): httpOnly session cookie with a CSRF check on writes
Groundwork for moving the dashboard token out of localStorage (#33),
where any XSS in the dashboard could read it.

- register, login and token-login also set the token as an HttpOnly,
  Secure, SameSite cookie; the JSON body keeps api_token for API clients
- the API accepts the cookie when no bearer header is sent; bearer auth
  (bot, scripts, OpenAI-compatible clients) is unchanged and needs no
  CSRF token, since browsers never attach it on their own
- cookie-authenticated unsafe methods must send X-CSRF-Token: an HMAC of
  the session token, so the server recomputes it without storing
  anything and a cross-site page cannot derive it (403 otherwise)
- GET /auth/session returns the signed-in account and its CSRF token;
  logout also clears the cookie
- CORS allows credentials for the explicit SOKHAN_CORS_ORIGINS list
- AUTH_COOKIE_SECURE / _SAMESITE / _MAX_AGE_DAYS, documented in
  .env.example and passed through compose
2026-11-26 18:02:10 +03:30
ahp a29dae7f56 fix(punctuation): keep thousands separators out of the comma mapping
The Latin-to-Persian mapping turned every comma into ، and the spacing
rule then added a space after it, so "1,000" came out as "1، 000": one
number split into two.

- a comma between a digit and exactly three more digits is a thousands
  separator and is kept as is (Latin and Persian digits)
- a comma in a list of numbers (4090,4080) still becomes ، as before
2026-11-26 18:02:08 +03:30
ahp d254527881 test(punctuation): pin the post-pass on real-world edge cases
Documents what the rule-based pass does today, case by case, before any
rule changes (#30):

- slash dates and fractions (1404/09/02, 2026/11/23, 1/2) stay intact
- Latin digits and words inside Persian sentences, decimals, version
  numbers and clock times are left alone
- abbreviation dots (Dr.) count as terminal punctuation; a dot mid
  sentence is untouched
- ellipses (… and ...) are terminal and tightened, so a trailing-off
  question keeps its ellipsis instead of gaining a question mark
- repeated and mixed marks (!!!, ؟؟, ?!) are preserved, since they carry
  the speaker's emphasis
2026-11-26 18:02:07 +03:30
ahp 53becfa1de fix(api): answer 503 when an upload cannot be stored
An unwritable DATA_DIR (a root-owned volume, a full disk, a read-only
mount) made POST /jobs and POST /v1/audio/transcriptions fail with a
bare 500 and a PermissionError traceback, with nothing in the response
telling the client it was a server-side storage problem.

- save_upload raises StorageUnavailableError on any OSError while
  creating DATA_DIR/audio or writing the file, and removes a partially
  written file first
- one app-level handler turns it into 503 with a short detail; the real
  error, including the path, goes only to the server log
- the API logs an error at startup when DATA_DIR is not writable, so a
  bad volume shows up before the first upload
2026-11-26 18:02:05 +03:30
ahp 4d2c060a29 feat(web): account menu in the header instead of an inline email
The email sat in the header row next to Sign out, truncated on medium
screens and hidden on small ones.

- an avatar with the email's initial opens a menu with the full email
  and Sign out
- the menu closes on outside click and Escape, returns focus to the
  avatar, and opens towards the inline end so it fits in RTL and LTR
- accounts without a known email get a generic avatar and "Signed in"
2026-11-26 17:58:31 +03:30
ahp f1f8a9919b feat(web): drop the separate sign-in button from the landing page
Signing in now lives in the header, so the landing page's second
button only repeated it.

- the hero keeps a single "Get started" call to action, which sends
  signed-out visitors to the login page
- removes the LoginCta component and the unused loginCta strings
2026-11-26 17:58:26 +03:30
ahp ea821ff70b feat(web): show/hide toggle on the login password field
- an eye button inside the password field switches it between hidden
  and plain text; it is labelled for screen readers, exposes its state
  with aria-pressed and resets when the sign-in mode changes
- the field stays LTR, so the button sits at its right edge in both
  languages
2026-11-26 17:58:21 +03:30
ahp ad23bbfa43 fix(web): live progress in the archive and a working state at 0%
- the archive re-fetches every 3 s while any job is queued or
  processing; it loaded once, so its progress bars never moved
- ProgressBar shows a moving bar while no progress has been reported
  yet, with "Getting ready" in place of 0%, and falls back to a pulse
  under prefers-reduced-motion
- the job page uses the translated percent string, so English no
  longer shows the Persian percent sign
2026-11-26 17:58:10 +03:30
ahp 36262770d0 fix(worker): report job progress while a chunk is transcribed
Progress was only saved after each 30-second chunk, so a clip shorter
than 30 s (one chunk) sat at 0% for the whole job, model load included,
and then jumped to 100%.

- the Whisper engine calls an optional on_progress callback with how far
  into the chunk it is, as faster-whisper yields each segment
- the pipeline maps that onto overall progress (by chunk count, or by
  the duration estimate when streaming) and saves it monotonically,
  below 100 and at most once a second
- engines opt in with reports_progress; ones with the plain
  three-argument transcribe keep working unchanged
2026-11-26 17:58:10 +03:30
ahp 7a3dab88c8 feat(web): show the sign-in state in the header and add sign out
After signing in nothing showed that you were signed in, and there was
no way to sign out.

- the header shows Sign in when signed out, and the account email plus
  Sign out when signed in (Telegram placeholder emails are not shown)
- sign out calls POST /auth/logout, then clears the local session even
  if the API is unreachable, and goes to the login page
- the landing page's sign-in button is hidden for a signed-in user, and
  the login page redirects them to the upload page
- a useSession hook (useSyncExternalStore) keeps every component in
  sync across sign-in and sign-out, including other tabs
2026-11-26 17:57:56 +03:30
ahp 752c972669 feat(auth): add POST /auth/logout to revoke the caller's token
Signing out of the dashboard only forgot the token in the browser; the
token itself stayed valid for anyone who had copied it.

- POST /auth/logout replaces the stored hash with one of a fresh random
  token that is never returned, then answers 204
- an account has a single active token, so this signs out every client
  holding it, the same way a new sign-in already does
- a revoked token is rejected by every endpoint, including token-login
2026-11-26 17:57:55 +03:30
ahp 9ba610d081 fix(bot): re-register when the API revokes a chat's cached token
The bot caches one API token per chat and reuses it forever. A newer
sign-in for the same account (or a logout) revokes that token, after
which every request from the chat failed and /start kept showing a dead
connect code.

- the client raises AuthError on 401 from upload, job and quota calls
- handlers run API calls through _authed: on AuthError the cached token
  is dropped, the chat re-registers once and the call is retried
- /start checks the cached token before showing it as the connect code
- the completion poller, which has no Telegram user to re-register
  with, untracks the job and asks the chat to send /start
- TokenStore.forget drops a chat's token
2026-11-26 17:57:55 +03:30
ahp d93d98c102 Merge branch 'fix/security-hardening'
# Conflicts:
#	CHANGELOG.md
2026-11-26 16:37:46 +03:30
ahp a2bab55d25 Merge branch 'feat/web-dark-mode' 2026-11-26 16:37:38 +03:30
ahp 9e6d8fc91a Merge branch 'fix/deploy-self-hosting' 2026-11-26 16:37:38 +03:30
ahp 8a585fc718 fix(deploy): persist the Whisper cache and clarify the compose env file
- HF_HOME=/data/huggingface on api and worker: the model cache sat in
  the container filesystem, so every recreate (down/up, --build, a new
  image) re-downloaded the model weights — and transcription failed
  outright wherever the Hugging Face Hub is unreachable
- the postgres healthcheck probes $POSTGRES_USER / $POSTGRES_DB instead
  of a hardcoded sokhan
- compose interpolates from the .env next to deploy/docker-compose.yml,
  not the one at the repo root: the quickstart in both READMEs and the
  .env.example header now say cp .env.example deploy/.env, and the
  missing-password error names that path
2026-11-26 16:26:03 +03:30
ahp 57be6ca2ce feat(web): dark mode with an OS-preference default and a header toggle
- ThemeToggle (sun/moon) in the site header; an explicit choice is
  saved in localStorage, otherwise prefers-color-scheme decides and OS
  changes are followed live
- an inline <head> script sets html.dark before first paint, so there
  is no flash of the wrong theme; suppressHydrationWarning on <html>
  covers the class it adds
- globals.css remaps the Tailwind palette under html.dark (stone
  inverted, accent tints darkened, text-only accent shades lifted)
  instead of adding dark: to ~230 utilities across 8 files; solid
  teal/red keep their value for white-on-accent buttons, with targeted
  overrides where they double as a text colour
- per-scheme themeColor; fa/en labels for the toggle
2026-11-26 16:25:44 +03:30
ahp 103f72f41e fix(security): throttle failed logins per client address and email
POST /auth/login accepted unlimited password guesses.

- FailureThrottle: thread-safe sliding window kept in process (the
  compose stack runs a single uvicorn process)
- keyed by (client address, email): an attacker cannot lock a victim
  out from everywhere, and users behind one NAT are not punished for
  each other's typos
- after LOGIN_MAX_FAILURES (10) failures within
  LOGIN_FAILURE_WINDOW_SECONDS (900) the endpoint answers 429 with
  Retry-After; a successful login clears the count; 0 disables it
2026-11-26 16:25:34 +03:30
ahp ee42254ab1 fix(security)!: keep webhook callbacks off internal addresses
callback_url only had to start with http(s)://, so any user could make
the worker POST to loopback, the compose network (postgres, redis),
link-local cloud metadata or the LAN.

- upload time: literal private, loopback and link-local hosts and
  localhost are rejected with 422 (no DNS lookup on the request path)
- delivery time: a guarded create_connection resolves once, refuses
  the host if any address is non-public and connects to the vetted
  address itself, so DNS rebinding cannot swap in a private IP after
  the check
- redirects are not followed and *_PROXY env vars are ignored for
  callbacks
- WEBHOOK_ALLOW_PRIVATE_TARGETS=true restores the old behaviour for
  trusted single-tenant installs (e.g. n8n on the LAN)

BREAKING CHANGE: callbacks to private addresses now need
WEBHOOK_ALLOW_PRIVATE_TARGETS=true.
2026-11-26 16:25:34 +03:30
ahp 9d15525500 fix(security): cap request bodies before uploads reach disk or memory
The MAX_UPLOAD_MB check in POST /jobs and /v1/audio/transcriptions ran
after file.file.read(): Starlette had already spooled the whole
multipart body to a temp file and the handler then loaded it into RAM,
so one multi-gigabyte upload from any registered user could exhaust the
API container.

- BodySizeLimitMiddleware answers 413 up front from Content-Length, or
  mid-stream by counting bytes for chunked bodies (FastAPI re-raises
  the HTTPException from body parsing)
- the cap is MAX_UPLOAD_MB plus 1 MiB of multipart framing; registered
  before CORS so browsers can read the 413
- measured on the compose stack: a 250 MB chunked upload is cut off
  with 413 while the API stays at ~89 MB RSS and /tmp stays empty
2026-11-26 16:25:34 +03:30
ahp c902ab4469 fix(security)!: require a bot shared secret on POST /auth/telegram
The endpoint minted a fresh API token for whatever telegram_id the
caller sent. Telegram ids are not secret (anyone sharing a group sees
them), so any client that could reach the API could log in as any
Telegram user: read and delete their transcripts, spend their quota and
rotate their token out from under the bot.

- new BOT_API_SECRET; require_bot checks X-Bot-Secret with
  compare_digest, mirroring require_admin: 403 on a wrong or missing
  secret, 503 while unset
- the bot sends the header and refuses to start without the secret
- tests: rejected without / with a wrong secret, disabled while unset,
  bot client sends the header

BREAKING CHANGE: deployments running the bot must set the same
BOT_API_SECRET on the API and the bot.
2026-11-26 16:25:34 +03:30
ahp 1304b13999 fix(deploy): pre-create /data owned by appuser in the backend image
Uploaded audio lives under DATA_DIR (/data, the sokhan-data named
volume). The image never created that directory, so Docker made the
mount point root-owned on first start and every upload failed with
PermissionError once the process runs as appuser.

Docker seeds a new named volume with the mount point's ownership, so
creating /data/audio in the image, owned by appuser, fixes fresh
installs without an entrypoint chown.
2026-11-26 16:25:33 +03:30