Open-source personal finance manager. Self-hosted, privacy-first.
feat: offer passkeys through conditional UI (#744)
Leonardo Zanivan96a3253387cc
diff --git a/frontend/src/lib/webauthn.test.ts b/frontend/src/lib/webauthn.test.tsnew file mode 100644index 00000000..8097946f--- /dev/null+++ b/frontend/src/lib/webauthn.test.ts@@ -0,0 +1,75 @@+/// <reference lib="dom" />++import { afterEach, describe, expect, it, vi } from 'vitest'++import {+ isConditionalPasskeySupported,+ startConditionalPasskeyAuthentication,+} from './webauthn'++class FakePublicKeyCredential {+ static isConditionalMediationAvailable = vi.fn<() => Promise<boolean>>()++ id = 'credential-id'+ rawId = new Uint8Array([1]).buffer+ type = 'public-key'+ authenticatorAttachment = 'platform'+ response = {+ authenticatorData: new Uint8Array([2]).buffer,+ clientDataJSON: new Uint8Array([3]).buffer,+ signature: new Uint8Array([4]).buffer,+ userHandle: new Uint8Array([5]).buffer,+ }++ getClientExtensionResults() {+ return {}+ }+}++function installWebAuthn(get = vi.fn()) {+ vi.stubGlobal('PublicKeyCredential', FakePublicKeyCredential)+ vi.stubGlobal('navigator', { credentials: { get } })+ vi.stubGlobal('window', {+ isSecureContext: true,+ location: { hostname: 'securo.example.com' },+ PublicKeyCredential: FakePublicKeyCredential,+ })+ return get+}++afterEach(() => {+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe('conditional passkey authentication', () => {+ it('uses the browser feature-detection result', async () => {+ installWebAuthn()+ FakePublicKeyCredential.isConditionalMediationAvailable.mockResolvedValue(true)++ await expect(isConditionalPasskeySupported()).resolves.toBe(true)+ expect(FakePublicKeyCredential.isConditionalMediationAvailable).toHaveBeenCalledOnce()+ })++ it('requests credentials with conditional mediation and an abort signal', async () => {+ const credential = new FakePublicKeyCredential()+ const get = installWebAuthn(vi.fn().mockResolvedValue(credential))+ const abortController = new AbortController()++ const result = await startConditionalPasskeyAuthentication(+ { challenge: 'AQ', rpId: 'example.com', userVerification: 'required' },+ abortController.signal,+ )++ expect(get).toHaveBeenCalledWith(expect.objectContaining({+ mediation: 'conditional',+ signal: abortController.signal,+ publicKey: expect.objectContaining({ rpId: 'example.com' }),+ }))+ expect(result).toMatchObject({+ id: 'credential-id',+ rawId: 'AQ',+ response: { userHandle: 'BQ' },+ })+ })+})diff --git a/frontend/src/lib/webauthn.ts b/frontend/src/lib/webauthn.tsindex e4acbc82..d1ca2b60 100644--- a/frontend/src/lib/webauthn.ts+++ b/frontend/src/lib/webauthn.ts@@ -66,6 +66,22 @@ export function isPasskeySupported(): boolean {return passkeyBlocker() === null}+/** Whether this browser can surface passkeys through form autofill. */+export async function isConditionalPasskeySupported(): Promise<boolean> {+ if (!isPasskeySupported()) return false++ const credentialType = PublicKeyCredential as typeof PublicKeyCredential & {+ isConditionalMediationAvailable?: () => Promise<boolean>+ }+ if (!credentialType.isConditionalMediationAvailable) return false++ try {+ return await credentialType.isConditionalMediationAvailable()+ } catch {+ return false+ }+}+const SERVER_FAILURES: Record<string, PasskeyFailure> = {passkey_origin_ip: 'ip',passkey_origin_insecure: 'insecure',@@ -166,13 +182,17 @@ export async function startPasskeyRegistration(options: Record<string, unknown>)}}-export async function startPasskeyAuthentication(options: Record<string, unknown>): Promise<AuthenticationCredentialJSON> {+async function getPasskeyAuthentication(+ options: Record<string, unknown>,+ request: Pick<CredentialRequestOptions, 'mediation' | 'signal'> = {},+): 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),+ ...request,})if (!(credential instanceof PublicKeyCredential)) {@@ -194,3 +214,14 @@ export async function startPasskeyAuthentication(options: Record<string, unknownclientExtensionResults: credential.getClientExtensionResults(),}}++export async function startPasskeyAuthentication(options: Record<string, unknown>): Promise<AuthenticationCredentialJSON> {+ return getPasskeyAuthentication(options)+}++export async function startConditionalPasskeyAuthentication(+ options: Record<string, unknown>,+ signal: AbortSignal,+): Promise<AuthenticationCredentialJSON> {+ return getPasskeyAuthentication(options, { mediation: 'conditional', signal })+}diff --git a/frontend/src/pages/login.tsx b/frontend/src/pages/login.tsxindex f01ddd6a..9e4e4bb6 100644--- a/frontend/src/pages/login.tsx+++ b/frontend/src/pages/login.tsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react'+import { useState, useEffect, useRef } from 'react'import { Link, useNavigate } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useAuth } from '@/contexts/auth-context'@@ -13,7 +13,13 @@ import { isServerUnreachable } from '@/lib/auth-errors'import { resolveLocalAuthEnabled } from '@/lib/auth-config-utils'import { useTheme } from 'next-themes'import { setThemeBasedOnSystem } from '@/lib/theme-utils'-import { isPasskeySupported, passkeyFailure, startPasskeyAuthentication } from '@/lib/webauthn'+import {+ isConditionalPasskeySupported,+ isPasskeySupported,+ passkeyFailure,+ startConditionalPasskeyAuthentication,+ startPasskeyAuthentication,+} from '@/lib/webauthn'import type { PasskeyFailure } from '@/lib/webauthn'const PASSKEY_LOGIN_FAILURE_KEYS: Record<PasskeyFailure, string> = {@@ -54,6 +60,14 @@ export default function LoginPage() {const [totpCode, setTotpCode] = useState('')const [available2faMethods, setAvailable2faMethods] = useState<Array<'totp' | 'passkey'>>(['totp'])const [selected2faMethod, setSelected2faMethod] = useState<'totp' | 'passkey'>('totp')+ const conditionalPasskeyAbortRef = useRef<AbortController | null>(null)++ const localAuthEnabled = resolveLocalAuthEnabled(oidcConfig, oidcConfigFailed)+ const oidcEnabled = oidcConfig?.enabled === true+ const authConfigLoading = oidcConfig === null && !oidcConfigFailed+ const noAuthMethodConfigured = oidcConfig !== null && !localAuthEnabled && !oidcEnabled+ const showPasskeyLogin = localAuthEnabled && passkeySupported+ const showAuthDivider = localAuthEnabled && (showPasskeyLogin || oidcEnabled)useEffect(() => {setPasskeySupported(isPasskeySupported())@@ -94,8 +108,68 @@ export default function LoginPage() {}}, [navigate, oidcConfig, oidcConfigFailed, token])+ useEffect(() => {+ if (+ token ||+ requires2fa ||+ authConfigLoading ||+ !localAuthEnabled ||+ !passkeySupported ||+ isLoading ||+ isPasskeyLoading+ ) return++ const abortController = new AbortController()+ conditionalPasskeyAbortRef.current?.abort()+ conditionalPasskeyAbortRef.current = abortController++ const authenticateConditionally = async () => {+ if (!await isConditionalPasskeySupported() || abortController.signal.aborted) return++ try {+ // An account-less request lets the browser discover eligible passkeys+ // and offer them alongside saved usernames in the email field.+ const options = await authApi.passkeyAuthenticationOptions()+ if (abortController.signal.aborted) return++ const credential = await startConditionalPasskeyAuthentication(+ options.options,+ abortController.signal,+ )+ const result = await authApi.verifyPasskeyAuthentication(options.challenge_id, credential)+ if (abortController.signal.aborted) return++ loginWithToken(result.access_token)+ navigate('/')+ } catch {+ // Conditional UI is an enhancement. Unsupported providers, dismissal,+ // expiry, and cancellation leave the normal login methods untouched.+ }+ }++ void authenticateConditionally()++ return () => {+ abortController.abort()+ if (conditionalPasskeyAbortRef.current === abortController) {+ conditionalPasskeyAbortRef.current = null+ }+ }+ }, [+ authConfigLoading,+ isLoading,+ isPasskeyLoading,+ localAuthEnabled,+ loginWithToken,+ navigate,+ passkeySupported,+ requires2fa,+ token,+ ])+const handleSubmit = async (e: React.FormEvent) => {e.preventDefault()+ conditionalPasskeyAbortRef.current?.abort()setError('')setIsLoading(true)try {@@ -124,10 +198,12 @@ export default function LoginPage() {}const handleOIDCLogin = () => {+ conditionalPasskeyAbortRef.current?.abort()window.location.href = '/api/auth/oidc/login'}const handlePasskeyLogin = async () => {+ conditionalPasskeyAbortRef.current?.abort()setError('')setIsPasskeyLoading(true)try {@@ -208,13 +284,6 @@ export default function LoginPage() {}}- const localAuthEnabled = resolveLocalAuthEnabled(oidcConfig, oidcConfigFailed)- const oidcEnabled = oidcConfig?.enabled === true- const authConfigLoading = oidcConfig === null && !oidcConfigFailed- const noAuthMethodConfigured = oidcConfig !== null && !localAuthEnabled && !oidcEnabled- const showPasskeyLogin = localAuthEnabled && passkeySupported- const showAuthDivider = localAuthEnabled && (showPasskeyLogin || oidcEnabled)-if (requires2fa) {return (<div className="flex flex-col items-center justify-center min-h-screen bg-background px-4">@@ -359,6 +428,7 @@ export default function LoginPage() {value={email}onChange={(e) => setEmail(e.target.value)}placeholder="[email protected]"+ autoComplete="username webauthn"required/></div>@@ -369,6 +439,7 @@ export default function LoginPage() {type="password"value={password}onChange={(e) => setPassword(e.target.value)}+ autoComplete="current-password"required/></div>