Author SHA1 Message Date
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
7 changed files with 45 additions and 116 deletions

No files matched your search

+1 -9
View File
@@ -51,6 +51,7 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
worker with timestamp-midpoint trimming, enabling the progress stream
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.
- A show/hide toggle (eye icon) on the login page's password field.
### Changed
@@ -74,15 +75,6 @@ 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
- An upload the API cannot store (unwritable `DATA_DIR`, full disk,
read-only volume) now answers **503** with a short message on `POST /jobs`
and `POST /v1/audio/transcriptions`, instead of a 500 with a traceback in
the log. The real `OSError` is logged server-side, a partially written
file is removed, and the API logs an error at startup when `DATA_DIR`
is not writable.
## [1.4.1] - 2026-11-26
### Security
+3 -22
View File
@@ -25,14 +25,6 @@ ALLOWED_EXTENSIONS = {".mp3", ".m4a", ".mp4", ".wav", ".ogg", ".opus", ".webm",
_SAFE_SUFFIX = re.compile(r"^[a-z0-9]{1,8}$")
class StorageUnavailableError(Exception):
"""DATA_DIR cannot be written, e.g. a root-owned volume or a full disk.
It is a server fault, not a bad upload, so the API answers 503 and the
real OSError stays in the server log instead of reaching the client.
"""
def decode_to_mono_16k(path: str | Path) -> np.ndarray:
"""Decode any media file to mono float32 PCM at 16 kHz."""
return decode_audio(str(path), sampling_rate=SAMPLE_RATE)
@@ -110,23 +102,12 @@ def audio_dir() -> Path:
def save_upload(data: bytes, job_id: str, original_filename: str) -> Path:
"""Persist an upload under DATA_DIR/audio with a safe extension.
Raises StorageUnavailableError when the directory or file cannot be
written; a partially written file is removed first.
"""
"""Persist an upload under DATA_DIR/audio with a safe extension."""
suffix = Path(original_filename).suffix.lower()
if suffix not in ALLOWED_EXTENSIONS or not _SAFE_SUFFIX.match(suffix[1:]):
suffix = ".bin"
try:
path = audio_dir() / f"{job_id}{suffix}"
except OSError as exc:
raise StorageUnavailableError(str(exc)) from exc
try:
path.write_bytes(data)
except OSError as exc:
delete_audio(path)
raise StorageUnavailableError(str(exc)) from exc
path = audio_dir() / f"{job_id}{suffix}"
path.write_bytes(data)
return path
+1 -19
View File
@@ -10,13 +10,11 @@ import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, status
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from sokhan import __version__
from sokhan.config import get_settings
from sokhan.core.audio import StorageUnavailableError, audio_dir
from sokhan.db import configure, create_all
logger = logging.getLogger("sokhan")
@@ -29,14 +27,6 @@ def create_app() -> FastAPI:
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
configure()
create_all()
try:
audio_dir()
except OSError as exc:
logger.error(
"DATA_DIR is not writable (%s) - uploads will fail with 503 until "
"it is; in Docker check the volume is owned by the app user",
exc,
)
if not settings.celery_enabled:
logger.warning(
"CELERY_ENABLED=false - jobs run inline in the API process; "
@@ -78,14 +68,6 @@ def create_app() -> FastAPI:
app.include_router(routes_openai.router)
app.include_router(routes_admin.router)
@app.exception_handler(StorageUnavailableError)
async def storage_unavailable(request: Request, exc: StorageUnavailableError) -> JSONResponse:
logger.error("upload storage failed for %s %s: %s", request.method, request.url.path, exc)
return JSONResponse(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
content={"detail": "upload storage is unavailable, try again later"},
)
@app.get("/")
def root() -> dict:
return {"name": "Sokhan API", "version": __version__, "docs": "/docs"}
-51
View File
@@ -1,8 +1,5 @@
import io
import shutil
from pathlib import Path
import pytest
from docx import Document
@@ -191,51 +188,3 @@ def test_other_users_cannot_read_a_job(client, auth, wav_bytes, fake_engine):
assert client.get(f"/jobs/{job_id}", headers=headers).status_code == 404
assert client.get("/jobs", headers=headers).json()["total"] == 0
def _make_data_dir_unwritable(tmp_path):
"""Replace DATA_DIR with a plain file, so creating DATA_DIR/audio fails."""
shutil.rmtree(tmp_path / "data")
(tmp_path / "data").write_text("not a directory")
def test_upload_answers_503_when_storage_is_unwritable(
client, auth, wav_bytes, fake_engine, tmp_path
):
_make_data_dir_unwritable(tmp_path)
response = _upload(client, auth, wav_bytes)
assert response.status_code == 503
assert response.json() == {"detail": "upload storage is unavailable, try again later"}
# No job row is left behind for an upload that was never stored.
assert client.get("/jobs", headers=auth).json()["total"] == 0
def test_openai_endpoint_answers_503_when_storage_is_unwritable(
client, auth, wav_bytes, fake_engine, tmp_path
):
_make_data_dir_unwritable(tmp_path)
response = client.post(
"/v1/audio/transcriptions",
files={"file": ("test.wav", wav_bytes, "audio/wav")},
data={"language": "fa", "response_format": "json"},
headers=auth,
)
assert response.status_code == 503
def test_failed_write_removes_the_partial_file(app, tmp_path, monkeypatch):
from sokhan.core.audio import StorageUnavailableError, audio_dir, save_upload
def write_fails_midway(self, data):
self.open("wb").write(data[:1])
raise OSError(28, "No space left on device")
monkeypatch.setattr(Path, "write_bytes", write_fails_midway)
with pytest.raises(StorageUnavailableError):
save_upload(b"RIFF....", "job-1", "clip.wav")
assert list(audio_dir().iterdir()) == []
+2
View File
@@ -53,6 +53,8 @@
"emailPlaceholder": "you@example.com",
"passwordLabel": "Password",
"passwordPlaceholder": "••••••••",
"showPassword": "Show password",
"hidePassword": "Hide password",
"codeLabel": "Connect code",
"codePlaceholder": "Enter your connect code",
"codeHint": "Have a connect code? No email or password needed.",
+2
View File
@@ -53,6 +53,8 @@
"emailPlaceholder": "you@example.com",
"passwordLabel": "رمز عبور",
"passwordPlaceholder": "••••••••",
"showPassword": "نمایش رمز عبور",
"hidePassword": "پنهان کردن رمز عبور",
"codeLabel": "کد اتصال",
"codePlaceholder": "کد اتصال را وارد کن",
"codeHint": "اگر کد اتصال داری، لازم نیست ایمیل و رمز عبور وارد کنی.",
+36 -15
View File
@@ -2,6 +2,7 @@
import { useState, type FormEvent } from "react";
import { useTranslations } from "next-intl";
import { Eye, EyeOff } from "lucide-react";
import { useRouter } from "@/i18n/navigation";
import { ApiError, login, register, setToken, tokenLogin } from "@/lib/api";
@@ -17,6 +18,7 @@ export default function LoginPage() {
const [mode, setMode] = useState<Mode>("login");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [showPassword, setShowPassword] = useState(false);
const [code, setCode] = useState("");
const [emailError, setEmailError] = useState<string | null>(null);
const [passwordError, setPasswordError] = useState<string | null>(null);
@@ -27,6 +29,7 @@ export default function LoginPage() {
function switchMode(next: Mode) {
if (next === mode) return;
setMode(next);
setShowPassword(false);
setEmailError(null);
setPasswordError(null);
setCodeError(null);
@@ -176,21 +179,39 @@ export default function LoginPage() {
>
{t("passwordLabel")}
</label>
<input
id="login-password"
name="password"
type="password"
dir="ltr"
autoComplete={mode === "register" ? "new-password" : "current-password"}
value={password}
onChange={(event) => {
setPassword(event.target.value);
if (passwordError) setPasswordError(null);
}}
placeholder={t("passwordPlaceholder")}
aria-invalid={passwordError ? true : undefined}
className={inputClasses}
/>
{/* The field is always LTR, so the toggle sits at its physical right. */}
<div className="relative" dir="ltr">
<input
id="login-password"
name="password"
type={showPassword ? "text" : "password"}
dir="ltr"
autoComplete={mode === "register" ? "new-password" : "current-password"}
value={password}
onChange={(event) => {
setPassword(event.target.value);
if (passwordError) setPasswordError(null);
}}
placeholder={t("passwordPlaceholder")}
aria-invalid={passwordError ? true : undefined}
className={`${inputClasses} pr-11`}
/>
<button
type="button"
onClick={() => setShowPassword((shown) => !shown)}
aria-label={showPassword ? t("hidePassword") : t("showPassword")}
aria-pressed={showPassword}
aria-controls="login-password"
title={showPassword ? t("hidePassword") : t("showPassword")}
className="absolute inset-y-0 right-0 flex w-11 items-center justify-center rounded-e-lg text-stone-500 transition-colors hover:text-stone-800 focus-visible:ring-2 focus-visible:ring-teal-700"
>
{showPassword ? (
<EyeOff className="h-5 w-5" aria-hidden="true" />
) : (
<Eye className="h-5 w-5" aria-hidden="true" />
)}
</button>
</div>
{passwordError ? (
<p className="mt-1.5 text-sm text-red-700">{passwordError}</p>
) : mode === "register" ? (