Open-source personal finance manager. Self-hosted, privacy-first.
fix(passkeys): bind WebAuthn to the origin the browser is on (#419)
Tássio Noronha296106d15d0c
diff --git a/.env.example b/.env.exampleindex d1130d97..f6548690 100644--- a/.env.example+++ b/.env.example@@ -40,6 +40,25 @@ ENABLE_BANKING_OAUTH_REDIRECT_URI=http://localhost:${FRONTEND_PORT:-3000}/oauth/# disable (e.g. to avoid the dependency on the Brazilian government CSV endpoint).# TESOURO_DIRETO_ENABLED=false+# Passkeys (optional) — nothing to set for the common cases.+## Passkeys follow the address you open the app on, so they work out of the box on+## http://localhost:3000 and on any HTTPS domain behind a reverse proxy.+##+## Two limits come from the WebAuthn standard itself, not from Securo:+## - an IP address (http://192.168.1.10:3000) can never be used for passkeys+## - plain HTTP can never be used, except on localhost+## Reach the app on a domain over HTTPS, or on http://localhost, to use passkeys.+##+## Set FRONTEND_URL when the app is served from a domain — it is also used for+## CORS and OAuth callbacks.+# FRONTEND_URL=https://securo.example.com+##+## Optional: pin passkeys to a single domain. Leave unset to follow the browser.+## Set it to the parent domain if you reach the app on several subdomains.+# WEBAUTHN_RP_ID=securo.example.com+## Optional: the name shown in the browser's passkey prompt.+# WEBAUTHN_RP_NAME=Securo+# Host ports (optional) — change these to avoid conflicts with other services## Default values are set in docker-compose.yml and docker-compose.prod.yml.## Example:diff --git a/README.md b/README.mdindex db2b78cf..b456db62 100644--- a/README.md+++ b/README.md@@ -129,6 +129,23 @@ OIDC_WORKSPACE_ROLE_MAP={"securo-owners":"owner","securo-editors":"editor","secu`OIDC_ADMIN_ROLES` grants or revokes Securo admin (`is_superuser`) on each OIDC login. `OIDC_WORKSPACE_ROLE_MAP` maps provider roles/groups to the user's Personal workspace role (`owner`, `editor`, or `viewer`); if multiple mapped roles are present, Securo applies the highest permission. Leave `OIDC_SYNC_ROLES=false` to keep all Securo roles managed locally.+## Passkeys (Optional)++Sign in with Touch ID, Face ID, Windows Hello, or a security key. Passkeys are on by default and need no configuration: they follow whatever address you open Securo on.++Two rules come from the WebAuthn standard itself, and no setting can work around them:++- **An IP address is never valid.** `http://192.168.1.10:3000` cannot register passkeys.+- **Plain HTTP is never valid, except on `localhost`.**++So use passkeys on `http://localhost:3000`, or put Securo on a domain behind an HTTPS reverse proxy. When serving from a domain, point `FRONTEND_URL` at it (this also covers CORS and OAuth callbacks):++```+FRONTEND_URL=https://securo.example.com+```++To pin passkeys to one domain, set `WEBAUTHN_RP_ID` (use the parent domain if you reach Securo on several subdomains). Otherwise Securo follows the browser, and requests from an unusable address get an explanation in the UI instead of a silent failure.+## Exchange Rates (Optional)For automatic currency conversion, add a free [Open Exchange Rates](https://openexchangerates.org/) key to `.env`:diff --git a/backend/app/api/passkeys.py b/backend/app/api/passkeys.pyindex 1be1d674..fe31514f 100644--- a/backend/app/api/passkeys.py+++ b/backend/app/api/passkeys.py@@ -4,7 +4,7 @@ import uuidfrom datetime import datetime, timezonefrom typing import Any-from fastapi import APIRouter, Depends, HTTPException, Response, status+from fastapi import APIRouter, Depends, HTTPException, Request, Response, statusfrom sqlalchemy import func, selectfrom sqlalchemy.exc import IntegrityErrorfrom sqlalchemy.ext.asyncio import AsyncSession@@ -29,6 +29,7 @@ from app.core.config import get_settingsfrom app.core.database import get_async_sessionfrom app.core.rate_limit import login_rate_limitfrom app.core.redis import get_redis+from app.core.webauthn import resolve_webauthn_contextfrom app.api.two_factor import _parse_temp_token_payloadfrom app.models.passkey import UserPasskeyfrom app.models.user import User@@ -123,6 +124,9 @@ async def _pop_challenge(prefix: str, challenge_id: str) -> dict[str, Any] | Nonreturn Noneif not isinstance(payload, dict):return None+ # Challenges issued before the ceremony was bound to an origin cannot be verified.+ if not payload.get("rp_id") or not payload.get("origin"):+ return Nonereturn payload@@ -144,13 +148,12 @@ async def _verify_passkey_credential(passkey: UserPasskey,session: AsyncSession,) -> User:- settings = get_settings()try:verification = verify_authentication_response(credential=_credential_json(credential),expected_challenge=base64url_to_bytes(challenge["challenge"]),- expected_origin=settings.resolved_webauthn_origin,- expected_rp_id=settings.resolved_webauthn_rp_id,+ expected_origin=challenge["origin"],+ expected_rp_id=challenge["rp_id"],credential_public_key=base64url_to_bytes(passkey.public_key),credential_current_sign_count=passkey.sign_count,require_user_verification=True,@@ -188,11 +191,13 @@ async def list_passkeys(@router.post("/passkeys/register/options", response_model=PasskeyOptionsResponse)async def passkey_registration_options(+ request: Request,body: PasskeyRegisterOptionsRequest,user: User = Depends(current_active_user),session: AsyncSession = Depends(get_async_session),):settings = get_settings()+ context = resolve_webauthn_context(request)existing = await session.execute(select(UserPasskey).where(UserPasskey.user_id == user.id))exclude_credentials = [PublicKeyCredentialDescriptor(id=base64url_to_bytes(passkey.credential_id))@@ -200,7 +205,7 @@ async def passkey_registration_options(]options = generate_registration_options(- rp_id=settings.resolved_webauthn_rp_id,+ rp_id=context.rp_id,rp_name=settings.webauthn_rp_name,user_id=str(user.id).encode("utf-8"),user_name=user.email,@@ -219,6 +224,8 @@ async def passkey_registration_options("challenge": bytes_to_base64url(options.challenge),"user_id": str(user.id),"name": body.name,+ "rp_id": context.rp_id,+ "origin": context.origin,},)return PasskeyOptionsResponse(challenge_id=challenge_id, options=_options_dict(options))@@ -230,7 +237,6 @@ async def verify_passkey_registration(user: User = Depends(current_active_user),session: AsyncSession = Depends(get_async_session),):- settings = get_settings()challenge = await _pop_challenge(REGISTER_CHALLENGE_PREFIX, body.challenge_id)if not challenge or challenge.get("user_id") != str(user.id):raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired challenge")@@ -239,8 +245,8 @@ async def verify_passkey_registration(verification = verify_registration_response(credential=_credential_json(body.credential),expected_challenge=base64url_to_bytes(challenge["challenge"]),- expected_origin=settings.resolved_webauthn_origin,- expected_rp_id=settings.resolved_webauthn_rp_id,+ expected_origin=challenge["origin"],+ expected_rp_id=challenge["rp_id"],require_user_verification=True,)except Exception as exc:@@ -291,10 +297,11 @@ async def delete_passkey(dependencies=[Depends(login_rate_limit)],)async def passkey_authentication_options(+ request: Request,body: PasskeyAuthenticateOptionsRequest,session: AsyncSession = Depends(get_async_session),):- settings = get_settings()+ context = resolve_webauthn_context(request)email = body.email.strip().lower() if body.email else Noneexpected_user_id: str | None = None@@ -305,7 +312,7 @@ async def passkey_authentication_options(expected_user_id = str(login_user.id)options = generate_authentication_options(- rp_id=settings.resolved_webauthn_rp_id,+ rp_id=context.rp_id,user_verification=UserVerificationRequirement.REQUIRED,)challenge_id = await _store_challenge(@@ -314,6 +321,8 @@ async def passkey_authentication_options("challenge": bytes_to_base64url(options.challenge),"email_bound": email is not None,"expected_user_id": expected_user_id,+ "rp_id": context.rp_id,+ "origin": context.origin,},)return PasskeyOptionsResponse(challenge_id=challenge_id, options=_options_dict(options))@@ -356,10 +365,11 @@ async def verify_passkey_authentication(@router.post("/passkeys/2fa/options", response_model=PasskeyOptionsResponse, dependencies=[Depends(login_rate_limit)])async def passkey_second_factor_options(+ request: Request,body: PasskeySecondFactorOptionsRequest,session: AsyncSession = Depends(get_async_session),):- settings = get_settings()+ context = resolve_webauthn_context(request)user_id = await _get_second_factor_user_id(body.temp_token)result = await session.execute(select(UserPasskey).where(UserPasskey.user_id == uuid.UUID(user_id)).order_by(UserPasskey.created_at.asc())@@ -369,7 +379,7 @@ async def passkey_second_factor_options(raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")options = generate_authentication_options(- rp_id=settings.resolved_webauthn_rp_id,+ rp_id=context.rp_id,user_verification=UserVerificationRequirement.REQUIRED,allow_credentials=[PublicKeyCredentialDescriptor(id=base64url_to_bytes(passkey.credential_id))@@ -378,7 +388,12 @@ async def passkey_second_factor_options()challenge_id = await _store_challenge(SECOND_FACTOR_CHALLENGE_PREFIX,- {"challenge": bytes_to_base64url(options.challenge), "user_id": user_id},+ {+ "challenge": bytes_to_base64url(options.challenge),+ "user_id": user_id,+ "rp_id": context.rp_id,+ "origin": context.origin,+ },)return PasskeyOptionsResponse(challenge_id=challenge_id, options=_options_dict(options))diff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex 6ce0c4ad..20150478 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -1,7 +1,6 @@from functools import lru_cachefrom os import getenvfrom pathlib import Path-from urllib.parse import urlparsefrom pydantic import SecretStrfrom pydantic_settings import BaseSettings, SettingsConfigDict@@ -49,23 +48,15 @@ class Settings(BaseSettings):# WebAuthn / passkeyswebauthn_rp_name: str = "Securo"- # Empty means derive from frontend_url host, e.g. localhost for http://localhost:5173.+ # Empty means the RP ID follows the domain the browser is on, which is what+ # most deployments want. Set it to pin passkeys to one domain (e.g.+ # securo.example.com); requests from other origins are then rejected.webauthn_rp_id: str = ""- # Empty means use frontend_url. Must match the browser origin exactly.+ # Empty means the expected origin follows the browser. Only set this when the+ # app is reached at exactly one origin and you want it enforced.webauthn_origin: str = ""webauthn_challenge_ttl_seconds: int = 300- @property- def resolved_webauthn_origin(self) -> str:- return self.webauthn_origin or self.frontend_url-- @property- def resolved_webauthn_rp_id(self) -> str:- if self.webauthn_rp_id:- return self.webauthn_rp_id- parsed = urlparse(self.frontend_url)- return parsed.hostname or "localhost"-# Defaultsdefault_currency: str = "USD" # fallback currency when user preference is unavailablediff --git a/backend/app/core/webauthn.py b/backend/app/core/webauthn.pynew file mode 100644index 00000000..bf6e03ad--- /dev/null+++ b/backend/app/core/webauthn.py@@ -0,0 +1,142 @@+"""Relying-party resolution for WebAuthn.++WebAuthn requires the relying-party ID to be equal to, or a registrable domain+suffix of, the effective domain of the origin the browser is on. A single+configured URL cannot satisfy that for every way a self-hosted deployment is+reached (localhost, a LAN address, a reverse-proxied domain), so the RP ID and+the expected origin are resolved per request instead, from the origin the+browser actually used.++Setting ``WEBAUTHN_RP_ID`` pins the RP ID; requests from an origin outside that+domain are then rejected rather than silently issuing credentials the browser+will refuse.+"""++from dataclasses import dataclass+from ipaddress import ip_address++from fastapi import HTTPException, Request, status++from app.core.config import get_settings+++@dataclass(frozen=True)+class WebAuthnContext:+ """The relying-party ID and browser origin a ceremony is bound to."""++ rp_id: str+ origin: str+++def _error(code: str, message: str) -> HTTPException:+ return HTTPException(+ status_code=status.HTTP_400_BAD_REQUEST,+ detail={"code": code, "message": message},+ )+++def is_ip_literal(hostname: str) -> bool:+ try:+ ip_address(hostname.strip("[]"))+ except ValueError:+ return False+ return True+++def _is_secure_origin(scheme: str, hostname: str) -> bool:+ # Browsers treat http://localhost as a secure context; every other plain-http+ # origin fails the secure-context check before WebAuthn is even reached.+ if scheme == "https":+ return True+ return scheme == "http" and (hostname == "localhost" or hostname.endswith(".localhost"))+++def _is_registrable_suffix(hostname: str, rp_id: str) -> bool:+ return hostname == rp_id or hostname.endswith(f".{rp_id}")+++def _split_origin(origin: str) -> tuple[str, str, int | None]:+ """Split an origin into (scheme, hostname, port) without pulling in urlparse quirks."""+ scheme, separator, remainder = origin.partition("://")+ if not separator or not remainder:+ raise _error("passkey_origin_invalid", "The request origin could not be understood.")++ scheme = scheme.lower()+ host = remainder.split("/", 1)[0]++ if host.startswith("["): # IPv6 literal, e.g. [::1]:3000+ closing = host.find("]")+ if closing == -1:+ raise _error("passkey_origin_invalid", "The request origin could not be understood.")+ hostname = host[: closing + 1]+ port_part = host[closing + 1 :].lstrip(":")+ else:+ hostname, _, port_part = host.partition(":")++ if not hostname:+ raise _error("passkey_origin_invalid", "The request origin could not be understood.")++ try:+ port = int(port_part) if port_part else None+ except ValueError:+ raise _error("passkey_origin_invalid", "The request origin could not be understood.") from None++ return scheme, hostname.lower(), port+++def _request_origin(request: Request) -> str:+ """The origin the browser is on, from the Origin header or the proxied Host."""+ origin = request.headers.get("origin")+ if origin and origin != "null":+ return origin++ # Non-browser clients and some proxies drop Origin; fall back to the host the+ # request was addressed to, honouring the proxy's forwarded scheme.+ host = request.headers.get("x-forwarded-host") or request.headers.get("host")+ if not host:+ raise _error(+ "passkey_origin_missing",+ "The request did not include an origin, so the passkey domain could not be determined.",+ )+ forwarded_proto = request.headers.get("x-forwarded-proto", "").split(",")[0].strip()+ scheme = forwarded_proto or request.url.scheme+ return f"{scheme}://{host}"+++def resolve_webauthn_context(request: Request) -> WebAuthnContext:+ """Resolve the RP ID and expected origin for a passkey ceremony.++ Raises a 400 with a machine-readable ``code`` when the origin can never+ support passkeys, so the UI can explain why instead of surfacing an opaque+ browser ``SecurityError``.+ """+ settings = get_settings()+ origin = _request_origin(request)+ scheme, hostname, _ = _split_origin(origin)++ if is_ip_literal(hostname):+ raise _error(+ "passkey_origin_ip",+ "Passkeys cannot be used on an IP address. Open the app on a domain name over HTTPS, "+ "or on http://localhost.",+ )++ if not _is_secure_origin(scheme, hostname):+ raise _error(+ "passkey_origin_insecure",+ "Passkeys require a secure connection. Open the app over HTTPS, or on http://localhost.",+ )++ configured_rp_id = settings.webauthn_rp_id.strip().lower()+ if configured_rp_id:+ if not _is_registrable_suffix(hostname, configured_rp_id):+ raise _error(+ "passkey_origin_mismatch",+ f"This app is reached at '{hostname}', which is outside the configured passkey domain "+ f"'{configured_rp_id}'. Update WEBAUTHN_RP_ID or open the app on that domain.",+ )+ rp_id = configured_rp_id+ else:+ rp_id = hostname++ return WebAuthnContext(rp_id=rp_id, origin=settings.webauthn_origin.strip() or origin)diff --git a/backend/tests/test_passkeys.py b/backend/tests/test_passkeys.pyindex 08256a58..0ba04387 100644--- a/backend/tests/test_passkeys.py+++ b/backend/tests/test_passkeys.py@@ -38,6 +38,17 @@ class _RedisStore:self.store.pop(key, None)+BROWSER_ORIGIN = "https://securo.test"++[email protected](autouse=True)+def _browser_origin(client: AsyncClient):+ """Passkey ceremonies are bound to the origin the browser is on."""+ client.headers["origin"] = BROWSER_ORIGIN+ yield+ client.headers.pop("origin", None)++@pytest.fixture(autouse=True)def _passkey_redis_store(_mock_redis):redis = _RedisStore()@@ -494,3 +505,144 @@ async def test_register_verify_deletes_challenge_after_failure(_passkey_redis_store.getdel.assert_called_once()_passkey_redis_store.delete.assert_not_called()assert _passkey_redis_store.store == {}+++# --- Relying-party resolution -------------------------------------------------+# The RP ID must match the domain the browser is on, or the browser refuses the+# credential with a SecurityError. See issues #403 and #410.+++async def _register_options(client: AsyncClient, auth_headers: dict, origin: str):+ return await client.post(+ "/api/auth/passkeys/register/options",+ json={"name": "YubiKey"},+ headers={**auth_headers, "origin": origin},+ )+++async def test_register_options_derive_rp_id_from_request_origin(+ client: AsyncClient,+ auth_headers: dict,+):+ response = await _register_options(client, auth_headers, "https://money.example.com")++ assert response.status_code == 200+ assert response.json()["options"]["rp"]["id"] == "money.example.com"+++async def test_register_options_allow_http_localhost(client: AsyncClient, auth_headers: dict):+ response = await _register_options(client, auth_headers, "http://localhost:3000")++ assert response.status_code == 200+ assert response.json()["options"]["rp"]["id"] == "localhost"+++async def test_register_options_reject_ip_origin(client: AsyncClient, auth_headers: dict):+ response = await _register_options(client, auth_headers, "http://192.168.4.10:3000")++ assert response.status_code == 400+ assert response.json()["detail"]["code"] == "passkey_origin_ip"+++async def test_register_options_reject_loopback_ip_origin(client: AsyncClient, auth_headers: dict):+ # A secure context, but 127.0.0.1 is still an IP and can never be an RP ID.+ response = await _register_options(client, auth_headers, "http://127.0.0.1:3000")++ assert response.status_code == 400+ assert response.json()["detail"]["code"] == "passkey_origin_ip"+++async def test_register_options_reject_insecure_origin(client: AsyncClient, auth_headers: dict):+ response = await _register_options(client, auth_headers, "http://securo.example.com")++ assert response.status_code == 400+ assert response.json()["detail"]["code"] == "passkey_origin_insecure"+++async def test_register_options_use_configured_rp_id_for_subdomain(+ client: AsyncClient,+ auth_headers: dict,+):+ settings = SimpleNamespace(webauthn_rp_id="example.com", webauthn_origin="", webauthn_rp_name="Securo")+ with patch("app.core.webauthn.get_settings", return_value=settings):+ response = await _register_options(client, auth_headers, "https://money.example.com")++ assert response.status_code == 200+ assert response.json()["options"]["rp"]["id"] == "example.com"+++async def test_register_options_reject_origin_outside_configured_rp_id(+ client: AsyncClient,+ auth_headers: dict,+):+ settings = SimpleNamespace(webauthn_rp_id="example.com", webauthn_origin="", webauthn_rp_name="Securo")+ with patch("app.core.webauthn.get_settings", return_value=settings):+ response = await _register_options(client, auth_headers, "https://not-example.com")++ assert response.status_code == 400+ assert response.json()["detail"]["code"] == "passkey_origin_mismatch"+++async def test_register_options_fall_back_to_forwarded_host(client: AsyncClient, auth_headers: dict):+ client.headers.pop("origin")+ response = await client.post(+ "/api/auth/passkeys/register/options",+ json={"name": "YubiKey"},+ headers={+ **auth_headers,+ "x-forwarded-host": "money.example.com",+ "x-forwarded-proto": "https",+ },+ )++ assert response.status_code == 200+ assert response.json()["options"]["rp"]["id"] == "money.example.com"+++async def test_authenticate_options_derive_rp_id_from_request_origin(client: AsyncClient):+ response = await client.post(+ "/api/auth/passkeys/authenticate/options",+ json={},+ headers={"origin": "https://money.example.com"},+ )++ assert response.status_code == 200+ assert response.json()["options"]["rpId"] == "money.example.com"+++async def test_register_verify_uses_the_origin_the_challenge_was_issued_for(+ client: AsyncClient,+ auth_headers: dict,+):+ options_response = await _register_options(client, auth_headers, "https://money.example.com")+ challenge_id = options_response.json()["challenge_id"]++ verification = SimpleNamespace(+ credential_id=b"credential-1",+ credential_public_key=b"public-key-1",+ sign_count=1,+ aaguid="test-aaguid",+ fmt="none",+ credential_type="public-key",+ )+ with patch("app.api.passkeys.verify_registration_response", return_value=verification) as verify_mock:+ response = await client.post(+ "/api/auth/passkeys/register/verify",+ json={+ "challenge_id": challenge_id,+ "name": "YubiKey",+ "credential": {+ "id": "credential-1",+ "rawId": "Y3JlZGVudGlhbC0x",+ "response": {"attestationObject": "YXR0", "clientDataJSON": "Y2xp"},+ "type": "public-key",+ "clientExtensionResults": {},+ },+ },+ headers=auth_headers,+ )++ assert response.status_code == 200+ kwargs = verify_mock.call_args.kwargs+ assert kwargs["expected_rp_id"] == "money.example.com"+ assert kwargs["expected_origin"] == "https://money.example.com"diff --git a/docker-compose.yml b/docker-compose.ymlindex ba75f7a9..565410be 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -11,7 +11,10 @@ x-backend-env: &backend-envDATABASE_URL: postgresql+asyncpg://postgres:postgres@db:5432/securoSECRET_KEY: ${SECRET_KEY:-dev-secret-change-in-production}DEBUG: ${DEBUG:-true}- FRONTEND_URL: http://localhost:${FRONTEND_PORT:-3000}+ FRONTEND_URL: ${FRONTEND_URL:-http://localhost:${FRONTEND_PORT:-3000}}+ WEBAUTHN_RP_NAME: ${WEBAUTHN_RP_NAME:-Securo}+ WEBAUTHN_RP_ID: ${WEBAUTHN_RP_ID:-}+ WEBAUTHN_ORIGIN: ${WEBAUTHN_ORIGIN:-}PLUGGY_CLIENT_ID: ${PLUGGY_CLIENT_ID:-}PLUGGY_CLIENT_SECRET: ${PLUGGY_CLIENT_SECRET:-}PLUGGY_OAUTH_REDIRECT_URI: http://localhost:${FRONTEND_PORT:-3000}/oauth/callback@@ -126,7 +129,8 @@ services:- "${FRONTEND_PORT:-3000}:5173"environment:BACKEND_URL: http://backend:8000- FRONTEND_URL: http://localhost:3000+ # Also drives Vite's allowedHosts, so a proxied domain is not blocked.+ FRONTEND_URL: ${FRONTEND_URL:-http://localhost:${FRONTEND_PORT:-3000}}APP_VERSION_ROOT: /workspacedepends_on:- backenddiff --git a/frontend/src/components/passkey-management-dialog.tsx b/frontend/src/components/passkey-management-dialog.tsxindex 31848ac8..f07a518c 100644--- a/frontend/src/components/passkey-management-dialog.tsx+++ b/frontend/src/components/passkey-management-dialog.tsx@@ -1,9 +1,10 @@import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import { toast } from 'sonner'-import { Fingerprint, Trash2 } from 'lucide-react'+import { Fingerprint, Loader2, TriangleAlert, X } from 'lucide-react'import { auth } from '@/lib/api'-import { isPasskeySupported, startPasskeyRegistration } from '@/lib/webauthn'+import { passkeyBlocker, passkeyFailure, startPasskeyRegistration } from '@/lib/webauthn'+import type { PasskeyFailure } from '@/lib/webauthn'import type { Passkey } from '@/types'import {Dialog,@@ -21,6 +22,17 @@ interface PasskeyManagementDialogProps {onClose: () => void}+const FAILURE_KEYS: Record<PasskeyFailure, string> = {+ cancelled: 'auth.passkeyCancelled',+ duplicate: 'auth.passkeyDuplicate',+ domain: 'auth.passkeyDomainError',+ mismatch: 'auth.passkeyDomainMismatch',+ ip: 'auth.passkeyIpAddress',+ insecure: 'auth.passkeyInsecureContext',+ unsupported: 'auth.passkeyUnsupported',+ unknown: 'auth.passkeyRegisterError',+}+export function PasskeyManagementDialog({ open, onClose }: PasskeyManagementDialogProps) {const { t } = useTranslation()const [passkeys, setPasskeys] = useState<Passkey[]>([])@@ -28,20 +40,21 @@ export function PasskeyManagementDialog({ open, onClose }: PasskeyManagementDialconst [loading, setLoading] = useState(false)const [saving, setSaving] = useState(false)const [deletingId, setDeletingId] = useState<string | null>(null)- const [error, setError] = useState('')- const supported = isPasskeySupported()+ const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null)+ const [loadFailed, setLoadFailed] = useState(false)+ const blocker = passkeyBlocker()const loadPasskeys = useCallback(async () => {setLoading(true)- setError('')+ setLoadFailed(false)try {setPasskeys(await auth.listPasskeys())} catch {- setError(t('auth.passkeyLoadError'))+ setLoadFailed(true)} finally {setLoading(false)}- }, [t])+ }, [])useEffect(() => {if (open) void loadPasskeys()@@ -54,7 +67,7 @@ export function PasskeyManagementDialog({ open, onClose }: PasskeyManagementDialconst handleClose = () => {setName('')- setError('')+ setConfirmDeleteId(null)onClose()}@@ -62,7 +75,6 @@ export function PasskeyManagementDialog({ open, onClose }: PasskeyManagementDialevent.preventDefault()const passkeyName = name.trim() || t('auth.defaultPasskeyName')setSaving(true)- setError('')try {const options = await auth.registerPasskeyOptions(passkeyName)const credential = await startPasskeyRegistration(options.options)@@ -71,26 +83,21 @@ export function PasskeyManagementDialog({ open, onClose }: PasskeyManagementDialsetName('')toast.success(t('auth.passkeyAdded'))} catch (err) {- const domError = err as { name?: string }- const message = domError?.name === 'NotAllowedError'- ? t('auth.passkeyCancelled')- : t('auth.passkeyRegisterError')- setError(message)+ toast.error(t(FAILURE_KEYS[passkeyFailure(err)]))} finally {setSaving(false)}}const handleDelete = async (passkey: Passkey) => {- if (!window.confirm(t('auth.passkeyDeleteConfirm', { name: passkey.name }))) returnsetDeletingId(passkey.id)- setError('')try {await auth.deletePasskey(passkey.id)setPasskeys((current) => current.filter((item) => item.id !== passkey.id))+ setConfirmDeleteId(null)toast.success(t('auth.passkeyDeleted'))} catch {- setError(t('auth.passkeyDeleteError'))+ toast.error(t('auth.passkeyDeleteError'))} finally {setDeletingId(null)}@@ -106,14 +113,13 @@ export function PasskeyManagementDialog({ open, onClose }: PasskeyManagementDial<div className="space-y-4"><p className="text-sm text-muted-foreground">{t('auth.passkeysDescription')}</p>- {!supported && (- <div className="rounded-lg bg-amber-500/10 px-3 py-2 text-sm text-amber-700 dark:text-amber-300">- {t('auth.passkeyUnsupported')}+ {blocker && (+ <div className="flex items-start gap-2.5 rounded-lg bg-amber-500/10 px-3 py-2.5 text-sm text-amber-700 dark:text-amber-300">+ <TriangleAlert size={16} className="mt-0.5 shrink-0" />+ <p>{t(FAILURE_KEYS[blocker])}</p></div>)}- {error && <p className="text-sm text-destructive">{error}</p>}-<form onSubmit={handleRegister} className="space-y-3 rounded-lg border p-3"><div className="space-y-1.5"><Label htmlFor="passkey-name">{t('auth.passkeyName')}</Label>@@ -123,46 +129,86 @@ export function PasskeyManagementDialog({ open, onClose }: PasskeyManagementDialonChange={(event) => setName(event.target.value)}placeholder={t('auth.passkeyNamePlaceholder')}maxLength={100}- disabled={saving}+ disabled={saving || !!blocker}/></div>- <Button type="submit" disabled={!supported || saving} className="w-full">- {saving ? t('common.loading') : t('auth.addPasskey')}+ <Button type="submit" disabled={!!blocker || saving} className="w-full">+ {saving && <Loader2 size={15} className="animate-spin" />}+ {saving ? t('auth.passkeyWaiting') : t('auth.addPasskey')}</Button></form><div className="space-y-2">{loading ? (<p className="text-sm text-muted-foreground">{t('common.loading')}</p>+ ) : loadFailed ? (+ <div className="flex items-center justify-between gap-3 rounded-lg border border-destructive/30 p-3">+ <p className="text-sm text-destructive">{t('auth.passkeyLoadError')}</p>+ <Button type="button" variant="outline" size="sm" onClick={() => void loadPasskeys()}>+ {t('common.retry')}+ </Button>+ </div>) : passkeys.length === 0 ? (- <p className="text-sm text-muted-foreground">{t('auth.noPasskeys')}</p>+ <div className="flex flex-col items-center gap-2 rounded-lg border border-dashed px-3 py-6 text-center">+ <Fingerprint size={20} className="text-muted-foreground" />+ <p className="text-sm text-muted-foreground">{t('auth.noPasskeys')}</p>+ </div>) : (- passkeys.map((passkey) => (- <div key={passkey.id} className="flex items-start gap-3 rounded-lg border p-3">- <div className="mt-0.5 rounded-full bg-primary/10 p-2 text-primary">- <Fingerprint size={16} />- </div>- <div className="min-w-0 flex-1">- <p className="truncate text-sm font-medium">{passkey.name}</p>- <p className="text-xs text-muted-foreground">- {t('auth.passkeyCreated')}: {formatDate(passkey.created_at)}- </p>- <p className="text-xs text-muted-foreground">- {t('auth.passkeyLastUsed')}: {formatDate(passkey.last_used_at)}- </p>+ passkeys.map((passkey) => {+ const isConfirming = confirmDeleteId === passkey.id+ const isDeleting = deletingId === passkey.id++ return (+ <div key={passkey.id} className="flex items-start gap-3 rounded-lg border p-3">+ <div className="mt-0.5 rounded-full bg-primary/10 p-2 text-primary">+ <Fingerprint size={16} />+ </div>+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium">{passkey.name}</p>+ <p className="text-xs text-muted-foreground">+ {t('auth.passkeyCreated')}: {formatDate(passkey.created_at)}+ </p>+ <p className="text-xs text-muted-foreground">+ {t('auth.passkeyLastUsed')}: {formatDate(passkey.last_used_at)}+ </p>+ </div>+ {isConfirming ? (+ <div className="flex shrink-0 items-center gap-1">+ <Button+ type="button"+ variant="destructive"+ size="sm"+ onClick={() => void handleDelete(passkey)}+ disabled={isDeleting}+ >+ {isDeleting ? <Loader2 size={13} className="animate-spin" /> : t('common.delete')}+ </Button>+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={() => setConfirmDeleteId(null)}+ disabled={isDeleting}+ aria-label={t('common.cancel')}+ >+ <X size={14} />+ </Button>+ </div>+ ) : (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="shrink-0 text-muted-foreground hover:text-destructive"+ onClick={() => setConfirmDeleteId(passkey.id)}+ aria-label={t('auth.deletePasskey')}+ >+ {t('common.delete')}+ </Button>+ )}</div>- <Button- type="button"- variant="ghost"- size="sm"- onClick={() => void handleDelete(passkey)}- disabled={deletingId === passkey.id}- aria-label={t('auth.deletePasskey')}- >- <Trash2 size={15} />- </Button>- </div>- ))+ )+ }))}</div></div>diff --git a/frontend/src/lib/webauthn.ts b/frontend/src/lib/webauthn.tsindex 2fd64120..e4acbc82 100644--- a/frontend/src/lib/webauthn.ts+++ b/frontend/src/lib/webauthn.ts@@ -36,13 +36,60 @@ type AuthenticationCredentialJSON = {clientExtensionResults: AuthenticationExtensionsClientOutputs}+/** Why passkeys cannot be used here, or null when they can. */+export type PasskeyBlocker = 'ip' | 'insecure' | 'unsupported'++/** Every failure the passkey ceremonies can surface, as an i18n-friendly code. */+export type PasskeyFailure = PasskeyBlocker | 'cancelled' | 'duplicate' | 'domain' | 'mismatch' | 'unknown'++const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/++function isIpLiteral(hostname: string): boolean {+ // Browsers bracket IPv6 hosts; a bare colon can only be IPv6 here.+ return IPV4.test(hostname) || hostname.startsWith('[') || hostname.includes(':')+}++/**+ * WebAuthn requires a domain name: an IP address is never a valid relying-party+ * ID, and plain HTTP is only a secure context on localhost. Detecting that up+ * front lets the UI explain it instead of showing an opaque SecurityError.+ */+export function passkeyBlocker(): PasskeyBlocker | null {+ if (typeof window === 'undefined') return 'unsupported'+ if (isIpLiteral(window.location.hostname)) return 'ip'+ if (!window.isSecureContext) return 'insecure'+ if (!('PublicKeyCredential' in window) || !navigator.credentials) return 'unsupported'+ return null+}+export function isPasskeySupported(): boolean {- return (- typeof window !== 'undefined' &&- window.isSecureContext &&- 'PublicKeyCredential' in window &&- !!navigator.credentials- )+ return passkeyBlocker() === null+}++const SERVER_FAILURES: Record<string, PasskeyFailure> = {+ passkey_origin_ip: 'ip',+ passkey_origin_insecure: 'insecure',+ passkey_origin_mismatch: 'mismatch',+}++const BROWSER_FAILURES: Record<string, PasskeyFailure> = {+ NotAllowedError: 'cancelled',+ AbortError: 'cancelled',+ InvalidStateError: 'duplicate',+ SecurityError: 'domain',+ NotSupportedError: 'unsupported',+}++/** Classify a ceremony failure so the UI can say what actually went wrong. */+export function passkeyFailure(error: unknown): PasskeyFailure {+ const response = (error as { response?: { data?: { detail?: { code?: string } } } })?.response+ const serverCode = response?.data?.detail?.code+ if (serverCode && SERVER_FAILURES[serverCode]) return SERVER_FAILURES[serverCode]++ const name = (error as { name?: string })?.name+ if (name && BROWSER_FAILURES[name]) return BROWSER_FAILURES[name]++ return 'unknown'}function base64urlToArrayBuffer(value: string): ArrayBuffer {diff --git a/frontend/src/locales/de.json b/frontend/src/locales/de.jsonindex 363221e1..f490e306 100644--- a/frontend/src/locales/de.json+++ b/frontend/src/locales/de.json@@ -202,8 +202,14 @@"passkeySecondFactorPrompt": "Klicke auf die Schaltfläche unten und folge den Anweisungen deines Browsers für den Sicherheitsschlüssel.","passkeysTitle": "Passkeys","passkeysDescription": "Verwende Sicherheitsschlüssel oder Geräte-Passkeys, um dich ohne Passwort anzumelden. Registrierte Passkeys schützen auch die Passwort-Anmeldung als zweiten Faktor; die Anmeldung nur mit Passkey überspringt den Authentifikator-Code-Schritt, da der Schlüssel bereits den Besitz nachweist.",- "passkeyUnsupported": "Passkeys erfordern einen unterstützten Browser und eine sichere HTTPS- oder localhost-Verbindung.","passkeyLoadError": "Passkeys konnten nicht geladen werden",+ "passkeyUnsupported": "Dieser Browser unterstützt keine Passkeys.",+ "passkeyInsecureContext": "Passkeys erfordern eine sichere Verbindung. Öffne Securo über HTTPS oder auf http://localhost.",+ "passkeyIpAddress": "Passkeys funktionieren nicht mit einer IP-Adresse. Öffne Securo über HTTPS auf einer Domain oder auf http://localhost.",+ "passkeyDomainError": "Dein Browser hat diese Domain für Passkeys abgelehnt. Öffne Securo über HTTPS auf der konfigurierten Domain.",+ "passkeyDomainMismatch": "Diese Adresse liegt außerhalb der auf dem Server konfigurierten Passkey-Domain (WEBAUTHN_RP_ID).",+ "passkeyDuplicate": "Dieses Gerät hat bereits einen Passkey für dein Konto.",+ "passkeyWaiting": "Warten auf dein Gerät...","passkeyName": "Passkey-Name","passkeyNamePlaceholder": "z.B. YubiKey, MacBook Touch ID","defaultPasskeyName": "Passkey",@@ -1204,6 +1210,7 @@"name": "Name","create": "Erstellen","loading": "Wird geladen...",+ "retry": "Erneut versuchen","error": "Fehler","success": "Erfolgreich","searchIcon": "Symbol suchen...",diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex e0c9b901..2cc8cf98 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -202,8 +202,14 @@"passkeySecondFactorPrompt": "Click the button below and follow your browser's security-key prompt.","passkeysTitle": "Passkeys","passkeysDescription": "Use security keys or device passkeys to sign in without entering your password. Enrolled passkeys also protect password sign-in as a second factor; passkey-only sign-in skips the authenticator-code step because the key already verifies possession.",- "passkeyUnsupported": "Passkeys require a supported browser and a secure HTTPS or localhost connection.","passkeyLoadError": "Could not load passkeys",+ "passkeyUnsupported": "This browser does not support passkeys.",+ "passkeyInsecureContext": "Passkeys need a secure connection. Open Securo over HTTPS, or on http://localhost.",+ "passkeyIpAddress": "Passkeys do not work on an IP address. Open Securo on a domain name over HTTPS, or on http://localhost.",+ "passkeyDomainError": "Your browser rejected this domain for passkeys. Open Securo on the domain it is configured for, over HTTPS.",+ "passkeyDomainMismatch": "This address is outside the passkey domain configured on the server (WEBAUTHN_RP_ID).",+ "passkeyDuplicate": "This device already has a passkey for your account.",+ "passkeyWaiting": "Waiting for your device...","passkeyName": "Passkey name","passkeyNamePlaceholder": "e.g. YubiKey, MacBook Touch ID","defaultPasskeyName": "Passkey",@@ -1204,6 +1210,7 @@"name": "Name","create": "Create","loading": "Loading...",+ "retry": "Retry","error": "Error","success": "Success","searchIcon": "Search icon...",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex e29adea3..6c996f74 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -202,8 +202,14 @@"passkeySecondFactorPrompt": "Haz clic en el botón de abajo y sigue la solicitud de llave de seguridad del navegador.","passkeysTitle": "Llaves de acceso","passkeysDescription": "Usa llaves de seguridad o llaves de acceso del dispositivo para iniciar sesión sin introducir la contraseña. Las llaves registradas también protegen el inicio con contraseña como segundo factor; el inicio solo con llave omite el código autenticador porque la llave ya verifica la posesión.",- "passkeyUnsupported": "Las llaves de acceso requieren un navegador compatible y una conexión HTTPS segura o localhost.","passkeyLoadError": "No se pudieron cargar las llaves de acceso",+ "passkeyUnsupported": "Este navegador no admite passkeys.",+ "passkeyInsecureContext": "Las passkeys requieren una conexión segura. Abre Securo por HTTPS o en http://localhost.",+ "passkeyIpAddress": "Las passkeys no funcionan en una dirección IP. Abre Securo en un dominio por HTTPS o en http://localhost.",+ "passkeyDomainError": "Tu navegador rechazó este dominio para passkeys. Abre Securo en el dominio configurado, por HTTPS.",+ "passkeyDomainMismatch": "Esta dirección está fuera del dominio de passkeys configurado en el servidor (WEBAUTHN_RP_ID).",+ "passkeyDuplicate": "Este dispositivo ya tiene una passkey para tu cuenta.",+ "passkeyWaiting": "Esperando a tu dispositivo...","passkeyName": "Nombre de la llave de acceso","passkeyNamePlaceholder": "p. ej. YubiKey, Touch ID de MacBook","defaultPasskeyName": "Llave de acceso",@@ -1204,6 +1210,7 @@"name": "Nombre","create": "Crear","loading": "Cargando...",+ "retry": "Reintentar","error": "Error","success": "Éxito","searchIcon": "Buscar icono...",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex b70a04d1..53285b5f 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -202,8 +202,14 @@"passkeySecondFactorPrompt": "Fai clic sul pulsante qui sotto e segui la richiesta della chiave di sicurezza del browser.","passkeysTitle": "Passkey","passkeysDescription": "Usa chiavi di sicurezza o passkey del dispositivo per accedere senza inserire la password. Le passkey registrate proteggono anche l'accesso con password come secondo fattore; l'accesso solo con passkey salta il codice dell'app di autenticazione perché la chiave verifica già il possesso.",- "passkeyUnsupported": "Le passkey richiedono un browser supportato e una connessione HTTPS sicura o localhost.","passkeyLoadError": "Impossibile caricare le passkey",+ "passkeyUnsupported": "Questo browser non supporta le passkey.",+ "passkeyInsecureContext": "Le passkey richiedono una connessione sicura. Apri Securo tramite HTTPS o su http://localhost.",+ "passkeyIpAddress": "Le passkey non funzionano con un indirizzo IP. Apri Securo su un dominio tramite HTTPS o su http://localhost.",+ "passkeyDomainError": "Il browser ha rifiutato questo dominio per le passkey. Apri Securo sul dominio configurato, tramite HTTPS.",+ "passkeyDomainMismatch": "Questo indirizzo è fuori dal dominio delle passkey configurato sul server (WEBAUTHN_RP_ID).",+ "passkeyDuplicate": "Questo dispositivo ha già una passkey per il tuo account.",+ "passkeyWaiting": "In attesa del dispositivo...","passkeyName": "Nome passkey","passkeyNamePlaceholder": "es. YubiKey, Touch ID del MacBook","defaultPasskeyName": "Passkey",@@ -1204,6 +1210,7 @@"name": "Nome","create": "Crea","loading": "Caricamento...",+ "retry": "Riprova","error": "Errore","success": "Successo","searchIcon": "Cerca icona...",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex ad41fae3..719e0f65 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -202,8 +202,14 @@"passkeySecondFactorPrompt": "Kliknij przycisk poniżej i postępuj zgodnie z prośbą przeglądarki o klucz bezpieczeństwa.","passkeysTitle": "Klucze dostępu","passkeysDescription": "Używaj kluczy bezpieczeństwa lub kluczy dostępu urządzenia, aby logować się bez wpisywania hasła. Zarejestrowane klucze chronią też logowanie hasłem jako drugi składnik; logowanie samym kluczem pomija kod z aplikacji, bo klucz już potwierdza posiadanie.",- "passkeyUnsupported": "Klucze dostępu wymagają obsługiwanej przeglądarki oraz bezpiecznego połączenia HTTPS lub localhost.","passkeyLoadError": "Nie udało się załadować kluczy dostępu",+ "passkeyUnsupported": "Ta przeglądarka nie obsługuje kluczy dostępu.",+ "passkeyInsecureContext": "Klucze dostępu wymagają bezpiecznego połączenia. Otwórz Securo przez HTTPS lub na http://localhost.",+ "passkeyIpAddress": "Klucze dostępu nie działają pod adresem IP. Otwórz Securo w domenie przez HTTPS lub na http://localhost.",+ "passkeyDomainError": "Przeglądarka odrzuciła tę domenę dla kluczy dostępu. Otwórz Securo w skonfigurowanej domenie przez HTTPS.",+ "passkeyDomainMismatch": "Ten adres jest poza domeną kluczy dostępu skonfigurowaną na serwerze (WEBAUTHN_RP_ID).",+ "passkeyDuplicate": "To urządzenie ma już klucz dostępu do Twojego konta.",+ "passkeyWaiting": "Oczekiwanie na urządzenie...","passkeyName": "Nazwa klucza dostępu","passkeyNamePlaceholder": "np. YubiKey, Touch ID MacBooka","defaultPasskeyName": "Klucz dostępu",@@ -1279,6 +1285,7 @@"name": "Nazwa","create": "Utwórz","loading": "Wczytywanie...",+ "retry": "Ponów","error": "Błąd","success": "Sukces","searchIcon": "Szukaj ikony...",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 36bbe401..159ae40d 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -202,8 +202,14 @@"passkeySecondFactorPrompt": "Clique no botão abaixo e siga a solicitação de chave de segurança do navegador.","passkeysTitle": "Chaves de acesso","passkeysDescription": "Use chaves de segurança ou chaves de acesso do dispositivo para entrar sem digitar sua senha. Chaves de acesso cadastradas também protegem o login por senha como segundo fator; o login somente por chave pula o código autenticador porque a chave já comprova a posse.",- "passkeyUnsupported": "Chaves de acesso exigem um navegador compatível e uma conexão HTTPS segura ou localhost.","passkeyLoadError": "Não foi possível carregar as chaves de acesso",+ "passkeyUnsupported": "Este navegador não oferece suporte a passkeys.",+ "passkeyInsecureContext": "Passkeys exigem uma conexão segura. Abra o Securo por HTTPS ou em http://localhost.",+ "passkeyIpAddress": "Passkeys não funcionam em um endereço IP. Abra o Securo em um domínio por HTTPS ou em http://localhost.",+ "passkeyDomainError": "Seu navegador recusou este domínio para passkeys. Abra o Securo no domínio configurado, por HTTPS.",+ "passkeyDomainMismatch": "Este endereço está fora do domínio de passkeys configurado no servidor (WEBAUTHN_RP_ID).",+ "passkeyDuplicate": "Este dispositivo já tem uma passkey para a sua conta.",+ "passkeyWaiting": "Aguardando seu dispositivo...","passkeyName": "Nome da chave de acesso","passkeyNamePlaceholder": "ex.: YubiKey, Touch ID do MacBook","defaultPasskeyName": "Chave de acesso",@@ -1204,6 +1210,7 @@"name": "Nome","create": "Criar","loading": "Carregando...",+ "retry": "Tentar novamente","error": "Erro","success": "Sucesso","searchIcon": "Buscar ícone...",diff --git a/frontend/src/locales/ru.json b/frontend/src/locales/ru.jsonindex 534017a6..fc8c9d10 100644--- a/frontend/src/locales/ru.json+++ b/frontend/src/locales/ru.json@@ -202,8 +202,14 @@"passkeySecondFactorPrompt": "Нажмите кнопку ниже и следуйте запросу ключа безопасности в браузере.","passkeysTitle": "Ключи доступа","passkeysDescription": "Используйте ключи безопасности или ключи доступа устройства, чтобы входить без ввода пароля. Зарегистрированные ключи доступа также защищают вход по паролю как второй фактор; вход только по ключу доступа пропускает шаг с кодом аутентификатора, потому что ключ уже подтверждает владение.",- "passkeyUnsupported": "Для ключей доступа нужен поддерживаемый браузер и защищённое соединение HTTPS или localhost.","passkeyLoadError": "Не удалось загрузить ключи доступа",+ "passkeyUnsupported": "Этот браузер не поддерживает passkey.",+ "passkeyInsecureContext": "Для passkey нужно защищённое соединение. Откройте Securo по HTTPS или на http://localhost.",+ "passkeyIpAddress": "Passkey не работают по IP-адресу. Откройте Securo на домене по HTTPS или на http://localhost.",+ "passkeyDomainError": "Браузер отклонил этот домен для passkey. Откройте Securo на настроенном домене по HTTPS.",+ "passkeyDomainMismatch": "Этот адрес вне домена passkey, настроенного на сервере (WEBAUTHN_RP_ID).",+ "passkeyDuplicate": "На этом устройстве уже есть passkey для вашего аккаунта.",+ "passkeyWaiting": "Ожидание устройства...","passkeyName": "Название ключа доступа","passkeyNamePlaceholder": "напр. YubiKey, Touch ID на MacBook","defaultPasskeyName": "Ключ доступа",@@ -1204,6 +1210,7 @@"name": "Название","create": "Создать","loading": "Загрузка...",+ "retry": "Повторить","error": "Ошибка","success": "Успешно","searchIcon": "Поиск иконки...",diff --git a/frontend/src/locales/uk.json b/frontend/src/locales/uk.jsonindex 26d86a5f..614da776 100644--- a/frontend/src/locales/uk.json+++ b/frontend/src/locales/uk.json@@ -202,8 +202,14 @@"passkeySecondFactorPrompt": "Натисніть кнопку нижче та дотримуйтесь запиту ключа безпеки у браузері.","passkeysTitle": "Ключі доступу","passkeysDescription": "Використовуйте ключі безпеки або ключі доступу пристрою, щоб входити без введення пароля. Зареєстровані ключі доступу також захищають вхід за паролем як другий фактор; вхід лише за ключем доступу пропускає крок із кодом автентифікатора, бо ключ уже підтверджує володіння.",- "passkeyUnsupported": "Для ключів доступу потрібен підтримуваний браузер і захищене з'єднання HTTPS або localhost.","passkeyLoadError": "Не вдалося завантажити ключі доступу",+ "passkeyUnsupported": "Цей браузер не підтримує passkey.",+ "passkeyInsecureContext": "Для passkey потрібне захищене з'єднання. Відкрийте Securo через HTTPS або на http://localhost.",+ "passkeyIpAddress": "Passkey не працюють за IP-адресою. Відкрийте Securo на домені через HTTPS або на http://localhost.",+ "passkeyDomainError": "Браузер відхилив цей домен для passkey. Відкрийте Securo на налаштованому домені через HTTPS.",+ "passkeyDomainMismatch": "Ця адреса поза доменом passkey, налаштованим на сервері (WEBAUTHN_RP_ID).",+ "passkeyDuplicate": "На цьому пристрої вже є passkey для вашого облікового запису.",+ "passkeyWaiting": "Очікування пристрою...","passkeyName": "Назва ключа доступу","passkeyNamePlaceholder": "напр. YubiKey, Touch ID на MacBook","defaultPasskeyName": "Ключ доступу",@@ -1204,6 +1210,7 @@"name": "Назва","create": "Створити","loading": "Завантаження...",+ "retry": "Повторити","error": "Помилка","success": "Успішно","searchIcon": "Пошук іконки...",diff --git a/frontend/src/pages/login.tsx b/frontend/src/pages/login.tsxindex 65d7620e..05c36d09 100644--- a/frontend/src/pages/login.tsx+++ b/frontend/src/pages/login.tsx@@ -12,7 +12,19 @@ import type { AxiosError } from 'axios'import { isServerUnreachable } from '@/lib/auth-errors'import { useTheme } from 'next-themes'import { setThemeBasedOnSystem } from '@/lib/theme-utils'-import { isPasskeySupported, startPasskeyAuthentication } from '@/lib/webauthn'+import { isPasskeySupported, passkeyFailure, startPasskeyAuthentication } from '@/lib/webauthn'+import type { PasskeyFailure } from '@/lib/webauthn'++const PASSKEY_LOGIN_FAILURE_KEYS: Record<PasskeyFailure, string> = {+ cancelled: 'auth.passkeyCancelled',+ domain: 'auth.passkeyDomainError',+ mismatch: 'auth.passkeyDomainMismatch',+ ip: 'auth.passkeyIpAddress',+ insecure: 'auth.passkeyInsecureContext',+ unsupported: 'auth.passkeyUnsupported',+ duplicate: 'auth.passkeyLoginError',+ unknown: 'auth.passkeyLoginError',+}export default function LoginPage() {const { t } = useTranslation()@@ -100,13 +112,10 @@ export default function LoginPage() {navigate('/')} catch (err) {const axiosErr = err as AxiosError- const domErr = err as { name?: string }- if (domErr?.name === 'NotAllowedError') {- setError(t('auth.passkeyCancelled'))- } else if (axiosErr?.response?.status === 429) {+ if (axiosErr?.response?.status === 429) {setError(t('auth.tooManyAttempts'))} else {- setError(t('auth.passkeyLoginError'))+ setError(t(PASSKEY_LOGIN_FAILURE_KEYS[passkeyFailure(err)]))}} finally {setIsPasskeyLoading(false)