17 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 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 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 d93d98c102 Merge branch 'fix/security-hardening'
# Conflicts:
#	CHANGELOG.md
2026-11-26 16:37:46 +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 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 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
Abolfazl Ranjbaran 4821d812dc feat(accuracy): Persian accuracy stack v2 — measured -24.3 WER points on the default stack
Every decision below is measured on the 12-clip Common Voice fa fixture
with a reproducible harness; no number is hand-written.

- fa_polish module: orthographic-only repair (ZWNJ fusion, split
  imperatives like 'بی پوش' -> 'بپوش', Arabic code points, digits).
  Wired into the pipeline (FA_POLISH=true) and ported 1:1 to the browser
  demo (16-case parity test vs Python). -3.6 WER points.
- Persian orthography initial_prompt as the default: whisper copies the
  prompt's script style. -1.3 points (small), -4.8 (fine-tuned).
- Default engine small -> medium: 56.2% WER vs 75.0% (v2 harness) at
  ~1.1x realtime on 2 CPU cores. small stays the speed-first profile.
- Browser demo: default model base -> small (90.2% -> 75.0% under v2),
  polished output identical to the server's shape.
- benchmarks/tune_decode.py: the sweep harness behind every decision
  (prompt x beam x VAD x condition_on_previous_text).
- training/export_web_onnx.py: LoRA merge -> ONNX -> int8 -> HF Hub so
  the next fine-tune can run inside the browser demo.
- baseline.json regenerated for the v2 harness; weekly benchmark now
  guards small AND medium; gate test updated.

Fixture: small 80.5% -> 75.0%, fine-tuned 79.3% -> 75.0%, medium 56.2%.
2026-11-26 09:44:41 +00:00
Abolfazl Ranjbaran 44ebd69090 chore(meta): release-grade packaging, compose plan passthrough, citation
Repo audit findings, fixed:
- backend/bot pyprojects: version was hardcoded 0.1.0 while the product
  is v1.4.0 — versions are dynamic now (attr = __version__) and both
  packages carry full PEP 621 metadata: authors, MIT license, keywords,
  classifiers, project URLs
- sokhan_bot.__version__ was still 1.1.0; tracks the release again
- web package.json: 0.1.0 -> 1.4.0 plus description/license/repository/
  bugs/homepage fields
- deploy/docker-compose.yml now passes PLAN_FREE_MAX_FILE_MINUTES,
  PLAN_PRO_MAX_FILE_MINUTES, PLAN_PRO_MONTHLY_MINUTES and ADMIN_API_KEY
  to the containers — the admin surface used to answer 503 and plan caps
  were untunable in every compose deployment
- FastAPI app gets MIT license_info on /docs
- CITATION.cff for academic citation
- issue-template chooser and the landing footer link to Discussions
- CHANGELOG: Unreleased section documents all of the above

Validated locally: 176 tests pass, tomllib/json/yaml parse clean,
pip -e resolves 1.4.0 from the dynamic version.
2026-11-25 08:06:05 +00:00
Abolfazl Ranjbaran ce3c9f73b7 feat(engine): streaming decode + signed job-completion webhooks
Streaming decode (ROADMAP v1.4): the worker now streams PyAV blocks and
emits the same 30-second windows from the block stream instead of decoding
the whole file to memory. iter_chunks reproduces chunk_samples exactly
(proven by test, including the short-tail fold); diarizers declare
requires_full_audio and take the legacy full decode automatically.
Measured whole-process peak RSS on identical mono 16 kHz WAVs:
30-minute file 86.4 MB streamed vs 355.6 MB full decode (4.1x),
10-minute file 84.9 MB vs 169.6 MB (2.0x) - streaming stays flat while
the full decode grows linearly with duration.

Signed webhooks (ROADMAP v1.5): POST /jobs accepts callback_url
(http/https, <=2048 chars, migration 0003). On completion or failure the
worker POSTs a JSON event signed Stripe-style (X-Sokhan-Signature:
t=<unix>,v1=<hex hmac-sha256(secret, '<ts>.<body>')>, 5-minute replay
window) after the DB session closes; a dead endpoint is retried once and
logged, never fatal to the job. WEBHOOK_SIGNING_SECRET enables signing.

40 new tests (streaming equivalence, lazy consumption, resampler flush
parity with decode_audio, signature scheme, delivery retries, end-to-end
signed callback on completed and failed jobs); full suite 154 passing,
ruff and mypy clean.
2026-11-22 22:38:04 +00:00
Abolfazl Ranjbaran 79dec8d46b feat: Persian punctuation restoration, confidence-aware review flags, GHCR image publish
Closes the two product-feature gaps still open in the ROADMAP, plus the
v1.5 deploy item:

- Persian punctuation restoration (v1.4): a deterministic rule-based
  post-pass in the worker pipeline and on the OpenAI-compatible endpoint
  behind PUNCTUATION_ENABLED (default on). Question sentences get a real
  ؟ (آیا/چرا/چطور/کی/کجا/کدام/چیه word family), declaratives get a
  period, Latin ,/;/? map to ،/؛/؟, spacing is fixed around every mark
  (no space before, one after), and decimals/clock times are deliberately
  left intact. The WER benchmark path bypasses the pipeline, so the
  measured numbers stay comparable; search normalization split into
  normalize_for_search (punctuation stripped on column and query) so
  phrase queries match the punctuated text while benchmarks keep using
  normalize_persian unchanged. The browser demo ports the same rule
  family verbatim (18-case parity check in scripts/), so the Space shows
  transcripts in the product's shape.

- Confidence-aware review flags (v1.5): the engine's exp(avg_logprob)
  now survives the whole pipeline — segments.confidence column (Alembic
  0002), GET /jobs/{id}, the JSON export, verbose_json — and segments
  below LOW_CONFIDENCE_THRESHOLD (0.5 default) are marked with a ⚠
  prefix in SRT/VTT/DOCX exports and a 'نیاز به بازبینی / Needs review'
  badge (hover shows the percent) in the dashboard timeline. Reviewers
  re-listen exactly where the model was unsure.

- Prebuilt images on GHCR (v1.5): the Docker workflow builds and pushes
  ghcr.io/abolfazlrwm/sokhan-api and ...-web on pushes to main and
  version tags (latest / sha-* / semver) with the GITHUB_TOKEN, no
  extra secrets; the compose file references the same image names next
  to its build: blocks so both pull and build paths work, and now also
  passes WHISPER_BEAM_SIZE / WHISPER_INITIAL_PROMPT / PUNCTUATION_ENABLED
  / LOW_CONFIDENCE_THRESHOLD through to the containers.

Docs updated end to end (README features + config table + prebuilt-image
section, ROADMAP ticks v1.4/v1.5, architecture request-flow, CHANGELOG).
101 tests passing (new: punctuation rules, search normalization, review
flags on exports, confidence flow through API/exports/verbose_json);
ruff and mypy clean; web build clean; demo punctuation port verified
against the same test cases as the backend.
2026-11-22 18:54:48 +00:00
Abolfazl Ranjbaran 86cea91442 fix(security): CORS allowlist instead of wildcard, required DB password
- API: CORS allow_origins now defaults to the local dev front-end only;
  deployments set SOKHAN_CORS_ORIGINS (comma-separated) to the real
  public origins. allow_credentials stays false, so a wildcard never
  leaks authenticated responses cross-origin either way.
- deploy/docker-compose.yml: POSTGRES_PASSWORD is required interpolation
  (${POSTGRES_PASSWORD:?...}) instead of the hardcoded 'sokhan'; the
  DATABASE_URL is built from the same variables. .env.example documents
  both, and the CI compose validation passes a placeholder.
2026-11-20 17:42:29 +00:00
Abolfazl Ranjbaran 88212a7b0b feat(ci): auto-sync the demo Space, contributor docs and issue templates
- Sync demo Space workflow: any push to main touching space/ (or the
  sync script/workflow itself) re-publishes the static demo to
  hf.co/spaces/Abol0pati/sokhan-fa-demo via deploy/sync_space.py, using
  the repo's HF_TOKEN Actions secret, so the public demo cannot drift
  from main
- CI lint loop now also covers deploy/
- CONTRIBUTING.md: dev setup, test/lint commands, how the demo sync
  works, and the measurement-first rule for accuracy claims
- Issue templates (bug report / feature idea / config) pointing users
  at the live demo and private security disclosure
- README gains the sync badge; repo homepage set to the live Space
2026-11-19 11:26:25 +00:00
Abolfazl Ranjbaran 822cdb8f31 feat(backend): energy and pyannote diarization engines behind a flag
DIARIZATION_ENGINE selects stub | energy | pyannote. The energy engine is a
numpy-only voiced-region two-cluster heuristic; pyannote is the real neural
pipeline, gated behind an HF token and the optional diarize extra. The
factory and the pipeline treat diarization as an enhancement: any failure
degrades to no speaker labels instead of failing the job. Speaker labels
flow into segments and the SRT export. Fixes the diarization tests' missing
shared fake_engine fixture (they could never run on the source branch).
2026-11-14 19:19:02 +00:00
Abolfazl Ranjbaran 8666c65be2 feat(deploy): docker compose for api, worker, redis, postgres and web
One command brings up the full stack on CPU. The worker shares the backend
image with a celery command, uploads live on a named volume, and the web
image inlines NEXT_PUBLIC_API_BASE at build time via a build argument.

Closes #7
2026-11-13 09:48:02 +00:00