Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(i18n): translate onboarding and auth; map server error codes to keys

Juan Denis965ea5c27fe2
diff --git a/backend/app/api/auth.py b/backend/app/api/auth.py
index 5a364a92..bd1f348a 100644
--- a/backend/app/api/auth.py
+++ b/backend/app/api/auth.py
@@ -19,6 +19,7 @@ from app.services import login_link_service
from app.services import auth_throttle_service
from app.utils.client_ip import get_client_ip
from app.utils.i18n import normalize_language
+from app.exceptions import AuthenticationError, ConflictError, PermissionDeniedError, ValidationError
logger = logging.getLogger(__name__)
@@ -77,32 +78,32 @@ def register():
from app.services.invitation_service import InvitationService
invitation = InvitationService.validate_token(invite_token)
if not invitation:
- return jsonify({'error': 'Invalid or expired invitation'}), 400
+ raise ValidationError('Invalid or expired invitation', code='auth.invitation_invalid')
# Check if registration is allowed
is_first_user = User.query.count() == 0
if not is_first_user and not invitation:
if not SettingsService.needs_setup() and not SettingsService.is_registration_enabled():
logger.warning(f"Registration attempt blocked - setup already completed. IP: {request.remote_addr}")
- return jsonify({'error': 'Registration is disabled'}), 403
+ raise PermissionDeniedError('Registration is disabled', code='auth.registration_disabled')
if not SettingsService.is_registration_enabled():
- return jsonify({'error': 'Registration is disabled'}), 403
+ raise PermissionDeniedError('Registration is disabled', code='auth.registration_disabled')
email = data.get('email')
username = data.get('username')
password = data.get('password')
if not all([email, username, password]):
- return jsonify({'error': 'Missing required fields'}), 400
+ raise ValidationError('Missing required fields', code='auth.missing_fields')
if User.query.filter(func.lower(User.email) == func.lower(email)).first():
- return jsonify({'error': 'This email or username is unavailable'}), 409
+ raise ConflictError('This email or username is unavailable', code='auth.identity_unavailable')
if User.query.filter_by(username=username).first():
- return jsonify({'error': 'This email or username is unavailable'}), 409
+ raise ConflictError('This email or username is unavailable', code='auth.identity_unavailable')
if len(password) < 8:
- return jsonify({'error': 'Password must be at least 8 characters'}), 400
+ raise ValidationError('Password must be at least 8 characters', code='auth.password_too_short')
# Determine role and permissions from invitation or defaults
if is_first_user:
@@ -220,7 +221,7 @@ def login():
# Check if password login is disabled (SSO-only mode)
from app.services import sso_service
if not sso_service.is_password_login_allowed():
- return jsonify({'error': 'Password login is disabled. Please use SSO.'}), 403
+ raise PermissionDeniedError('Password login is disabled. Please use SSO.', code='auth.password_login_disabled')
# Per-IP brute-force throttle — checked up front, before any password work,
# so spraying wrong passwords across many usernames from one IP is blocked.
@@ -240,7 +241,7 @@ def login():
password = data.get('password')
if not all([login_id, password]):
- return jsonify({'error': 'Missing email/username or password'}), 400
+ raise ValidationError('Missing email/username or password', code='auth.missing_credentials')
# Try to find user by email (case-insensitive) or username
user = User.query.filter(
@@ -262,7 +263,7 @@ def login():
user.record_failed_login()
AuditService.log_login(user.id, success=False, details={'reason': 'invalid_password'})
db.session.commit()
- return jsonify({'error': 'Invalid username/email or password'}), 401
+ raise AuthenticationError('Invalid username/email or password', code='auth.invalid_credentials')
# Correct password — clear this IP's failure count (covers the 2FA-pending
# and no-2FA paths below).
@@ -271,7 +272,7 @@ def login():
if not user.is_active:
AuditService.log_login(user.id, success=False, details={'reason': 'account_deactivated'})
db.session.commit()
- return jsonify({'error': 'Account is deactivated'}), 403
+ raise PermissionDeniedError('Account is deactivated', code='auth.account_deactivated')
# Check if 2FA is enabled
if user.totp_enabled:
@@ -399,7 +400,7 @@ def redeem_login_link():
if not user:
auth_throttle_service.register_failure(client_ip)
logger.info(f"Login link redeem failed ({reason}) from {client_ip}")
- return jsonify({'error': 'Invalid or expired link'}), 401
+ raise AuthenticationError('Invalid or expired link', code='auth.link_invalid')
auth_throttle_service.reset(client_ip)
user.reset_failed_login()
@@ -521,7 +522,7 @@ def update_current_user():
if 'username' in data:
existing = User.query.filter_by(username=data['username']).first()
if existing and existing.id != user.id:
- return jsonify({'error': 'Username already taken'}), 409
+ raise ConflictError('Username already taken', code='auth.username_taken')
user.username = data['username']
if 'email' in data:
@@ -529,7 +530,7 @@ def update_current_user():
func.lower(User.email) == func.lower(data['email'])
).first()
if existing and existing.id != user.id:
- return jsonify({'error': 'Email already registered'}), 409
+ raise ConflictError('Email already registered', code='auth.email_registered')
user.email = data['email']
if 'password' in data:
diff --git a/backend/tests/ERROR_SHAPE_CEILING b/backend/tests/ERROR_SHAPE_CEILING
index 1b66bc15..23ca55f5 100644
--- a/backend/tests/ERROR_SHAPE_CEILING
+++ b/backend/tests/ERROR_SHAPE_CEILING
@@ -1 +1 @@
-1159
+1145
diff --git a/backend/tests/test_login_links.py b/backend/tests/test_login_links.py
index 78d832ca..9a5cb33d 100644
--- a/backend/tests/test_login_links.py
+++ b/backend/tests/test_login_links.py
@@ -1,6 +1,19 @@
"""One-time login links: mint / redeem / expiry / single-use / IP-bound / RBAC."""
from datetime import datetime, timedelta
+def _assert_link_invalid(response):
+ """The typed-error contract body (plan 76 B), not a bare {'error': ...}.
+
+ `code` is what the frontend maps to a translation key (plan 79 F1), so it
+ is asserted rather than tolerated: dropping it would silently make the
+ message untranslatable again.
+ """
+ body = response.get_json()
+ assert body['error'] == 'Invalid or expired link'
+ assert body['status'] == 401
+ assert body['code'] == 'auth.link_invalid'
+ assert body['request_id']
+
import pytest
# Explicit import so the table registers with SQLAlchemy even though
@@ -87,7 +100,7 @@ def test_redeem_success_and_single_use(client, auth_headers):
# Second redeem fails with a generic error
again = client.post('/api/v1/auth/login-links/redeem', json={'token': token})
assert again.status_code == 401
- assert again.get_json() == {'error': 'Invalid or expired link'}
+ _assert_link_invalid(again)
def test_redeem_expired_link_fails(app, client, auth_headers):
@@ -101,13 +114,13 @@ def test_redeem_expired_link_fails(app, client, auth_headers):
resp = client.post('/api/v1/auth/login-links/redeem', json={'token': token})
assert resp.status_code == 401
- assert resp.get_json() == {'error': 'Invalid or expired link'}
+ _assert_link_invalid(resp)
def test_redeem_unknown_token_fails(client):
resp = client.post('/api/v1/auth/login-links/redeem', json={'token': 'bogus'})
assert resp.status_code == 401
- assert resp.get_json() == {'error': 'Invalid or expired link'}
+ _assert_link_invalid(resp)
def test_ip_bound_link(client, auth_headers):
diff --git a/frontend/scripts/I18N_LITERAL_CEILING b/frontend/scripts/I18N_LITERAL_CEILING
index a7c026f0..7d73dd85 100644
--- a/frontend/scripts/I18N_LITERAL_CEILING
+++ b/frontend/scripts/I18N_LITERAL_CEILING
@@ -1 +1 @@
-8087
+8055
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index 363edd66..58f336c5 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -1,6 +1,39 @@
{
+ "auth": {
+ "backToLogin": "Back to login",
+ "confirmPassword": "Confirm Password",
+ "confirmPasswordPlaceholder": "Confirm your password",
+ "createAccount": "Create Account",
+ "creatingAccount": "Creating account…",
+ "demoMode": "Demo mode — sign in read-only",
+ "email": "Email",
+ "haveAccount": "Already have an account? <0>Sign in</0>",
+ "invitationInvalid": "This invitation is invalid or has expired",
+ "noAccount": "Don't have an account? <0>Create one</0>",
+ "password": "Password",
+ "passwordPlaceholder": "Enter your password",
+ "passwordRule": "At least 8 characters",
+ "registrationDisabled": "Registration is currently disabled",
+ "signIn": "Sign In",
+ "signInSubtitle": "Sign in to your account",
+ "signingIn": "Signing in…",
+ "signingYouIn": "Signing you in…",
+ "twoFactor": {
+ "backupCode": "Backup Code",
+ "backupHint": "Enter a backup code",
+ "codeHint": "Enter the 6-digit code from your authenticator app",
+ "title": "Two-Factor Authentication"
+ },
+ "useDemoCredentials": "Use demo credentials",
+ "username": "Username",
+ "usernameChoose": "Choose a username",
+ "usernameOrEmail": "Username or Email",
+ "usernamePlaceholder": "admin or [email protected]",
+ "validatingInvitation": "Validating invitation…"
+ },
"common": {
"actions": {
+ "back": "Back",
"logOut": "Log out",
"refresh": "Refresh",
"retry": "Retry",
@@ -37,6 +70,22 @@
"minutesShort": "{{count}}m"
}
},
+ "errors": {
+ "auth": {
+ "accountDeactivated": "Account is deactivated",
+ "emailRegistered": "Email already registered",
+ "identityUnavailable": "This email or username is unavailable",
+ "invalidCredentials": "Invalid username/email or password",
+ "invitationInvalid": "Invalid or expired invitation",
+ "linkInvalid": "Invalid or expired link",
+ "missingCredentials": "Missing email/username or password",
+ "missingFields": "Missing required fields",
+ "passwordLoginDisabled": "Password login is disabled. Please use SSO.",
+ "passwordTooShort": "Password must be at least 8 characters",
+ "registrationDisabled": "Registration is disabled",
+ "usernameTaken": "Username already taken"
+ }
+ },
"git": {
"picker": {
"branch": "Branch",
@@ -152,5 +201,9 @@
"manifest": "Docs: serverkit.yaml manifest"
},
"label": "Command palette"
+ },
+ "setup": {
+ "subtitle": "Let’s get your server ready",
+ "welcome": "Welcome to {{panel}}"
}
}
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 3c94179f..7ca49692 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -1,6 +1,39 @@
{
+ "auth": {
+ "backToLogin": "Volver al inicio de sesión",
+ "confirmPassword": "Confirmar contraseña",
+ "confirmPasswordPlaceholder": "Confirma tu contraseña",
+ "createAccount": "Crear cuenta",
+ "creatingAccount": "Creando la cuenta…",
+ "demoMode": "Modo demo: acceso de solo lectura",
+ "email": "Correo electrónico",
+ "haveAccount": "¿Ya tienes una cuenta? <0>Inicia sesión</0>",
+ "invitationInvalid": "Esta invitación no es válida o ha caducado",
+ "noAccount": "¿No tienes una cuenta? <0>Crea una</0>",
+ "password": "Contraseña",
+ "passwordPlaceholder": "Introduce tu contraseña",
+ "passwordRule": "Al menos 8 caracteres",
+ "registrationDisabled": "El registro está desactivado en este momento",
+ "signIn": "Iniciar sesión",
+ "signInSubtitle": "Inicia sesión en tu cuenta",
+ "signingIn": "Iniciando sesión…",
+ "signingYouIn": "Iniciando tu sesión…",
+ "twoFactor": {
+ "backupCode": "Código de recuperación",
+ "backupHint": "Introduce un código de recuperación",
+ "codeHint": "Introduce el código de 6 dígitos de tu app de autenticación",
+ "title": "Autenticación en dos pasos"
+ },
+ "useDemoCredentials": "Usar las credenciales de demo",
+ "username": "Nombre de usuario",
+ "usernameChoose": "Elige un nombre de usuario",
+ "usernameOrEmail": "Nombre de usuario o correo",
+ "usernamePlaceholder": "admin o [email protected]",
+ "validatingInvitation": "Validando la invitación…"
+ },
"common": {
"actions": {
+ "back": "Atrás",
"logOut": "Cerrar sesión",
"refresh": "Actualizar",
"retry": "Reintentar",
@@ -37,6 +70,22 @@
"minutesShort": "{{count}} min"
}
},
+ "errors": {
+ "auth": {
+ "accountDeactivated": "La cuenta está desactivada",
+ "emailRegistered": "Ese correo ya está registrado",
+ "identityUnavailable": "Ese correo o nombre de usuario no está disponible",
+ "invalidCredentials": "Nombre de usuario/correo o contraseña incorrectos",
+ "invitationInvalid": "Invitación no válida o caducada",
+ "linkInvalid": "Enlace no válido o caducado",
+ "missingCredentials": "Falta el correo/nombre de usuario o la contraseña",
+ "missingFields": "Faltan campos obligatorios",
+ "passwordLoginDisabled": "El inicio de sesión con contraseña está desactivado. Usa SSO.",
+ "passwordTooShort": "La contraseña debe tener al menos 8 caracteres",
+ "registrationDisabled": "El registro está desactivado",
+ "usernameTaken": "Ese nombre de usuario ya está en uso"
+ }
+ },
"git": {
"picker": {
"branch": "Rama",
@@ -152,5 +201,9 @@
"manifest": "Documentación: Manifiesto serverkit.yaml"
},
"label": "Paleta de comandos"
+ },
+ "setup": {
+ "subtitle": "Vamos a dejar tu servidor listo",
+ "welcome": "Te damos la bienvenida a {{panel}}"
}
}
diff --git a/frontend/src/pages/Login.jsx b/frontend/src/pages/Login.jsx
index 76e81b66..e2697c27 100644
--- a/frontend/src/pages/Login.jsx
+++ b/frontend/src/pages/Login.jsx
@@ -1,5 +1,6 @@
import { useState, useRef, useEffect } from 'react';
import { useNavigate, Link, useLocation } from 'react-router-dom';
+import { Trans, useTranslation } from 'react-i18next';
import { useAuth } from '../contexts/AuthContext';
import api from '../services/api';
import SSOProviderIcon from '../components/SSOProviderIcon';
@@ -11,6 +12,7 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
const Login = () => {
+ const { t } = useTranslation();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
@@ -218,8 +220,10 @@ const Login = () => {
<div className="brand-logo">
<ServerKitLogo width={40} height={40} />
</div>
- <h1>Two-Factor Authentication</h1>
- <p>{useBackupCode ? 'Enter a backup code' : 'Enter the 6-digit code from your authenticator app'}</p>
+ <h1>{t('auth.twoFactor.title', 'Two-Factor Authentication')}</h1>
+ <p>{useBackupCode
+ ? t('auth.twoFactor.backupHint', 'Enter a backup code')
+ : t('auth.twoFactor.codeHint', 'Enter the 6-digit code from your authenticator app')}</p>
</div>
{error && <div className="error-message">{error}</div>}
@@ -245,7 +249,7 @@ const Login = () => {
</div>
) : (
<div className="form-group">
- <Label htmlFor="backupCode">Backup Code</Label>
+ <Label htmlFor="backupCode">{t('auth.twoFactor.backupCode', 'Backup Code')}</Label>
<Input
type="text"
id="backupCode"
@@ -275,7 +279,7 @@ const Login = () => {
variant="link"
onClick={handleBack}
>
- Back to login
+ {t('auth.backToLogin', 'Back to login')}
</Button>
</div>
</AuthLayout>
@@ -291,7 +295,7 @@ const Login = () => {
<ServerKitLogo width={40} height={40} />
</div>
<h1>{publicTitle}</h1>
- <p>Signing you in…</p>
+ <p>{t('auth.signingYouIn', 'Signing you in…')}</p>
</div>
</AuthLayout>
);
@@ -305,19 +309,19 @@ const Login = () => {
<ServerKitLogo width={40} height={40} />
</div>
<h1>{publicTitle}</h1>
- <p>Sign in to your account</p>
+ <p>{t('auth.signInSubtitle', 'Sign in to your account')}</p>
</div>
{error && <div className="error-message">{error}</div>}
{demoInfo && (
<div className="demo-hint">
- <div className="demo-hint__title">Demo mode — sign in read-only</div>
+ <div className="demo-hint__title">{t('auth.demoMode', 'Demo mode — sign in read-only')}</div>
<div className="demo-hint__creds">
<code>{demoInfo.username}</code> / <code>{demoInfo.password}</code>
</div>
<Button type="button" variant="link" className="demo-hint__fill" onClick={fillDemoCredentials}>
- Use demo credentials
+ {t('auth.useDemoCredentials', 'Use demo credentials')}
</Button>
</div>
)}
@@ -347,39 +351,43 @@ const Login = () => {
{passwordLoginEnabled && (
<form onSubmit={handleSubmit}>
<div className="form-group">
- <Label htmlFor="email">Username or Email</Label>
+ <Label htmlFor="email">{t('auth.usernameOrEmail', 'Username or Email')}</Label>
<Input
type="text"
id="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
- placeholder="admin or [email protected]"
+ placeholder={t('auth.usernamePlaceholder', 'admin or [email protected]')}
required
autoComplete="username"
/>
</div>
<div className="form-group">
- <Label htmlFor="password">Password</Label>
+ <Label htmlFor="password">{t('auth.password', 'Password')}</Label>
<Input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
- placeholder="Enter your password"
+ placeholder={t('auth.passwordPlaceholder', 'Enter your password')}
required
/>
</div>
<Button type="submit" className="btn-full" disabled={loading}>
- {loading ? 'Signing in...' : 'Sign In'}
+ {loading ? t('auth.signingIn', 'Signing in…') : t('auth.signIn', 'Sign In')}
</Button>
</form>
)}
{registrationEnabled && passwordLoginEnabled && (
<p className="auth-footer">
- Don&apos;t have an account? <Link to="/register">Create one</Link>
+ <Trans
+ i18nKey="auth.noAccount"
+ defaults="Don't have an account? <0>Create one</0>"
+ components={[<Link key="register" to="/register" />]}
+ />
</p>
)}
</AuthLayout>
diff --git a/frontend/src/pages/Register.jsx b/frontend/src/pages/Register.jsx
index 3c777c06..72e3683b 100644
--- a/frontend/src/pages/Register.jsx
+++ b/frontend/src/pages/Register.jsx
@@ -1,5 +1,6 @@
import { useState, useEffect } from 'react';
import { useNavigate, Link, useSearchParams } from 'react-router-dom';
+import { Trans, useTranslation } from 'react-i18next';
import { useAuth } from '../contexts/AuthContext';
import api from '../services/api';
import ServerKitLogo from '../components/ServerKitLogo';
@@ -8,6 +9,7 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
const Register = () => {
+ const { t } = useTranslation();
const [email, setEmail] = useState('');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
@@ -47,10 +49,14 @@ const Register = () => {
<ServerKitLogo width={40} height={40} />
</div>
<h1>{publicTitle}</h1>
- <p>Registration is currently disabled</p>
+ <p>{t('auth.registrationDisabled', 'Registration is currently disabled')}</p>
</div>
<p className="auth-footer">
- Already have an account? <Link to="/login">Sign in</Link>
+ <Trans
+ i18nKey="auth.haveAccount"
+ defaults="Already have an account? <0>Sign in</0>"
+ components={[<Link key="login" to="/login" />]}
+ />
</p>
</div>
</div>
@@ -66,7 +72,7 @@ const Register = () => {
<ServerKitLogo width={40} height={40} />
</div>
<h1>{publicTitle}</h1>
- <p>Validating invitation...</p>
+ <p>{t('auth.validatingInvitation', 'Validating invitation…')}</p>
</div>
</div>
</div>
@@ -82,10 +88,14 @@ const Register = () => {
<ServerKitLogo width={40} height={40} />
</div>
<h1>{publicTitle}</h1>
- <p>This invitation is invalid or has expired</p>
+ <p>{t('auth.invitationInvalid', 'This invitation is invalid or has expired')}</p>
</div>
<p className="auth-footer">
- Already have an account? <Link to="/login">Sign in</Link>
+ <Trans
+ i18nKey="auth.haveAccount"
+ defaults="Already have an account? <0>Sign in</0>"
+ components={[<Link key="login" to="/login" />]}
+ />
</p>
</div>
</div>
@@ -133,7 +143,7 @@ const Register = () => {
<form onSubmit={handleSubmit}>
<div className="form-group">
- <Label htmlFor="email">Email</Label>
+ <Label htmlFor="email">{t('auth.email', 'Email')}</Label>
<Input
type="email"
id="email"
@@ -146,48 +156,52 @@ const Register = () => {
</div>
<div className="form-group">
- <Label htmlFor="username">Username</Label>
+ <Label htmlFor="username">{t('auth.username', 'Username')}</Label>
<Input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
- placeholder="Choose a username"
+ placeholder={t('auth.usernameChoose', 'Choose a username')}
required
/>
</div>
<div className="form-group">
- <Label htmlFor="password">Password</Label>
+ <Label htmlFor="password">{t('auth.password', 'Password')}</Label>
<Input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
- placeholder="At least 8 characters"
+ placeholder={t('auth.passwordRule', 'At least 8 characters')}
required
/>
</div>
<div className="form-group">
- <Label htmlFor="confirmPassword">Confirm Password</Label>
+ <Label htmlFor="confirmPassword">{t('auth.confirmPassword', 'Confirm Password')}</Label>
<Input
type="password"
id="confirmPassword"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
- placeholder="Confirm your password"
+ placeholder={t('auth.confirmPasswordPlaceholder', 'Confirm your password')}
required
/>
</div>
<Button type="submit" className="btn-full" disabled={loading}>
- {loading ? 'Creating account...' : 'Create Account'}
+ {loading ? t('auth.creatingAccount', 'Creating account…') : t('auth.createAccount', 'Create Account')}
</Button>
</form>
<p className="auth-footer">
- Already have an account? <Link to="/login">Sign in</Link>
+ <Trans
+ i18nKey="auth.haveAccount"
+ defaults="Already have an account? <0>Sign in</0>"
+ components={[<Link key="login" to="/login" />]}
+ />
</p>
</div>
</div>
diff --git a/frontend/src/pages/Setup.jsx b/frontend/src/pages/Setup.jsx
index de0de67a..b5edc8cc 100644
--- a/frontend/src/pages/Setup.jsx
+++ b/frontend/src/pages/Setup.jsx
@@ -9,6 +9,7 @@ import SetupStepCapacity from '../components/setup/SetupStepCapacity';
import SetupStepSecurity from '../components/setup/SetupStepSecurity';
import SetupStepSummary from '../components/setup/SetupStepSummary';
import { Button } from '@/components/ui/button';
+import { useTranslation } from 'react-i18next';
const TOTAL_STEPS = 5;
@@ -21,6 +22,7 @@ const STEP_TITLES = [
];
const Setup = () => {
+ const { t } = useTranslation();
const { isAuthenticated, completeOnboarding, publicTitle } = useAuth();
const navigate = useNavigate();
@@ -129,8 +131,8 @@ const Setup = () => {
<div className="wizard-card">
<div className="wizard-header">
<ServerKitLogo className="wizard-logo" width={48} height={48} />
- <h1>Welcome to {publicTitle}</h1>
- <p>Let&apos;s get your server ready</p>
+ <h1>{t('setup.welcome', 'Welcome to {{panel}}', { panel: publicTitle })}</h1>
+ <p>{t('setup.subtitle', 'Let’s get your server ready')}</p>
</div>
{renderProgressBar()}
@@ -142,7 +144,7 @@ const Setup = () => {
onClick={handleBack}
>
<ArrowLeft size={16} />
- Back
+ {t('common.actions.back', 'Back')}
</Button>
)}
diff --git a/frontend/src/services/api/client.js b/frontend/src/services/api/client.js
index d7cdbf59..76ccd49a 100644
--- a/frontend/src/services/api/client.js
+++ b/frontend/src/services/api/client.js
@@ -1,5 +1,6 @@
// Base HTTP client - constructor, token management, core request methods
import { workspaceStore } from '../workspaceStore.js';
+import { translateServerError } from './errorCodes';
const AUTH_EXPIRED_EVENT = 'serverkit:auth-expired';
@@ -199,8 +200,16 @@ class ApiClient {
try {
fallback += `: ${new URL(response.url).pathname}`;
} catch { /* keep the status-only message */ }
- const err = new Error(data.error || data.msg || fallback);
+ // Plan 79 F1: when the route names a machine `code`, the message
+ // becomes translatable — `errors.<code>` with the server's own
+ // English as the inline default, so an un-keyed code degrades to
+ // exactly today's behaviour. The 257 `toast.error(err.message)`
+ // sites keep working unchanged and gain translations as codes land.
+ const serverMessage = data.error || data.msg || fallback;
+ const err = new Error(translateServerError(data.code, serverMessage));
err.status = response.status;
+ err.code = data.code || null;
+ err.serverMessage = serverMessage;
err.data = data;
throw err;
}
diff --git a/frontend/src/services/api/errorCodes.js b/frontend/src/services/api/errorCodes.js
new file mode 100644
index 00000000..a5828988
--- /dev/null
+++ b/frontend/src/services/api/errorCodes.js
@@ -0,0 +1,69 @@
+import { t } from '../../i18n';
+
+/**
+ * Translate a server error by its machine code (plan 79 F1).
+ *
+ * The problem: 257 render sites do `toast.error(err.message)`, showing a
+ * string the backend authored in English. There is no key to translate
+ * against, and the frontend cannot invent one — the same prose comes from
+ * several routes and a route can change its wording.
+ *
+ * The backend already answers this. Plan 76 milestone B's typed-error door
+ * (`app/exceptions.py` + the global handler) emits a stable body:
+ *
+ * { "error": "Invalid username/email or password",
+ * "status": 401, "code": "auth.invalid_credentials", "request_id": "…" }
+ *
+ * so this maps `code` to a key, once, in the client.
+ *
+ * WHY A LITERAL REGISTRY RATHER THAN `t('errors.' + code)`: a computed key is
+ * invisible to the extractor, so it would never appear in en.json and a
+ * translator would have no way to discover that the string exists. The table
+ * below is the list of server errors we have actually translated; anything
+ * else falls through to the server's English, which is exactly today's
+ * behaviour.
+ *
+ * WHY ONLY AUTH CODES SO FAR: plan 76 §C measured 23 sites that pick an HTTP
+ * status by grepping their own error prose (`403 if 'denied' in error else
+ * 400`). Until those services raise typed errors, translating that prose would
+ * turn those 403s into 400s. The auth and onboarding routes carry codes today;
+ * the rest waits on plan 76 milestone C rather than shipping a silent status
+ * regression.
+ */
+function translatedServerErrors() {
+ return {
+ 'auth.invalid_credentials': t(
+ 'errors.auth.invalidCredentials', 'Invalid username/email or password'),
+ 'auth.account_deactivated': t(
+ 'errors.auth.accountDeactivated', 'Account is deactivated'),
+ 'auth.registration_disabled': t(
+ 'errors.auth.registrationDisabled', 'Registration is disabled'),
+ 'auth.password_login_disabled': t(
+ 'errors.auth.passwordLoginDisabled', 'Password login is disabled. Please use SSO.'),
+ 'auth.missing_credentials': t(
+ 'errors.auth.missingCredentials', 'Missing email/username or password'),
+ 'auth.missing_fields': t(
+ 'errors.auth.missingFields', 'Missing required fields'),
+ 'auth.password_too_short': t(
+ 'errors.auth.passwordTooShort', 'Password must be at least 8 characters'),
+ 'auth.identity_unavailable': t(
+ 'errors.auth.identityUnavailable', 'This email or username is unavailable'),
+ 'auth.username_taken': t(
+ 'errors.auth.usernameTaken', 'Username already taken'),
+ 'auth.email_registered': t(
+ 'errors.auth.emailRegistered', 'Email already registered'),
+ 'auth.invitation_invalid': t(
+ 'errors.auth.invitationInvalid', 'Invalid or expired invitation'),
+ 'auth.link_invalid': t(
+ 'errors.auth.linkInvalid', 'Invalid or expired link'),
+ };
+}
+
+export function translateServerError(code, serverMessage) {
+ if (!code || typeof code !== 'string') return serverMessage;
+ // Built per call, not at module load: a table resolved at import would
+ // freeze the language of the session's first paint.
+ return translatedServerErrors()[code] ?? serverMessage;
+}
+
+export default translateServerError;