Open-source personal finance manager. Self-hosted, privacy-first.
feat: add passkey authentication (#330)
Sgubela1d0ea2b0c015
diff --git a/backend/alembic/versions/062_passkeys.py b/backend/alembic/versions/062_passkeys.pynew file mode 100644index 00000000..851914a3--- /dev/null+++ b/backend/alembic/versions/062_passkeys.py@@ -0,0 +1,47 @@+"""add passkeys for webauthn login++Revision ID: 062+Revises: 061+Create Date: 2026-06-14+"""+from typing import Sequence, Union++import sqlalchemy as sa+from alembic import op+from sqlalchemy.dialects import postgresql++revision: str = "062"+down_revision: Union[str, None] = "061"+branch_labels: Union[str, Sequence[str], None] = None+depends_on: Union[str, Sequence[str], None] = None+++def upgrade() -> None:+ op.create_table(+ "user_passkeys",+ sa.Column("id", postgresql.UUID(as_uuid=True), primary_key=True),+ sa.Column(+ "user_id",+ postgresql.UUID(as_uuid=True),+ sa.ForeignKey("users.id", ondelete="CASCADE"),+ nullable=False,+ ),+ sa.Column("credential_id", sa.String(length=512), nullable=False),+ sa.Column("public_key", sa.Text(), nullable=False),+ sa.Column("sign_count", sa.Integer(), nullable=False, server_default="0"),+ sa.Column("name", sa.String(length=100), nullable=False),+ sa.Column("transports", sa.JSON(), nullable=True),+ sa.Column("aaguid", sa.String(length=64), nullable=True),+ sa.Column("device_type", sa.String(length=50), nullable=True),+ sa.Column("backed_up", sa.Boolean(), nullable=True),+ sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),+ sa.Column("last_used_at", sa.DateTime(timezone=True), nullable=True),+ )+ op.create_index("ix_user_passkeys_user_id", "user_passkeys", ["user_id"])+ op.create_index("ix_user_passkeys_credential_id", "user_passkeys", ["credential_id"], unique=True)+++def downgrade() -> None:+ op.drop_index("ix_user_passkeys_credential_id", table_name="user_passkeys")+ op.drop_index("ix_user_passkeys_user_id", table_name="user_passkeys")+ op.drop_table("user_passkeys")diff --git a/backend/app/api/custom_auth.py b/backend/app/api/custom_auth.pyindex da29e2c4..98cd052d 100644--- a/backend/app/api/custom_auth.py+++ b/backend/app/api/custom_auth.py@@ -1,10 +1,15 @@import secrets+import jsonfrom fastapi import APIRouter, Depends, HTTPExceptionfrom fastapi.security import OAuth2PasswordRequestForm+from sqlalchemy import func, select+from sqlalchemy.ext.asyncio import AsyncSessionfrom app.core.auth import get_jwt_strategy, get_user_manager+from app.core.database import get_async_sessionfrom app.core.redis import get_redis+from app.models.passkey import UserPasskeyrouter = APIRouter()@@ -15,17 +20,31 @@ TEMP_TOKEN_TTL = 300 # 5 minutesasync def login(credentials: OAuth2PasswordRequestForm = Depends(),user_manager=Depends(get_user_manager),+ session: AsyncSession = Depends(get_async_session),):user = await user_manager.authenticate(credentials)if user is None or not user.is_active:raise HTTPException(status_code=400, detail="LOGIN_BAD_CREDENTIALS")+ passkey_count = await session.scalar(+ select(func.count()).select_from(UserPasskey).where(UserPasskey.user_id == user.id)+ )+ available_methods = []if user.is_2fa_enabled and user.totp_secret:+ available_methods.append("totp")+ if passkey_count and passkey_count > 0:+ available_methods.append("passkey")++ if available_methods:# Store temp token in Redis, return 2FA challenger = await get_redis()temp_token = secrets.token_urlsafe(32)- await r.set(f"2fa_temp:{temp_token}", str(user.id), ex=TEMP_TOKEN_TTL)- return {"requires_2fa": True, "temp_token": temp_token}+ await r.set(+ f"2fa_temp:{temp_token}",+ json.dumps({"user_id": str(user.id), "available_methods": available_methods}),+ ex=TEMP_TOKEN_TTL,+ )+ return {"requires_2fa": True, "temp_token": temp_token, "available_methods": available_methods}# Normal login — generate JWTstrategy = get_jwt_strategy()diff --git a/backend/app/api/passkeys.py b/backend/app/api/passkeys.pynew file mode 100644index 00000000..1be1d674--- /dev/null+++ b/backend/app/api/passkeys.py@@ -0,0 +1,420 @@+import json+import secrets+import uuid+from datetime import datetime, timezone+from typing import Any++from fastapi import APIRouter, Depends, HTTPException, Response, status+from sqlalchemy import func, select+from sqlalchemy.exc import IntegrityError+from sqlalchemy.ext.asyncio import AsyncSession+from webauthn import (+ generate_authentication_options,+ generate_registration_options,+ options_to_json,+ verify_authentication_response,+ verify_registration_response,+)+from webauthn.helpers import base64url_to_bytes, bytes_to_base64url+from webauthn.helpers.structs import (+ AttestationConveyancePreference,+ AuthenticatorSelectionCriteria,+ PublicKeyCredentialDescriptor,+ ResidentKeyRequirement,+ UserVerificationRequirement,+)++from app.core.auth import current_active_user, get_jwt_strategy+from app.core.config import get_settings+from app.core.database import get_async_session+from app.core.rate_limit import login_rate_limit+from app.core.redis import get_redis+from app.api.two_factor import _parse_temp_token_payload+from app.models.passkey import UserPasskey+from app.models.user import User+from app.schemas.passkey import (+ PasskeyAuthenticateOptionsRequest,+ PasskeyAuthenticateVerifyRequest,+ PasskeyOptionsResponse,+ PasskeyRead,+ PasskeyRegisterOptionsRequest,+ PasskeyRegisterVerifyRequest,+ PasskeySecondFactorOptionsRequest,+ PasskeySecondFactorVerifyRequest,+)++router = APIRouter()++REGISTER_CHALLENGE_PREFIX = "passkey_register"+AUTHENTICATE_CHALLENGE_PREFIX = "passkey_authenticate"+SECOND_FACTOR_CHALLENGE_PREFIX = "passkey_2fa"+++def _options_dict(options: Any) -> dict[str, Any]:+ return json.loads(options_to_json(options))+++def _credential_json(credential: dict[str, Any]) -> str:+ return json.dumps(credential)+++def _as_base64url(value: bytes | str) -> str:+ if isinstance(value, bytes):+ return bytes_to_base64url(value)+ return value+++def _optional_string(value: Any) -> str | None:+ if value is None:+ return None+ return getattr(value, "value", str(value))+++def _optional_bool(value: Any) -> bool | None:+ if value is None:+ return None+ return bool(value)+++def _challenge_key(prefix: str, challenge_id: str) -> str:+ return f"{prefix}:{challenge_id}"+++async def _get_second_factor_user_id(temp_token: str) -> str:+ redis = await get_redis()+ raw_payload = await redis.get(f"2fa_temp:{temp_token}")+ if not raw_payload:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid or expired token")+ payload = _parse_temp_token_payload(raw_payload)+ available_methods = payload.get("available_methods", []) if payload else []+ if payload is None or not isinstance(available_methods, list) or "passkey" not in available_methods:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")+ return str(payload["user_id"])+++async def _delete_second_factor_temp_token(temp_token: str) -> None:+ redis = await get_redis()+ await redis.delete(f"2fa_temp:{temp_token}")+++async def _store_challenge(prefix: str, payload: dict[str, Any]) -> str:+ settings = get_settings()+ challenge_id = secrets.token_urlsafe(32)+ redis = await get_redis()+ await redis.set(+ _challenge_key(prefix, challenge_id),+ json.dumps(payload),+ ex=settings.webauthn_challenge_ttl_seconds,+ )+ return challenge_id+++async def _pop_challenge(prefix: str, challenge_id: str) -> dict[str, Any] | None:+ redis = await get_redis()+ key = _challenge_key(prefix, challenge_id)+ raw = await redis.getdel(key)+ if not raw:+ return None+ if isinstance(raw, bytes):+ raw = raw.decode()+ try:+ payload = json.loads(raw)+ except (TypeError, ValueError, json.JSONDecodeError):+ return None+ if not isinstance(payload, dict):+ return None+ return payload+++def _credential_transports(credential: dict[str, Any]) -> list[str] | None:+ transports = credential.get("transports")+ if transports is None:+ response = credential.get("response")+ if isinstance(response, dict):+ transports = response.get("transports")+ if not isinstance(transports, list):+ return None+ return [str(item) for item in transports]+++async def _verify_passkey_credential(+ *,+ credential: dict[str, Any],+ challenge: dict[str, Any],+ 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,+ credential_public_key=base64url_to_bytes(passkey.public_key),+ credential_current_sign_count=passkey.sign_count,+ require_user_verification=True,+ )+ except Exception as exc:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid passkey") from exc++ verified_credential_id = _as_base64url(verification.credential_id)+ if verified_credential_id != passkey.credential_id:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid passkey")++ user = await session.get(User, passkey.user_id)+ if user is None or not user.is_active:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid passkey")++ passkey.sign_count = verification.new_sign_count+ passkey.last_used_at = datetime.now(timezone.utc)+ session.add(passkey)+ await session.commit()+ return user++[email protected]("/passkeys", response_model=list[PasskeyRead])+async def list_passkeys(+ user: User = Depends(current_active_user),+ session: AsyncSession = Depends(get_async_session),+):+ result = await session.execute(+ select(UserPasskey)+ .where(UserPasskey.user_id == user.id)+ .order_by(UserPasskey.created_at.asc())+ )+ return result.scalars().all()++[email protected]("/passkeys/register/options", response_model=PasskeyOptionsResponse)+async def passkey_registration_options(+ body: PasskeyRegisterOptionsRequest,+ user: User = Depends(current_active_user),+ session: AsyncSession = Depends(get_async_session),+):+ settings = get_settings()+ existing = await session.execute(select(UserPasskey).where(UserPasskey.user_id == user.id))+ exclude_credentials = [+ PublicKeyCredentialDescriptor(id=base64url_to_bytes(passkey.credential_id))+ for passkey in existing.scalars().all()+ ]++ options = generate_registration_options(+ rp_id=settings.resolved_webauthn_rp_id,+ rp_name=settings.webauthn_rp_name,+ user_id=str(user.id).encode("utf-8"),+ user_name=user.email,+ user_display_name=user.email,+ attestation=AttestationConveyancePreference.NONE,+ authenticator_selection=AuthenticatorSelectionCriteria(+ resident_key=ResidentKeyRequirement.PREFERRED,+ user_verification=UserVerificationRequirement.REQUIRED,+ ),+ exclude_credentials=exclude_credentials,+ )++ challenge_id = await _store_challenge(+ REGISTER_CHALLENGE_PREFIX,+ {+ "challenge": bytes_to_base64url(options.challenge),+ "user_id": str(user.id),+ "name": body.name,+ },+ )+ return PasskeyOptionsResponse(challenge_id=challenge_id, options=_options_dict(options))++[email protected]("/passkeys/register/verify", response_model=PasskeyRead)+async def verify_passkey_registration(+ body: PasskeyRegisterVerifyRequest,+ 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")++ try:+ 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,+ require_user_verification=True,+ )+ except Exception as exc:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid passkey registration") from exc++ credential_id = _as_base64url(verification.credential_id)+ passkey = UserPasskey(+ user_id=user.id,+ credential_id=credential_id,+ public_key=_as_base64url(verification.credential_public_key),+ sign_count=verification.sign_count,+ name=body.name or challenge.get("name") or "Passkey",+ transports=_credential_transports(body.credential),+ aaguid=_optional_string(getattr(verification, "aaguid", None)),+ device_type=_optional_string(getattr(verification, "credential_device_type", None)),+ backed_up=_optional_bool(getattr(verification, "credential_backed_up", None)),+ )+ session.add(passkey)+ try:+ await session.commit()+ except IntegrityError as exc:+ await session.rollback()+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Passkey is already registered") from exc+ await session.refresh(passkey)+ return passkey++[email protected]("/passkeys/{passkey_id}", status_code=status.HTTP_204_NO_CONTENT)+async def delete_passkey(+ passkey_id: uuid.UUID,+ user: User = Depends(current_active_user),+ session: AsyncSession = Depends(get_async_session),+):+ result = await session.execute(+ select(UserPasskey).where(UserPasskey.id == passkey_id, UserPasskey.user_id == user.id)+ )+ passkey = result.scalar_one_or_none()+ if passkey is None:+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Passkey not found")+ await session.delete(passkey)+ await session.commit()+ return Response(status_code=status.HTTP_204_NO_CONTENT)+++ "/passkeys/authenticate/options",+ response_model=PasskeyOptionsResponse,+ dependencies=[Depends(login_rate_limit)],+)+async def passkey_authentication_options(+ body: PasskeyAuthenticateOptionsRequest,+ session: AsyncSession = Depends(get_async_session),+):+ settings = get_settings()+ email = body.email.strip().lower() if body.email else None+ expected_user_id: str | None = None++ if email:+ user_result = await session.execute(select(User).where(func.lower(User.email) == email))+ login_user = user_result.scalar_one_or_none()+ if login_user is not None:+ expected_user_id = str(login_user.id)++ options = generate_authentication_options(+ rp_id=settings.resolved_webauthn_rp_id,+ user_verification=UserVerificationRequirement.REQUIRED,+ )+ challenge_id = await _store_challenge(+ AUTHENTICATE_CHALLENGE_PREFIX,+ {+ "challenge": bytes_to_base64url(options.challenge),+ "email_bound": email is not None,+ "expected_user_id": expected_user_id,+ },+ )+ return PasskeyOptionsResponse(challenge_id=challenge_id, options=_options_dict(options))++[email protected]("/passkeys/authenticate/verify", dependencies=[Depends(login_rate_limit)])+async def verify_passkey_authentication(+ body: PasskeyAuthenticateVerifyRequest,+ session: AsyncSession = Depends(get_async_session),+):+ challenge = await _pop_challenge(AUTHENTICATE_CHALLENGE_PREFIX, body.challenge_id)+ if not challenge:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired challenge")++ credential_id = body.credential.get("rawId") or body.credential.get("id")+ if not credential_id:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing credential ID")++ result = await session.execute(select(UserPasskey).where(UserPasskey.credential_id == credential_id))+ passkey = result.scalar_one_or_none()+ if passkey is None:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid passkey")++ if challenge.get("email_bound"):+ expected_user_id = challenge.get("expected_user_id")+ if expected_user_id is None or str(passkey.user_id) != expected_user_id:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid passkey")++ user = await _verify_passkey_credential(+ credential=body.credential,+ challenge=challenge,+ passkey=passkey,+ session=session,+ )++ strategy = get_jwt_strategy()+ token = await strategy.write_token(user)+ return {"access_token": token, "token_type": "bearer"}++[email protected]("/passkeys/2fa/options", response_model=PasskeyOptionsResponse, dependencies=[Depends(login_rate_limit)])+async def passkey_second_factor_options(+ body: PasskeySecondFactorOptionsRequest,+ session: AsyncSession = Depends(get_async_session),+):+ settings = get_settings()+ 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())+ )+ passkeys = result.scalars().all()+ if not passkeys:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")++ options = generate_authentication_options(+ rp_id=settings.resolved_webauthn_rp_id,+ user_verification=UserVerificationRequirement.REQUIRED,+ allow_credentials=[+ PublicKeyCredentialDescriptor(id=base64url_to_bytes(passkey.credential_id))+ for passkey in passkeys+ ],+ )+ challenge_id = await _store_challenge(+ SECOND_FACTOR_CHALLENGE_PREFIX,+ {"challenge": bytes_to_base64url(options.challenge), "user_id": user_id},+ )+ return PasskeyOptionsResponse(challenge_id=challenge_id, options=_options_dict(options))++[email protected]("/passkeys/2fa/verify", dependencies=[Depends(login_rate_limit)])+async def verify_passkey_second_factor(+ body: PasskeySecondFactorVerifyRequest,+ session: AsyncSession = Depends(get_async_session),+):+ user_id = await _get_second_factor_user_id(body.temp_token)+ challenge = await _pop_challenge(SECOND_FACTOR_CHALLENGE_PREFIX, body.challenge_id)+ if not challenge or challenge.get("user_id") != user_id:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Invalid or expired challenge")++ credential_id = body.credential.get("rawId") or body.credential.get("id")+ if not credential_id:+ raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Missing credential ID")++ result = await session.execute(+ select(UserPasskey).where(+ UserPasskey.credential_id == credential_id,+ UserPasskey.user_id == uuid.UUID(user_id),+ )+ )+ passkey = result.scalar_one_or_none()+ if passkey is None:+ raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid passkey")++ user = await _verify_passkey_credential(+ credential=body.credential,+ challenge=challenge,+ passkey=passkey,+ session=session,+ )+ await _delete_second_factor_temp_token(body.temp_token)++ strategy = get_jwt_strategy()+ token = await strategy.write_token(user)+ return {"access_token": token, "token_type": "bearer"}diff --git a/backend/app/api/two_factor.py b/backend/app/api/two_factor.pyindex 9a3652a9..21d1d664 100644--- a/backend/app/api/two_factor.py+++ b/backend/app/api/two_factor.py@@ -1,3 +1,4 @@+import jsonimport uuidimport pyotp@@ -19,6 +20,19 @@ from app.schemas.two_factor import (router = APIRouter()+def _parse_temp_token_payload(raw: str | bytes) -> dict[str, object] | None:+ if isinstance(raw, bytes):+ raw = raw.decode()+ try:+ payload = json.loads(raw)+ except (TypeError, ValueError, json.JSONDecodeError):+ # Backward compatibility with existing temp tokens that only stored user_id.+ return {"user_id": raw, "available_methods": ["totp"]}+ if not isinstance(payload, dict) or not isinstance(payload.get("user_id"), str):+ return None+ return payload++@router.post("/2fa/setup", response_model=TwoFactorSetupResponse)async def setup_2fa(user: User = Depends(current_active_user),@@ -95,15 +109,20 @@ async def verify_2fa():r = await get_redis()redis_key = f"2fa_temp:{body.temp_token}"- user_id_str = await r.get(redis_key)+ raw_payload = await r.get(redis_key)- if not user_id_str:+ if not raw_payload:raise HTTPException(status_code=401, detail="Invalid or expired token")+ payload = _parse_temp_token_payload(raw_payload)+ available_methods = payload.get("available_methods", []) if payload else []+ if payload is None or not isinstance(available_methods, list) or "totp" not in available_methods:+ raise HTTPException(status_code=401, detail="Invalid token")+# Load user- result = await session.execute(select(User).where(User.id == uuid.UUID(user_id_str)))+ result = await session.execute(select(User).where(User.id == uuid.UUID(str(payload["user_id"]))))user = result.scalar_one_or_none()- if not user or not user.totp_secret:+ if not user or not (user.is_2fa_enabled and user.totp_secret):raise HTTPException(status_code=401, detail="Invalid token")# Verify TOTPdiff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex cc8f63db..f0f0b600 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -1,5 +1,7 @@-from pydantic_settings import BaseSettings, SettingsConfigDictfrom functools import lru_cache+from urllib.parse import urlparse++from pydantic_settings import BaseSettings, SettingsConfigDictclass Settings(BaseSettings):@@ -36,6 +38,25 @@ class Settings(BaseSettings):# Frontendfrontend_url: str = "http://localhost:5173"+ # WebAuthn / passkeys+ webauthn_rp_name: str = "Securo"+ # Empty means derive from frontend_url host, e.g. localhost for http://localhost:5173.+ webauthn_rp_id: str = ""+ # Empty means use frontend_url. Must match the browser origin exactly.+ 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/main.py b/backend/app/main.pyindex 468ec226..ab6f34a7 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -16,6 +16,7 @@ from app.api.custom_auth import router as custom_auth_routerfrom app.api.dashboard import router as dashboard_routerfrom app.api.import_logs import router as import_logs_routerfrom app.api.oidc_auth import router as oidc_auth_router+from app.api.passkeys import router as passkeys_routerfrom app.api.import_transactions import router as import_routerfrom app.api.info import router as info_routerfrom app.api.recurring_transactions import router as recurring_router@@ -89,6 +90,11 @@ app.include_router(prefix="/api/auth",tags=["auth"],)+app.include_router(+ passkeys_router,+ prefix="/api/auth",+ tags=["auth"],+)app.include_router(oidc_auth_router)app.include_router(fastapi_users.get_register_router(UserRead, UserCreate),diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.pyindex 741f1bcf..14b8de34 100644--- a/backend/app/models/__init__.py+++ b/backend/app/models/__init__.py@@ -1,4 +1,5 @@from app.models.user import User+from app.models.passkey import UserPasskeyfrom app.models.workspace import Workspace, WorkspaceMemberfrom app.models.category import Categoryfrom app.models.category_group import CategoryGroup@@ -31,6 +32,7 @@ from app.core import workspace_autostamp # noqa: F401, E402__all__ = ["User",+ "UserPasskey","Workspace","WorkspaceMember","Category",diff --git a/backend/app/models/passkey.py b/backend/app/models/passkey.pynew file mode 100644index 00000000..ef698147--- /dev/null+++ b/backend/app/models/passkey.py@@ -0,0 +1,35 @@+import uuid+from datetime import datetime, timezone+from typing import TYPE_CHECKING, Optional++from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, JSON, String, Text+from sqlalchemy.dialects.postgresql import UUID+from sqlalchemy.orm import Mapped, mapped_column, relationship++from app.core.database import Base++if TYPE_CHECKING:+ from app.models.user import User+++class UserPasskey(Base):+ __tablename__ = "user_passkeys"++ id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)+ user_id: Mapped[uuid.UUID] = mapped_column(+ UUID(as_uuid=True), ForeignKey("users.id", ondelete="CASCADE"), index=True+ )+ credential_id: Mapped[str] = mapped_column(String(512), unique=True, index=True)+ public_key: Mapped[str] = mapped_column(Text)+ sign_count: Mapped[int] = mapped_column(Integer, default=0, server_default="0")+ name: Mapped[str] = mapped_column(String(100))+ transports: Mapped[Optional[list[str]]] = mapped_column(JSON, nullable=True)+ aaguid: Mapped[Optional[str]] = mapped_column(String(64), nullable=True)+ device_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)+ backed_up: Mapped[Optional[bool]] = mapped_column(Boolean, nullable=True)+ created_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)+ )+ last_used_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)++ user: Mapped["User"] = relationship(back_populates="passkeys")diff --git a/backend/app/models/user.py b/backend/app/models/user.pyindex c91fd65c..6664706c 100644--- a/backend/app/models/user.py+++ b/backend/app/models/user.py@@ -10,6 +10,7 @@ if TYPE_CHECKING:from app.models.category import Categoryfrom app.models.category_group import CategoryGroupfrom app.models.bank_connection import BankConnection+ from app.models.passkey import UserPasskeyclass User(SQLAlchemyBaseUserTableUUID, Base):@@ -36,6 +37,7 @@ class User(SQLAlchemyBaseUserTableUUID, Base):categories: Mapped[list["Category"]] = relationship(back_populates="user", cascade="all, delete-orphan")category_groups: Mapped[list["CategoryGroup"]] = relationship(back_populates="user", cascade="all, delete-orphan")bank_connections: Mapped[list["BankConnection"]] = relationship(back_populates="user", cascade="all, delete-orphan")+ passkeys: Mapped[list["UserPasskey"]] = relationship(back_populates="user", cascade="all, delete-orphan")@propertydef primary_currency(self) -> str:diff --git a/backend/app/schemas/passkey.py b/backend/app/schemas/passkey.pynew file mode 100644index 00000000..6b94bd6c--- /dev/null+++ b/backend/app/schemas/passkey.py@@ -0,0 +1,52 @@+import uuid+from datetime import datetime+from typing import Any++from pydantic import BaseModel, Field+++class PasskeyRead(BaseModel):+ id: uuid.UUID+ name: str+ transports: list[str] | None = None+ aaguid: str | None = None+ device_type: str | None = None+ backed_up: bool | None = None+ created_at: datetime+ last_used_at: datetime | None = None++ model_config = {"from_attributes": True}+++class PasskeyRegisterOptionsRequest(BaseModel):+ name: str = Field(default="Passkey", min_length=1, max_length=100)+++class PasskeyOptionsResponse(BaseModel):+ challenge_id: str+ options: dict[str, Any]+++class PasskeyRegisterVerifyRequest(BaseModel):+ challenge_id: str+ name: str = Field(default="Passkey", min_length=1, max_length=100)+ credential: dict[str, Any]+++class PasskeyAuthenticateOptionsRequest(BaseModel):+ email: str | None = None+++class PasskeyAuthenticateVerifyRequest(BaseModel):+ challenge_id: str+ credential: dict[str, Any]+++class PasskeySecondFactorOptionsRequest(BaseModel):+ temp_token: str+++class PasskeySecondFactorVerifyRequest(BaseModel):+ temp_token: str+ challenge_id: str+ credential: dict[str, Any]diff --git a/backend/pyproject.toml b/backend/pyproject.tomlindex 3fc9fee5..b111aed9 100644--- a/backend/pyproject.toml+++ b/backend/pyproject.toml@@ -22,6 +22,7 @@ dependencies = ["aiofiles>=24.0","redis[hiredis]>=5.0.0","pyotp>=2.9.0",+ "webauthn>=2.8.0","yfinance>=1.3.0","pgvector>=0.3.0","pypdf>=5.0.0",diff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex d8be533d..38d5bcc1 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -46,6 +46,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessfrom app.core.database import Base, get_async_session # noqa: E402from app.main import app # noqa: E402from app.models.user import User # noqa: E402+from app.models.passkey import UserPasskey # noqa: E402,F401from app.models.category import Category # noqa: E402from app.models.bank_connection import BankConnection # noqa: E402from app.models.account import Account # noqa: E402diff --git a/backend/tests/test_passkeys.py b/backend/tests/test_passkeys.pynew file mode 100644index 00000000..08256a58--- /dev/null+++ b/backend/tests/test_passkeys.py@@ -0,0 +1,496 @@+from datetime import datetime+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest+from httpx import AsyncClient+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.models.passkey import UserPasskey+++class _RedisStore:+ def __init__(self):+ self.store = {}+ self.get = AsyncMock(side_effect=self._get)+ self.getdel = AsyncMock(side_effect=self._getdel)+ self.set = AsyncMock(side_effect=self._set)+ self.delete = AsyncMock(side_effect=self._delete)+ pipe = AsyncMock()+ pipe.zremrangebyscore = AsyncMock()+ pipe.zcard = AsyncMock()+ pipe.zadd = AsyncMock()+ pipe.expire = AsyncMock()+ pipe.execute = AsyncMock(return_value=[0, 0, True, True])+ self.pipeline = lambda: pipe++ async def _get(self, key):+ return self.store.get(key)++ async def _getdel(self, key):+ return self.store.pop(key, None)++ async def _set(self, key, value, ex=None):+ self.store[key] = value++ async def _delete(self, key):+ self.store.pop(key, None)++[email protected](autouse=True)+def _passkey_redis_store(_mock_redis):+ redis = _RedisStore()++ async def _fake():+ return redis++ with patch("app.core.redis.get_redis", _fake), \+ patch("app.core.rate_limit.get_redis", _fake), \+ patch("app.api.custom_auth.get_redis", _fake), \+ patch("app.api.two_factor.get_redis", _fake), \+ patch("app.api.passkeys.get_redis", _fake):+ yield redis+++async def test_register_options_requires_auth(client: AsyncClient):+ response = await client.post("/api/auth/passkeys/register/options", json={"name": "YubiKey"})++ assert response.status_code == 401+++async def test_register_and_list_passkey(+ client: AsyncClient,+ auth_headers: dict,+ session: AsyncSession,+ test_user,+):+ options_response = await client.post(+ "/api/auth/passkeys/register/options",+ json={"name": "YubiKey"},+ headers=auth_headers,+ )+ assert options_response.status_code == 200+ options_data = options_response.json()+ assert options_data["challenge_id"]+ assert options_data["options"]["rp"]["name"] == "Securo"+ assert options_data["options"]["user"]["name"] == test_user.email++ verification = SimpleNamespace(+ credential_id=b"credential-1",+ credential_public_key=b"public-key-1",+ sign_count=7,+ aaguid="test-aaguid",+ fmt="none",+ credential_type="public-key",+ )+ with patch("app.api.passkeys.verify_registration_response", return_value=verification):+ verify_response = await client.post(+ "/api/auth/passkeys/register/verify",+ json={+ "challenge_id": options_data["challenge_id"],+ "name": "YubiKey",+ "credential": {+ "id": "credential-1",+ "rawId": "Y3JlZGVudGlhbC0x",+ "response": {+ "attestationObject": "YXR0ZXN0YXRpb24",+ "clientDataJSON": "Y2xpZW50LWRhdGE",+ },+ "type": "public-key",+ "clientExtensionResults": {},+ "transports": ["usb", "nfc"],+ },+ },+ headers=auth_headers,+ )++ assert verify_response.status_code == 200+ created = verify_response.json()+ assert created["name"] == "YubiKey"+ assert "credential_id" not in created++ list_response = await client.get("/api/auth/passkeys", headers=auth_headers)+ assert list_response.status_code == 200+ assert [item["name"] for item in list_response.json()] == ["YubiKey"]++ result = await session.execute(select(UserPasskey).where(UserPasskey.user_id == test_user.id))+ passkey = result.scalar_one()+ assert passkey.public_key == "cHVibGljLWtleS0x"+ assert passkey.sign_count == 7+ assert passkey.transports == ["usb", "nfc"]+++async def test_authenticate_passkey_returns_jwt_and_bypasses_2fa(+ client: AsyncClient,+ session: AsyncSession,+ test_user_with_2fa,+):+ passkey = UserPasskey(+ user_id=test_user_with_2fa.id,+ credential_id="Y3JlZGVudGlhbC0y",+ public_key="cHVibGljLWtleS0y",+ sign_count=3,+ name="Platform passkey",+ )+ session.add(passkey)+ await session.commit()+ await session.refresh(passkey)++ email_options_response = await client.post(+ "/api/auth/passkeys/authenticate/options",+ json={"email": test_user_with_2fa.email.upper()},+ )+ assert email_options_response.status_code == 200+ email_options = email_options_response.json()["options"]+ assert email_options.get("allowCredentials") in (None, [])+ challenge_id = email_options_response.json()["challenge_id"]++ verification = SimpleNamespace(+ credential_id=b"credential-2",+ new_sign_count=8,+ )+ with patch("app.api.passkeys.verify_authentication_response", return_value=verification):+ verify_response = await client.post(+ "/api/auth/passkeys/authenticate/verify",+ json={+ "challenge_id": challenge_id,+ "credential": {+ "id": "credential-2",+ "rawId": "Y3JlZGVudGlhbC0y",+ "response": {+ "authenticatorData": "YXV0aC1kYXRh",+ "clientDataJSON": "Y2xpZW50LWRhdGE",+ "signature": "c2lnbmF0dXJl",+ "userHandle": None,+ },+ "type": "public-key",+ "clientExtensionResults": {},+ },+ },+ )++ assert verify_response.status_code == 200+ data = verify_response.json()+ assert "access_token" in data+ assert data["token_type"] == "bearer"+ assert "requires_2fa" not in data++ await session.refresh(passkey)+ assert passkey.sign_count == 8+ assert isinstance(passkey.last_used_at, datetime)+++async def test_password_login_with_passkey_requires_second_factor(+ client: AsyncClient,+ session: AsyncSession,+ test_user,+):+ session.add(+ UserPasskey(+ user_id=test_user.id,+ credential_id="cGFzc3dvcmQtbWZhLWtleQ",+ public_key="cHVibGljLWtleQ",+ sign_count=1,+ name="Security key",+ )+ )+ await session.commit()++ response = await client.post(+ "/api/auth/login",+ data={"username": test_user.email, "password": "testpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )++ assert response.status_code == 200+ data = response.json()+ assert data["requires_2fa"] is True+ assert data["temp_token"]+ assert data["available_methods"] == ["passkey"]+ assert "access_token" not in data+++async def test_passkey_second_factor_returns_jwt_for_same_user_passkey(+ client: AsyncClient,+ session: AsyncSession,+ test_user,+):+ passkey = UserPasskey(+ user_id=test_user.id,+ credential_id="c2FtZS11c2VyLWtleQ",+ public_key="c2FtZS11c2VyLXB1YmxpYw",+ sign_count=2,+ name="Security key",+ )+ session.add(passkey)+ await session.commit()+ await session.refresh(passkey)++ login_response = await client.post(+ "/api/auth/login",+ data={"username": test_user.email, "password": "testpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ temp_token = login_response.json()["temp_token"]++ options_response = await client.post("/api/auth/passkeys/2fa/options", json={"temp_token": temp_token})+ assert options_response.status_code == 200+ options_data = options_response.json()+ assert options_data["options"]["allowCredentials"][0]["id"] == passkey.credential_id++ verification = SimpleNamespace(credential_id=b"same-user-key", new_sign_count=9)+ with patch("app.api.passkeys.verify_authentication_response", return_value=verification):+ verify_response = await client.post(+ "/api/auth/passkeys/2fa/verify",+ json={+ "temp_token": temp_token,+ "challenge_id": options_data["challenge_id"],+ "credential": {+ "id": "same-user-key",+ "rawId": "c2FtZS11c2VyLWtleQ",+ "response": {+ "authenticatorData": "YXV0aC1kYXRh",+ "clientDataJSON": "Y2xpZW50LWRhdGE",+ "signature": "c2lnbmF0dXJl",+ "userHandle": None,+ },+ "type": "public-key",+ "clientExtensionResults": {},+ },+ },+ )++ assert verify_response.status_code == 200+ data = verify_response.json()+ assert "access_token" in data+ assert data["token_type"] == "bearer"++ await session.refresh(passkey)+ assert passkey.sign_count == 9+ assert isinstance(passkey.last_used_at, datetime)+++async def test_passkey_second_factor_rejects_other_users_passkey(+ client: AsyncClient,+ session: AsyncSession,+ test_user,+ test_user_with_2fa,+):+ own_passkey = UserPasskey(+ user_id=test_user.id,+ credential_id="b3duZXItbWZhLWtleQ",+ public_key="b3duZXItcHVibGlj",+ sign_count=1,+ name="Own key",+ )+ other_passkey = UserPasskey(+ user_id=test_user_with_2fa.id,+ credential_id="b3RoZXItbWZhLWtleQ",+ public_key="b3RoZXItcHVibGlj",+ sign_count=1,+ name="Other key",+ )+ session.add_all([own_passkey, other_passkey])+ await session.commit()++ login_response = await client.post(+ "/api/auth/login",+ data={"username": test_user.email, "password": "testpass123"},+ headers={"Content-Type": "application/x-www-form-urlencoded"},+ )+ temp_token = login_response.json()["temp_token"]++ options_response = await client.post("/api/auth/passkeys/2fa/options", json={"temp_token": temp_token})+ assert options_response.status_code == 200++ with patch("app.api.passkeys.verify_authentication_response") as verify_mock:+ verify_response = await client.post(+ "/api/auth/passkeys/2fa/verify",+ json={+ "temp_token": temp_token,+ "challenge_id": options_response.json()["challenge_id"],+ "credential": {+ "id": "other-mfa-key",+ "rawId": "b3RoZXItbWZhLWtleQ",+ "response": {+ "authenticatorData": "YXV0aC1kYXRh",+ "clientDataJSON": "Y2xpZW50LWRhdGE",+ "signature": "c2lnbmF0dXJl",+ "userHandle": None,+ },+ "type": "public-key",+ "clientExtensionResults": {},+ },+ },+ )++ assert verify_response.status_code == 401+ verify_mock.assert_not_called()+++async def test_authenticate_email_bound_challenge_rejects_other_users_passkey(+ client: AsyncClient,+ session: AsyncSession,+ test_user,+ test_user_with_2fa,+):+ expected_passkey = UserPasskey(+ user_id=test_user_with_2fa.id,+ credential_id="ZXhwZWN0ZWQ",+ public_key="cHVibGljLWtleS1leHBlY3RlZA",+ sign_count=1,+ name="Expected key",+ )+ other_passkey = UserPasskey(+ user_id=test_user.id,+ credential_id="b3RoZXIta2V5",+ public_key="cHVibGljLWtleS1vdGhlcg",+ sign_count=1,+ name="Other key",+ )+ session.add_all([expected_passkey, other_passkey])+ await session.commit()++ options_response = await client.post(+ "/api/auth/passkeys/authenticate/options",+ json={"email": test_user_with_2fa.email},+ )+ assert options_response.status_code == 200++ with patch("app.api.passkeys.verify_authentication_response") as verify_mock:+ verify_response = await client.post(+ "/api/auth/passkeys/authenticate/verify",+ json={+ "challenge_id": options_response.json()["challenge_id"],+ "credential": {+ "id": "other-key",+ "rawId": "b3RoZXIta2V5",+ "response": {+ "authenticatorData": "YXV0aC1kYXRh",+ "clientDataJSON": "Y2xpZW50LWRhdGE",+ "signature": "c2lnbmF0dXJl",+ "userHandle": None,+ },+ "type": "public-key",+ "clientExtensionResults": {},+ },+ },+ )++ assert verify_response.status_code == 401+ verify_mock.assert_not_called()+++async def test_authenticate_email_bound_challenge_rejects_unknown_email(+ client: AsyncClient,+ session: AsyncSession,+ test_user,+):+ passkey = UserPasskey(+ user_id=test_user.id,+ credential_id="b3duZXIta2V5",+ public_key="cHVibGljLWtleS1vd25lcg",+ sign_count=1,+ name="Owner key",+ )+ session.add(passkey)+ await session.commit()++ options_response = await client.post(+ "/api/auth/passkeys/authenticate/options",+ json={"email": "[email protected]"},+ )+ assert options_response.status_code == 200++ with patch("app.api.passkeys.verify_authentication_response") as verify_mock:+ verify_response = await client.post(+ "/api/auth/passkeys/authenticate/verify",+ json={+ "challenge_id": options_response.json()["challenge_id"],+ "credential": {+ "id": "owner-key",+ "rawId": "b3duZXIta2V5",+ "response": {+ "authenticatorData": "YXV0aC1kYXRh",+ "clientDataJSON": "Y2xpZW50LWRhdGE",+ "signature": "c2lnbmF0dXJl",+ "userHandle": None,+ },+ "type": "public-key",+ "clientExtensionResults": {},+ },+ },+ )++ assert verify_response.status_code == 401+ verify_mock.assert_not_called()+++async def test_delete_passkey_is_owner_scoped(+ client: AsyncClient,+ auth_headers: dict,+ session: AsyncSession,+ test_user,+ test_user_with_2fa,+):+ own_passkey = UserPasskey(+ user_id=test_user.id,+ credential_id="b3du",+ public_key="cHVi",+ name="Own key",+ )+ other_passkey = UserPasskey(+ user_id=test_user_with_2fa.id,+ credential_id="b3RoZXI",+ public_key="cHVi",+ name="Other key",+ )+ session.add_all([own_passkey, other_passkey])+ await session.commit()+ await session.refresh(own_passkey)+ await session.refresh(other_passkey)++ forbidden = await client.delete(f"/api/auth/passkeys/{other_passkey.id}", headers=auth_headers)+ assert forbidden.status_code == 404++ deleted = await client.delete(f"/api/auth/passkeys/{own_passkey.id}", headers=auth_headers)+ assert deleted.status_code == 204++ remaining = await session.execute(select(UserPasskey).order_by(UserPasskey.name))+ assert [item.name for item in remaining.scalars().all()] == ["Other key"]+++async def test_register_verify_deletes_challenge_after_failure(+ client: AsyncClient,+ auth_headers: dict,+ _passkey_redis_store,+):+ options_response = await client.post(+ "/api/auth/passkeys/register/options",+ json={"name": "Key"},+ headers=auth_headers,+ )+ challenge_id = options_response.json()["challenge_id"]++ with patch("app.api.passkeys.verify_registration_response", side_effect=ValueError("bad")):+ response = await client.post(+ "/api/auth/passkeys/register/verify",+ json={+ "challenge_id": challenge_id,+ "name": "Key",+ "credential": {+ "id": "bad",+ "rawId": "YmFk",+ "response": {"attestationObject": "bad", "clientDataJSON": "bad"},+ "type": "public-key",+ "clientExtensionResults": {},+ },+ },+ headers=auth_headers,+ )++ assert response.status_code == 400+ _passkey_redis_store.getdel.assert_called_once()+ _passkey_redis_store.delete.assert_not_called()+ assert _passkey_redis_store.store == {}diff --git a/frontend/src/components/app-layout.tsx b/frontend/src/components/app-layout.tsxindex 65f8e471..de242178 100644--- a/frontend/src/components/app-layout.tsx+++ b/frontend/src/components/app-layout.tsx@@ -58,10 +58,12 @@ import {HardDriveDownload,Shield,ShieldCheck,+ Fingerprint,} from 'lucide-react'import { usePrivacyMode } from '@/hooks/use-privacy-mode'import { ChangePasswordDialog } from '@/components/change-password-dialog'import { TwoFactorSetup } from '@/components/two-factor-setup'+import { PasskeyManagementDialog } from '@/components/passkey-management-dialog'import { CommandPalette } from '@/components/command-palette'import { useCommandPaletteHotkey } from '@/hooks/use-command-palette-hotkey'import { GlobalChatPanel } from '@/components/global-chat-panel'@@ -115,6 +117,7 @@ export function AppLayout() {const { privacyMode, togglePrivacyMode, mask } = usePrivacyMode()const [changePasswordOpen, setChangePasswordOpen] = useState(false)const [twoFactorOpen, setTwoFactorOpen] = useState(false)+ const [passkeysOpen, setPasskeysOpen] = useState(false)const [backingUp, setBackingUp] = useState(false)const [paletteOpen, setPaletteOpen] = useState(false)const [chatOpen, setChatOpen] = useState(false)@@ -260,6 +263,7 @@ export function AppLayout() {logout={logout}onChangePassword={() => setChangePasswordOpen(true)}onTwoFactor={() => setTwoFactorOpen(true)}+ onPasskeys={() => setPasskeysOpen(true)}agentsEnabled={agentsEnabled}backingUp={backingUp}onBackup={async () => {@@ -510,6 +514,7 @@ export function AppLayout() {backingUp={backingUp}onChangePassword={() => setChangePasswordOpen(true)}onTwoFactor={() => setTwoFactorOpen(true)}+ onPasskeys={() => setPasskeysOpen(true)}onBackup={async () => {setBackingUp(true)try {@@ -559,6 +564,10 @@ export function AppLayout() {open={twoFactorOpen}onClose={() => setTwoFactorOpen(false)}/>+ <PasskeyManagementDialog+ open={passkeysOpen}+ onClose={() => setPasskeysOpen(false)}+ /><CommandPalette open={paletteOpen} onOpenChange={setPaletteOpen} />{/* Slide-over global chat — opened from the sidebar pill or via⌘J. The previous floating bottom-right button was removed@@ -577,6 +586,7 @@ function UserMenu({logout,onChangePassword,onTwoFactor,+ onPasskeys,onBackup,backingUp,dark,@@ -587,6 +597,7 @@ function UserMenu({logout: () => voidonChangePassword: () => voidonTwoFactor: () => void+ onPasskeys: () => voidonBackup: () => voidbackingUp: booleandark?: boolean@@ -640,6 +651,13 @@ function UserMenu({<ShieldCheck size={14} />{t('auth.twoFactorTitle')}</DropdownMenuItem>+ <DropdownMenuItem+ onClick={onPasskeys}+ className="flex items-center gap-2"+ >+ <Fingerprint size={14} />+ {t('auth.passkeysTitle')}+ </DropdownMenuItem><DropdownMenuItemdisabled={backingUp}onClick={onBackup}diff --git a/frontend/src/components/passkey-management-dialog.tsx b/frontend/src/components/passkey-management-dialog.tsxnew file mode 100644index 00000000..31848ac8--- /dev/null+++ b/frontend/src/components/passkey-management-dialog.tsx@@ -0,0 +1,178 @@+import { useCallback, useEffect, useState } from 'react'+import { useTranslation } from 'react-i18next'+import { toast } from 'sonner'+import { Fingerprint, Trash2 } from 'lucide-react'+import { auth } from '@/lib/api'+import { isPasskeySupported, startPasskeyRegistration } from '@/lib/webauthn'+import type { Passkey } from '@/types'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'++interface PasskeyManagementDialogProps {+ open: boolean+ onClose: () => void+}++export function PasskeyManagementDialog({ open, onClose }: PasskeyManagementDialogProps) {+ const { t } = useTranslation()+ const [passkeys, setPasskeys] = useState<Passkey[]>([])+ const [name, setName] = useState('')+ const [loading, setLoading] = useState(false)+ const [saving, setSaving] = useState(false)+ const [deletingId, setDeletingId] = useState<string | null>(null)+ const [error, setError] = useState('')+ const supported = isPasskeySupported()++ const loadPasskeys = useCallback(async () => {+ setLoading(true)+ setError('')+ try {+ setPasskeys(await auth.listPasskeys())+ } catch {+ setError(t('auth.passkeyLoadError'))+ } finally {+ setLoading(false)+ }+ }, [t])++ useEffect(() => {+ if (open) void loadPasskeys()+ }, [open, loadPasskeys])++ const formatDate = (value: string | null) => {+ if (!value) return t('auth.passkeyNeverUsed')+ return new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(new Date(value))+ }++ const handleClose = () => {+ setName('')+ setError('')+ onClose()+ }++ const handleRegister = async (event: React.FormEvent) => {+ event.preventDefault()+ const passkeyName = name.trim() || t('auth.defaultPasskeyName')+ setSaving(true)+ setError('')+ try {+ const options = await auth.registerPasskeyOptions(passkeyName)+ const credential = await startPasskeyRegistration(options.options)+ const created = await auth.verifyPasskeyRegistration(options.challenge_id, passkeyName, credential)+ setPasskeys((current) => [...current, created])+ setName('')+ 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)+ } finally {+ setSaving(false)+ }+ }++ const handleDelete = async (passkey: Passkey) => {+ if (!window.confirm(t('auth.passkeyDeleteConfirm', { name: passkey.name }))) return+ setDeletingId(passkey.id)+ setError('')+ try {+ await auth.deletePasskey(passkey.id)+ setPasskeys((current) => current.filter((item) => item.id !== passkey.id))+ toast.success(t('auth.passkeyDeleted'))+ } catch {+ setError(t('auth.passkeyDeleteError'))+ } finally {+ setDeletingId(null)+ }+ }++ return (+ <Dialog open={open} onOpenChange={(v) => !v && handleClose()}>+ <DialogContent className="sm:max-w-lg">+ <DialogHeader>+ <DialogTitle>{t('auth.passkeysTitle')}</DialogTitle>+ </DialogHeader>++ <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')}+ </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>+ <Input+ id="passkey-name"+ value={name}+ onChange={(event) => setName(event.target.value)}+ placeholder={t('auth.passkeyNamePlaceholder')}+ maxLength={100}+ disabled={saving}+ />+ </div>+ <Button type="submit" disabled={!supported || saving} className="w-full">+ {saving ? t('common.loading') : t('auth.addPasskey')}+ </Button>+ </form>++ <div className="space-y-2">+ {loading ? (+ <p className="text-sm text-muted-foreground">{t('common.loading')}</p>+ ) : passkeys.length === 0 ? (+ <p className="text-sm text-muted-foreground">{t('auth.noPasskeys')}</p>+ ) : (+ 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>+ </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>++ <DialogFooter>+ <Button type="button" variant="outline" onClick={handleClose}>+ {t('common.close')}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/components/workspace-switcher.tsx b/frontend/src/components/workspace-switcher.tsxindex c905391c..c0e09368 100644--- a/frontend/src/components/workspace-switcher.tsx+++ b/frontend/src/components/workspace-switcher.tsx@@ -43,6 +43,7 @@ import {Shield,ShieldCheck,Sparkles,+ Fingerprint,} from 'lucide-react'import { CategoryIcon } from '@/components/category-icon'import type { Workspace } from '@/types'@@ -77,6 +78,8 @@ interface AccountMenuProps {onChangePassword: () => void/** Open the 2FA setup dialog. */onTwoFactor: () => void+ /** Open the passkey management dialog. */+ onPasskeys: () => void/** Trigger a backup download. */onBackup: () => void/** Open the "Update available" dialog. */@@ -98,6 +101,7 @@ export function WorkspaceSwitcher({backingUp,onChangePassword,onTwoFactor,+ onPasskeys,onBackup,onUpdateAvailable,agentsEnabled,@@ -240,6 +244,13 @@ export function WorkspaceSwitcher({<ShieldCheck size={14} />{t('auth.twoFactorTitle')}</DropdownMenuItem>+ <DropdownMenuItem+ onClick={onPasskeys}+ className="flex items-center gap-2"+ >+ <Fingerprint size={14} />+ {t('auth.passkeysTitle')}+ </DropdownMenuItem><DropdownMenuItemdisabled={backingUp}onClick={onBackup}diff --git a/frontend/src/contexts/auth-context.tsx b/frontend/src/contexts/auth-context.tsxindex b0fde987..994d9e24 100644--- a/frontend/src/contexts/auth-context.tsx+++ b/frontend/src/contexts/auth-context.tsx@@ -6,6 +6,7 @@ import type { User } from '@/types'interface LoginResult {requires_2fa: booleantemp_token?: string+ available_methods?: Array<'totp' | 'passkey'>}interface AuthContextType {@@ -58,7 +59,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {const data = await auth.login(email, password)if (data.requires_2fa) {- return { requires_2fa: true, temp_token: data.temp_token }+ return { requires_2fa: true, temp_token: data.temp_token, available_methods: data.available_methods }}const accessToken = data.access_tokendiff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.tsindex 9a9c6d18..c967fe85 100644--- a/frontend/src/lib/api.ts+++ b/frontend/src/lib/api.ts@@ -4,6 +4,8 @@ import type {User,AdminUser,AdminUserList,+ Passkey,+ PasskeyOptionsResponse,AppSetting,Category,CategoryGroup,@@ -187,6 +189,59 @@ export const auth = {const { data } = await api.post('/auth/2fa/verify', { temp_token: tempToken, code })return data},+ listPasskeys: async (): Promise<Passkey[]> => {+ const { data } = await api.get('/auth/passkeys')+ return data+ },+ registerPasskeyOptions: async (name: string): Promise<PasskeyOptionsResponse> => {+ const { data } = await api.post('/auth/passkeys/register/options', { name })+ return data+ },+ verifyPasskeyRegistration: async (+ challengeId: string,+ name: string,+ credential: Record<string, unknown>,+ ): Promise<Passkey> => {+ const { data } = await api.post('/auth/passkeys/register/verify', {+ challenge_id: challengeId,+ name,+ credential,+ })+ return data+ },+ deletePasskey: async (id: string): Promise<void> => {+ await api.delete(`/auth/passkeys/${id}`)+ },+ passkeyAuthenticationOptions: async (email?: string): Promise<PasskeyOptionsResponse> => {+ const { data } = await api.post('/auth/passkeys/authenticate/options', { email })+ return data+ },+ verifyPasskeyAuthentication: async (+ challengeId: string,+ credential: Record<string, unknown>,+ ): Promise<{ access_token: string; token_type: string }> => {+ const { data } = await api.post('/auth/passkeys/authenticate/verify', {+ challenge_id: challengeId,+ credential,+ })+ return data+ },+ passkeySecondFactorOptions: async (tempToken: string): Promise<PasskeyOptionsResponse> => {+ const { data } = await api.post('/auth/passkeys/2fa/options', { temp_token: tempToken })+ return data+ },+ verifyPasskeySecondFactor: async (+ tempToken: string,+ challengeId: string,+ credential: Record<string, unknown>,+ ): Promise<{ access_token: string; token_type: string }> => {+ const { data } = await api.post('/auth/passkeys/2fa/verify', {+ temp_token: tempToken,+ challenge_id: challengeId,+ credential,+ })+ return data+ },oidcConfig: async (): Promise<{ enabled: boolean; provider_name: string }> => {const { data } = await api.get('/auth/oidc/config')return datadiff --git a/frontend/src/lib/webauthn.ts b/frontend/src/lib/webauthn.tsnew file mode 100644index 00000000..2fd64120--- /dev/null+++ b/frontend/src/lib/webauthn.ts@@ -0,0 +1,149 @@+type PublicKeyCredentialCreationOptionsJSON = Omit<PublicKeyCredentialCreationOptions, 'challenge' | 'user' | 'excludeCredentials'> & {+ challenge: string+ user: Omit<PublicKeyCredentialUserEntity, 'id'> & { id: string }+ excludeCredentials?: Array<Omit<PublicKeyCredentialDescriptor, 'id'> & { id: string }>+}++type PublicKeyCredentialRequestOptionsJSON = Omit<PublicKeyCredentialRequestOptions, 'challenge' | 'allowCredentials'> & {+ challenge: string+ allowCredentials?: Array<Omit<PublicKeyCredentialDescriptor, 'id'> & { id: string }>+}++type RegistrationCredentialJSON = {+ id: string+ rawId: string+ type: string+ authenticatorAttachment?: string | null+ transports?: string[]+ response: {+ attestationObject: string+ clientDataJSON: string+ }+ clientExtensionResults: AuthenticationExtensionsClientOutputs+}++type AuthenticationCredentialJSON = {+ id: string+ rawId: string+ type: string+ authenticatorAttachment?: string | null+ response: {+ authenticatorData: string+ clientDataJSON: string+ signature: string+ userHandle: string | null+ }+ clientExtensionResults: AuthenticationExtensionsClientOutputs+}++export function isPasskeySupported(): boolean {+ return (+ typeof window !== 'undefined' &&+ window.isSecureContext &&+ 'PublicKeyCredential' in window &&+ !!navigator.credentials+ )+}++function base64urlToArrayBuffer(value: string): ArrayBuffer {+ const base64 = value.replace(/-/g, '+').replace(/_/g, '/')+ const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), '=')+ const binary = atob(padded)+ const bytes = new Uint8Array(binary.length)+ for (let i = 0; i < binary.length; i += 1) {+ bytes[i] = binary.charCodeAt(i)+ }+ return bytes.buffer+}++function arrayBufferToBase64url(buffer: ArrayBuffer): string {+ const bytes = new Uint8Array(buffer)+ let binary = ''+ for (let i = 0; i < bytes.byteLength; i += 1) {+ binary += String.fromCharCode(bytes[i])+ }+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')+}++function creationOptionsFromJSON(options: PublicKeyCredentialCreationOptionsJSON): PublicKeyCredentialCreationOptions {+ return {+ ...options,+ challenge: base64urlToArrayBuffer(options.challenge),+ user: {+ ...options.user,+ id: base64urlToArrayBuffer(options.user.id),+ },+ excludeCredentials: options.excludeCredentials?.map((credential) => ({+ ...credential,+ id: base64urlToArrayBuffer(credential.id),+ })),+ }+}++function requestOptionsFromJSON(options: PublicKeyCredentialRequestOptionsJSON): PublicKeyCredentialRequestOptions {+ return {+ ...options,+ challenge: base64urlToArrayBuffer(options.challenge),+ allowCredentials: options.allowCredentials?.map((credential) => ({+ ...credential,+ id: base64urlToArrayBuffer(credential.id),+ })),+ }+}++export async function startPasskeyRegistration(options: Record<string, unknown>): Promise<RegistrationCredentialJSON> {+ if (!isPasskeySupported()) {+ throw new Error('Passkeys are not supported in this browser or context')+ }++ const credential = await navigator.credentials.create({+ publicKey: creationOptionsFromJSON(options as PublicKeyCredentialCreationOptionsJSON),+ })++ if (!(credential instanceof PublicKeyCredential)) {+ throw new Error('No passkey credential was created')+ }++ const response = credential.response as AuthenticatorAttestationResponse+ return {+ id: credential.id,+ rawId: arrayBufferToBase64url(credential.rawId),+ type: credential.type,+ authenticatorAttachment: credential.authenticatorAttachment,+ transports: response.getTransports?.(),+ response: {+ attestationObject: arrayBufferToBase64url(response.attestationObject),+ clientDataJSON: arrayBufferToBase64url(response.clientDataJSON),+ },+ clientExtensionResults: credential.getClientExtensionResults(),+ }+}++export async function startPasskeyAuthentication(options: Record<string, unknown>): Promise<AuthenticationCredentialJSON> {+ if (!isPasskeySupported()) {+ throw new Error('Passkeys are not supported in this browser or context')+ }++ const credential = await navigator.credentials.get({+ publicKey: requestOptionsFromJSON(options as PublicKeyCredentialRequestOptionsJSON),+ })++ if (!(credential instanceof PublicKeyCredential)) {+ throw new Error('No passkey credential was selected')+ }++ const response = credential.response as AuthenticatorAssertionResponse+ return {+ id: credential.id,+ rawId: arrayBufferToBase64url(credential.rawId),+ type: credential.type,+ authenticatorAttachment: credential.authenticatorAttachment,+ response: {+ authenticatorData: arrayBufferToBase64url(response.authenticatorData),+ clientDataJSON: arrayBufferToBase64url(response.clientDataJSON),+ signature: arrayBufferToBase64url(response.signature),+ userHandle: response.userHandle ? arrayBufferToBase64url(response.userHandle) : null,+ },+ clientExtensionResults: credential.getClientExtensionResults(),+ }+}diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 49da9d8a..05b1c8e7 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -190,7 +190,34 @@"twoFactorEnabled": "Two-factor authentication enabled","twoFactorDisabled": "Two-factor authentication disabled","or": "or",- "loginWithProvider": "Continue with {{provider}}"+ "loginWithProvider": "Continue with {{provider}}",+ "loginWithPasskey": "Continue with passkey",+ "passkeyLoginError": "Could not sign in with that passkey",+ "passkeyCancelled": "Passkey prompt was cancelled",+ "passkeyMethod": "Passkey",+ "totpMethod": "Authenticator code",+ "usePasskeySecondFactor": "Use security key/passkey",+ "passkeySecondFactorTitle": "Security key verification",+ "passkeySecondFactorDescription": "Use your security key or device passkey to approve this sign-in.",+ "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",+ "passkeyName": "Passkey name",+ "passkeyNamePlaceholder": "e.g. YubiKey, MacBook Touch ID",+ "defaultPasskeyName": "Passkey",+ "addPasskey": "Add passkey",+ "passkeyAdded": "Passkey added",+ "passkeyDeleted": "Passkey deleted",+ "passkeyRegisterError": "Could not add passkey",+ "passkeyDeleteError": "Could not delete passkey",+ "passkeyDeleteConfirm": "Delete passkey \"{{name}}\"?",+ "noPasskeys": "No passkeys registered yet.",+ "deletePasskey": "Delete passkey",+ "passkeyCreated": "Created",+ "passkeyLastUsed": "Last used",+ "passkeyNeverUsed": "Never"},"dashboard": {"title": "Dashboard",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 7457fe3f..d330caa4 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -190,7 +190,34 @@"twoFactorEnabled": "Autenticación de dos factores activada","twoFactorDisabled": "Autenticación de dos factores desactivada","or": "o",- "loginWithProvider": "Continuar con {{provider}}"+ "loginWithProvider": "Continuar con {{provider}}",+ "loginWithPasskey": "Continuar con llave de acceso",+ "passkeyLoginError": "No se pudo iniciar sesión con esa llave de acceso",+ "passkeyCancelled": "Se canceló la solicitud de la llave de acceso",+ "passkeyMethod": "Llave de acceso",+ "totpMethod": "Código autenticador",+ "usePasskeySecondFactor": "Usar llave de seguridad/acceso",+ "passkeySecondFactorTitle": "Verificación con llave de seguridad",+ "passkeySecondFactorDescription": "Usa tu llave de seguridad o llave de acceso del dispositivo para aprobar este inicio de sesión.",+ "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",+ "passkeyName": "Nombre de la llave de acceso",+ "passkeyNamePlaceholder": "p. ej. YubiKey, Touch ID de MacBook",+ "defaultPasskeyName": "Llave de acceso",+ "addPasskey": "Añadir llave de acceso",+ "passkeyAdded": "Llave de acceso añadida",+ "passkeyDeleted": "Llave de acceso eliminada",+ "passkeyRegisterError": "No se pudo añadir la llave de acceso",+ "passkeyDeleteError": "No se pudo eliminar la llave de acceso",+ "passkeyDeleteConfirm": "¿Eliminar la llave de acceso \"{{name}}\"?",+ "noPasskeys": "Aún no hay llaves de acceso registradas.",+ "deletePasskey": "Eliminar llave de acceso",+ "passkeyCreated": "Creada",+ "passkeyLastUsed": "Último uso",+ "passkeyNeverUsed": "Nunca"},"dashboard": {"title": "Inicio",diff --git a/frontend/src/locales/it.json b/frontend/src/locales/it.jsonindex 5c122194..9b0b0f15 100644--- a/frontend/src/locales/it.json+++ b/frontend/src/locales/it.json@@ -161,7 +161,36 @@"disable2fa": "Disabilita 2FA","disable2faDescription": "Inserisci la tua password e un codice di verifica per disabilitare l'autenticazione a due fattori.","twoFactorEnabled": "Autenticazione a due fattori abilitata",- "twoFactorDisabled": "Autenticazione a due fattori disabilitata"+ "twoFactorDisabled": "Autenticazione a due fattori disabilitata",+ "or": "o",+ "loginWithProvider": "Continua con {{provider}}",+ "loginWithPasskey": "Continua con passkey",+ "passkeyLoginError": "Impossibile accedere con questa passkey",+ "passkeyCancelled": "La richiesta della passkey è stata annullata",+ "passkeyMethod": "Passkey",+ "totpMethod": "Codice autenticatore",+ "usePasskeySecondFactor": "Usa chiave di sicurezza/passkey",+ "passkeySecondFactorTitle": "Verifica con chiave di sicurezza",+ "passkeySecondFactorDescription": "Usa la tua chiave di sicurezza o passkey del dispositivo per approvare questo accesso.",+ "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",+ "passkeyName": "Nome passkey",+ "passkeyNamePlaceholder": "es. YubiKey, Touch ID del MacBook",+ "defaultPasskeyName": "Passkey",+ "addPasskey": "Aggiungi passkey",+ "passkeyAdded": "Passkey aggiunta",+ "passkeyDeleted": "Passkey eliminata",+ "passkeyRegisterError": "Impossibile aggiungere la passkey",+ "passkeyDeleteError": "Impossibile eliminare la passkey",+ "passkeyDeleteConfirm": "Eliminare la passkey \"{{name}}\"?",+ "noPasskeys": "Nessuna passkey registrata.",+ "deletePasskey": "Elimina passkey",+ "passkeyCreated": "Creata",+ "passkeyLastUsed": "Ultimo utilizzo",+ "passkeyNeverUsed": "Mai"},"dashboard": {"title": "Dashboard",diff --git a/frontend/src/locales/pl.json b/frontend/src/locales/pl.jsonindex b65b230d..88d299ac 100644--- a/frontend/src/locales/pl.json+++ b/frontend/src/locales/pl.json@@ -190,7 +190,34 @@"twoFactorEnabled": "Włączono uwierzytelnianie dwuskładnikowe","twoFactorDisabled": "Wyłączono uwierzytelnianie dwuskładnikowe","or": "lub",- "loginWithProvider": "Kontynuuj z {{provider}}"+ "loginWithProvider": "Kontynuuj z {{provider}}",+ "loginWithPasskey": "Kontynuuj z kluczem dostępu",+ "passkeyLoginError": "Nie udało się zalogować tym kluczem dostępu",+ "passkeyCancelled": "Anulowano żądanie klucza dostępu",+ "passkeyMethod": "Klucz dostępu",+ "totpMethod": "Kod z aplikacji",+ "usePasskeySecondFactor": "Użyj klucza bezpieczeństwa/dostępu",+ "passkeySecondFactorTitle": "Weryfikacja kluczem bezpieczeństwa",+ "passkeySecondFactorDescription": "Użyj klucza bezpieczeństwa lub klucza dostępu urządzenia, aby zatwierdzić to logowanie.",+ "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",+ "passkeyName": "Nazwa klucza dostępu",+ "passkeyNamePlaceholder": "np. YubiKey, Touch ID MacBooka",+ "defaultPasskeyName": "Klucz dostępu",+ "addPasskey": "Dodaj klucz dostępu",+ "passkeyAdded": "Dodano klucz dostępu",+ "passkeyDeleted": "Usunięto klucz dostępu",+ "passkeyRegisterError": "Nie udało się dodać klucza dostępu",+ "passkeyDeleteError": "Nie udało się usunąć klucza dostępu",+ "passkeyDeleteConfirm": "Usunąć klucz dostępu „{{name}}”?",+ "noPasskeys": "Nie zarejestrowano jeszcze kluczy dostępu.",+ "deletePasskey": "Usuń klucz dostępu",+ "passkeyCreated": "Utworzono",+ "passkeyLastUsed": "Ostatnio użyty",+ "passkeyNeverUsed": "Nigdy"},"dashboard": {"title": "Pulpit",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 7e86afe3..9b6e366a 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -190,7 +190,34 @@"twoFactorEnabled": "Autenticação em dois fatores ativada","twoFactorDisabled": "Autenticação de dois fatores desativada","or": "ou",- "loginWithProvider": "Continuar com {{provider}}"+ "loginWithProvider": "Continuar com {{provider}}",+ "loginWithPasskey": "Continuar com chave de acesso",+ "passkeyLoginError": "Não foi possível entrar com essa chave de acesso",+ "passkeyCancelled": "A solicitação da chave de acesso foi cancelada",+ "passkeyMethod": "Chave de acesso",+ "totpMethod": "Código autenticador",+ "usePasskeySecondFactor": "Usar chave de segurança/acesso",+ "passkeySecondFactorTitle": "Verificação com chave de segurança",+ "passkeySecondFactorDescription": "Use sua chave de segurança ou chave de acesso do dispositivo para aprovar este login.",+ "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",+ "passkeyName": "Nome da chave de acesso",+ "passkeyNamePlaceholder": "ex.: YubiKey, Touch ID do MacBook",+ "defaultPasskeyName": "Chave de acesso",+ "addPasskey": "Adicionar chave de acesso",+ "passkeyAdded": "Chave de acesso adicionada",+ "passkeyDeleted": "Chave de acesso excluída",+ "passkeyRegisterError": "Não foi possível adicionar a chave de acesso",+ "passkeyDeleteError": "Não foi possível excluir a chave de acesso",+ "passkeyDeleteConfirm": "Excluir a chave de acesso \"{{name}}\"?",+ "noPasskeys": "Nenhuma chave de acesso cadastrada ainda.",+ "deletePasskey": "Excluir chave de acesso",+ "passkeyCreated": "Criada",+ "passkeyLastUsed": "Último uso",+ "passkeyNeverUsed": "Nunca"},"dashboard": {"title": "Painel",diff --git a/frontend/src/pages/login.tsx b/frontend/src/pages/login.tsxindex 82018739..65d7620e 100644--- a/frontend/src/pages/login.tsx+++ b/frontend/src/pages/login.tsx@@ -12,16 +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'export default function LoginPage() {const { t } = useTranslation()- const { login, verify2fa, token } = useAuth()+ const { login, verify2fa, loginWithToken, token } = useAuth()const navigate = useNavigate()const { resolvedTheme } = useTheme()const [email, setEmail] = useState('')const [password, setPassword] = useState('')const [error, setError] = useState('')const [isLoading, setIsLoading] = useState(false)+ const [isPasskeyLoading, setIsPasskeyLoading] = useState(false)+ const [passkeySupported, setPasskeySupported] = useState(false)const [registrationEnabled, setRegistrationEnabled] = useState(true)const [oidcConfig, setOidcConfig] = useState<{ enabled: boolean; provider_name: string }>({ enabled: false, provider_name: 'OIDC' })@@ -29,8 +32,11 @@ export default function LoginPage() {const [requires2fa, setRequires2fa] = useState(false)const [tempToken, setTempToken] = useState('')const [totpCode, setTotpCode] = useState('')+ const [available2faMethods, setAvailable2faMethods] = useState<Array<'totp' | 'passkey'>>(['totp'])+ const [selected2faMethod, setSelected2faMethod] = useState<'totp' | 'passkey'>('totp')useEffect(() => {+ setPasskeySupported(isPasskeySupported())if (token) {navigate('/', { replace: true })return@@ -56,8 +62,11 @@ export default function LoginPage() {try {const result = await login(email, password)if (result.requires_2fa) {+ const methods: Array<'totp' | 'passkey'> = result.available_methods?.length ? result.available_methods : ['totp']setRequires2fa(true)setTempToken(result.temp_token ?? '')+ setAvailable2faMethods(methods)+ setSelected2faMethod(methods.includes('passkey') ? 'passkey' : methods[0])} else {navigate('/')}@@ -79,6 +88,31 @@ export default function LoginPage() {window.location.href = '/api/auth/oidc/login'}+ const handlePasskeyLogin = async () => {+ setError('')+ setIsPasskeyLoading(true)+ try {+ const trimmedEmail = email.trim()+ const options = await authApi.passkeyAuthenticationOptions(trimmedEmail || undefined)+ const credential = await startPasskeyAuthentication(options.options)+ const result = await authApi.verifyPasskeyAuthentication(options.challenge_id, credential)+ loginWithToken(result.access_token)+ 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) {+ setError(t('auth.tooManyAttempts'))+ } else {+ setError(t('auth.passkeyLoginError'))+ }+ } finally {+ setIsPasskeyLoading(false)+ }+ }+const handleVerify2fa = async (e: React.FormEvent) => {e.preventDefault()setError('')@@ -93,9 +127,7 @@ export default function LoginPage() {} else if (axiosErr?.response?.status === 401) {setError(t('auth.invalidCredentials'))// Token expired, go back to login- setRequires2fa(false)- setTempToken('')- setTotpCode('')+ resetSecondFactor()} else {setError(t('auth.invalid2faCode'))}@@ -104,6 +136,42 @@ export default function LoginPage() {}}+ function resetSecondFactor() {+ setRequires2fa(false)+ setTempToken('')+ setTotpCode('')+ setAvailable2faMethods(['totp'])+ setSelected2faMethod('totp')+ setError('')+ }++ const handlePasskeySecondFactor = async () => {+ setError('')+ setIsPasskeyLoading(true)+ try {+ const options = await authApi.passkeySecondFactorOptions(tempToken)+ const credential = await startPasskeyAuthentication(options.options)+ const result = await authApi.verifyPasskeySecondFactor(tempToken, options.challenge_id, credential)+ loginWithToken(result.access_token)+ 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 === 401) {+ setError(t('auth.invalidCredentials'))+ resetSecondFactor()+ } else if (axiosErr?.response?.status === 429) {+ setError(t('auth.tooManyAttempts'))+ } else {+ setError(t('auth.passkeyLoginError'))+ }+ } finally {+ setIsPasskeyLoading(false)+ }+ }+if (requires2fa) {return (<div className="flex flex-col items-center justify-center min-h-screen bg-background px-4">@@ -113,8 +181,14 @@ export default function LoginPage() {<div className="w-11 h-11 rounded-xl bg-primary/10 flex items-center justify-center mb-4"><ShellLogo size={22} className="text-primary" /></div>- <h1 className="text-xl font-semibold tracking-tight">{t('auth.twoFactor')}</h1>- <p className="text-sm text-muted-foreground mt-1">{t('auth.twoFactorDescription')}</p>+ <h1 className="text-xl font-semibold tracking-tight">+ {selected2faMethod === 'passkey' ? t('auth.passkeySecondFactorTitle') : t('auth.twoFactorTitle')}+ </h1>+ <p className="text-sm text-muted-foreground mt-1 text-center">+ {selected2faMethod === 'passkey'+ ? t('auth.passkeySecondFactorDescription')+ : t('auth.twoFactorDescription')}+ </p></div><CardContent className="space-y-4 px-8 pt-4">{error && (@@ -122,35 +196,70 @@ export default function LoginPage() {{error}</div>)}- <div className="space-y-1.5">- <Label htmlFor="totp-code" className="text-sm">{t('auth.twoFactor')}</Label>- <Input- id="totp-code"- type="text"- inputMode="numeric"- autoComplete="one-time-code"- value={totpCode}- onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, '').slice(0, 6))}- placeholder="000000"- className="text-center text-lg tracking-[0.3em] font-mono"- maxLength={6}- required- autoFocus- />- </div>+ {available2faMethods.length > 1 && (+ <div className="grid grid-cols-2 gap-2">+ {available2faMethods.includes('passkey') && (+ <Button+ type="button"+ variant={selected2faMethod === 'passkey' ? 'default' : 'outline'}+ onClick={() => setSelected2faMethod('passkey')}+ >+ {t('auth.passkeyMethod')}+ </Button>+ )}+ {available2faMethods.includes('totp') && (+ <Button+ type="button"+ variant={selected2faMethod === 'totp' ? 'default' : 'outline'}+ onClick={() => setSelected2faMethod('totp')}+ >+ {t('auth.totpMethod')}+ </Button>+ )}+ </div>+ )}+ {selected2faMethod === 'totp' && (+ <div className="space-y-1.5">+ <Label htmlFor="totp-code" className="text-sm">{t('auth.twoFactor')}</Label>+ <Input+ id="totp-code"+ type="text"+ inputMode="numeric"+ autoComplete="one-time-code"+ value={totpCode}+ onChange={(e) => setTotpCode(e.target.value.replace(/\D/g, '').slice(0, 6))}+ placeholder="000000"+ className="text-center text-lg tracking-[0.3em] font-mono"+ maxLength={6}+ required+ autoFocus+ />+ </div>+ )}+ {selected2faMethod === 'passkey' && (+ <p className="text-sm text-muted-foreground text-center">+ {t('auth.passkeySecondFactorPrompt')}+ </p>+ )}</CardContent><CardFooter className="flex flex-col gap-4 px-8 pb-8 pt-2">- <Button type="submit" className="w-full" disabled={isLoading || totpCode.length !== 6}>- {isLoading ? t('common.loading') : t('auth.verify')}- </Button>+ {selected2faMethod === 'totp' ? (+ <Button type="submit" className="w-full" disabled={isLoading || totpCode.length !== 6}>+ {isLoading ? t('common.loading') : t('auth.verify')}+ </Button>+ ) : (+ <Button+ type="button"+ className="w-full"+ onClick={handlePasskeySecondFactor}+ disabled={isLoading || isPasskeyLoading || !passkeySupported}+ >+ {isPasskeyLoading ? t('common.loading') : t('auth.usePasskeySecondFactor')}+ </Button>+ )}<buttontype="button"- onClick={() => {- setRequires2fa(false)- setTempToken('')- setTotpCode('')- setError('')- }}+ onClick={resetSecondFactor}className="text-sm text-muted-foreground hover:text-foreground">{t('auth.login')}@@ -202,20 +311,31 @@ export default function LoginPage() {</div></CardContent><CardFooter className="flex flex-col gap-4 px-8 pb-8 pt-2">- <Button type="submit" className="w-full" disabled={isLoading}>+ <Button type="submit" className="w-full" disabled={isLoading || isPasskeyLoading}>{isLoading ? t('common.loading') : t('auth.login')}</Button>+ {(passkeySupported || oidcConfig.enabled) && (+ <div className="flex items-center gap-3 w-full">+ <div className="h-px flex-1 bg-border" />+ <span className="text-xs text-muted-foreground">{t('auth.or')}</span>+ <div className="h-px flex-1 bg-border" />+ </div>+ )}+ {passkeySupported && (+ <Button+ type="button"+ variant="outline"+ className="w-full"+ onClick={handlePasskeyLogin}+ disabled={isLoading || isPasskeyLoading}+ >+ {isPasskeyLoading ? t('common.loading') : t('auth.loginWithPasskey')}+ </Button>+ )}{oidcConfig.enabled && (- <>- <div className="flex items-center gap-3 w-full">- <div className="h-px flex-1 bg-border" />- <span className="text-xs text-muted-foreground">{t('auth.or')}</span>- <div className="h-px flex-1 bg-border" />- </div>- <Button type="button" variant="outline" className="w-full" onClick={handleOIDCLogin}>- {t('auth.loginWithProvider', { provider: oidcConfig.provider_name })}- </Button>- </>+ <Button type="button" variant="outline" className="w-full" onClick={handleOIDCLogin}>+ {t('auth.loginWithProvider', { provider: oidcConfig.provider_name })}+ </Button>)}{registrationEnabled && (<p className="text-sm text-muted-foreground">diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex e7e20ec3..9fcffdc3 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -22,6 +22,22 @@ export interface AdminUserList {total: number}+export interface Passkey {+ id: string+ name: string+ transports: string[] | null+ aaguid: string | null+ device_type: string | null+ backed_up: boolean | null+ created_at: string+ last_used_at: string | null+}++export interface PasskeyOptionsResponse {+ challenge_id: string+ options: Record<string, unknown>+}+export interface AppSetting {key: stringvalue: string