feat(auth): add passkey sign-in and management

Sign in with Face ID, Touch ID, Windows Hello or a security key, keeping
email + password as the primary method.

- API: BetterAuth passkey plugin deriving rpID/origin from WEB_APP_URL
  (the browser origin), with residentKey "required" because sign-in is
  username-less. New Passkey model mapped to the passkeys table.
- Web: conditional UI in the email field plus an explicit "Entrar con
  passkey" button; cancelled ceremonies are ignored.
- Settings: create, rename and delete passkeys with TanStack Query.
- Pin @better-auth/passkey to 1.7.7: its peers lock better-call, so
  newer versions break the API.
This commit is contained in:
Jose Selesan
2026-10-29 11:37:38 -03:00
parent f3d9996b11
commit 7ed4d27844
17 changed files with 724 additions and 21 deletions

View File

@@ -1,6 +1,7 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { useState } from 'react'
import { FingerprintIcon } from 'lucide-react'
import { useCallback, useEffect, useRef, useState } from 'react'
import { useForm } from 'react-hook-form'
import { z } from 'zod'
@@ -10,7 +11,7 @@ import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Field, FieldError, FieldGroup, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { signIn } from '@/lib/auth-client'
import { authClient, signIn } from '@/lib/auth-client'
export const Route = createFileRoute('/(auth)/sign-in')({
validateSearch: (search: Record<string, unknown>): { redirect?: string } => ({
@@ -26,16 +27,69 @@ const signInSchema = z.object({
type SignInValues = z.infer<typeof signInSchema>
const PASSKEY_ERROR_MESSAGE = 'No pudimos iniciar tu sesión con passkey.'
/** The user dismissed the system sheet: not worth showing an error for. */
function isPasskeyCancellation(error: unknown) {
return (
typeof error === 'object' &&
error !== null &&
'code' in error &&
error.code === 'AUTH_CANCELLED'
)
}
function SignInPage() {
const navigate = useNavigate()
const { redirect } = Route.useSearch()
const [error, setError] = useState<string | null>(null)
const [passkeyPending, setPasskeyPending] = useState(false)
const conditionalUiStarted = useRef(false)
const supportsPasskeys = typeof window !== 'undefined' && 'PublicKeyCredential' in window
const form = useForm<SignInValues>({
resolver: zodResolver(signInSchema),
defaultValues: { email: '', password: '' },
})
const completeSignIn = useCallback(async () => {
if (redirect) {
window.location.assign(redirect)
return
}
await navigate({ to: '/' })
}, [navigate, redirect])
// Conditional UI: the browser offers the user's passkeys in the email field's
// autofill. Guarded with a ref because StrictMode mounts effects twice in dev
// and a second ceremony would abort the first one.
useEffect(() => {
if (conditionalUiStarted.current || !supportsPasskeys) return
if (typeof window.PublicKeyCredential.isConditionalMediationAvailable !== 'function') return
conditionalUiStarted.current = true
void (async () => {
if (!(await window.PublicKeyCredential.isConditionalMediationAvailable())) return
try {
const { error: passkeyError } = await authClient.signIn.passkey({ autoFill: true })
if (passkeyError) {
if (!isPasskeyCancellation(passkeyError)) {
setError(passkeyError.message ?? PASSKEY_ERROR_MESSAGE)
}
return
}
await completeSignIn()
} catch {
setError(PASSKEY_ERROR_MESSAGE)
}
})()
}, [completeSignIn, supportsPasskeys])
const onSubmit = form.handleSubmit(async (values) => {
setError(null)
@@ -46,14 +100,31 @@ function SignInPage() {
return
}
if (redirect) {
window.location.assign(redirect)
return
}
await navigate({ to: '/' })
await completeSignIn()
})
const onPasskeySignIn = async () => {
setError(null)
setPasskeyPending(true)
try {
const { error: passkeyError } = await authClient.signIn.passkey()
if (passkeyError) {
if (!isPasskeyCancellation(passkeyError)) {
setError(passkeyError.message ?? PASSKEY_ERROR_MESSAGE)
}
return
}
await completeSignIn()
} catch {
setError(PASSKEY_ERROR_MESSAGE)
} finally {
setPasskeyPending(false)
}
}
return (
<div className="flex min-h-svh flex-col items-center justify-center gap-6 p-6">
<AppBrand />
@@ -77,7 +148,9 @@ function SignInPage() {
<Input
id="email"
type="email"
autoComplete="email"
// `webauthn` lets the browser offer passkeys in autofill
// (conditional UI); `username` is what login forms use.
autoComplete="username webauthn"
placeholder="ada@ejemplo.com"
{...form.register('email')}
/>
@@ -107,11 +180,31 @@ function SignInPage() {
<FieldError errors={[form.formState.errors.password]} />
</Field>
<Button type="submit" disabled={form.formState.isSubmitting}>
<Button type="submit" disabled={form.formState.isSubmitting || passkeyPending}>
{form.formState.isSubmitting ? 'Iniciando sesión…' : 'Iniciar sesión'}
</Button>
</FieldGroup>
{supportsPasskeys && (
<>
<div className="flex items-center gap-3" aria-hidden>
<span className="bg-border h-px flex-1" />
<span className="text-muted-foreground text-xs uppercase">o</span>
<span className="bg-border h-px flex-1" />
</div>
<Button
type="button"
variant="outline"
onClick={onPasskeySignIn}
disabled={passkeyPending || form.formState.isSubmitting}
>
<FingerprintIcon />
{passkeyPending ? 'Esperando a tu passkey…' : 'Entrar con passkey'}
</Button>
</>
)}
<p className="text-muted-foreground text-center text-sm">
¿Todavía no tienes cuenta?{' '}
<Link