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

@@ -13,6 +13,7 @@
"test": "vitest run --passWithNoTests"
},
"dependencies": {
"@better-auth/passkey": "1.7.7",
"@fontsource-variable/geist": "^5.3.0",
"@hookform/resolvers": "^5.9.1",
"@superlist/shared": "workspace:*",

View File

@@ -0,0 +1,336 @@
import {
FingerprintIcon,
KeyRoundIcon,
MoreHorizontalIcon,
PencilIcon,
PlusIcon,
Trash2Icon,
} from 'lucide-react'
import { type FormEvent, useState } from 'react'
import { toast } from 'sonner'
import { Badge } from '@/components/ui/badge'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu'
import { Field, FieldDescription, FieldLabel } from '@/components/ui/field'
import { Input } from '@/components/ui/input'
import { Skeleton } from '@/components/ui/skeleton'
import {
type Passkey,
useAddPasskey,
useDeletePasskey,
usePasskeys,
useUpdatePasskey,
} from '@/hooks/use-passkeys'
const DEFAULT_NAME = 'Este dispositivo'
const createdOnFormat = new Intl.DateTimeFormat('es', { dateStyle: 'medium' })
function passkeyLabel(passkey: Passkey) {
return passkey.name?.trim() || 'Passkey sin nombre'
}
function passkeyDetails(passkey: Passkey) {
const created = passkey.createdAt ? new Date(passkey.createdAt) : null
if (!created || Number.isNaN(created.getTime())) return 'Passkey de acceso'
return `Creada el ${createdOnFormat.format(created)}`
}
export function PasskeysCard() {
const supportsPasskeys = typeof window !== 'undefined' && 'PublicKeyCredential' in window
const passkeys = usePasskeys()
const addPasskey = useAddPasskey()
const updatePasskey = useUpdatePasskey()
const deletePasskey = useDeletePasskey()
const [addOpen, setAddOpen] = useState(false)
const [newName, setNewName] = useState(DEFAULT_NAME)
const [renaming, setRenaming] = useState<Passkey | null>(null)
const [renameName, setRenameName] = useState('')
const [deleting, setDeleting] = useState<Passkey | null>(null)
const openAdd = () => {
setNewName(DEFAULT_NAME)
setAddOpen(true)
}
const openRename = (passkey: Passkey) => {
setRenameName(passkeyLabel(passkey))
setRenaming(passkey)
}
const onAdd = async (event: FormEvent) => {
event.preventDefault()
try {
await addPasskey.mutateAsync(newName.trim() || DEFAULT_NAME)
setAddOpen(false)
toast.success('Passkey creada.')
} catch (error) {
toast.error(error instanceof Error ? error.message : 'No pudimos crear la passkey.')
}
}
const onRename = async (event: FormEvent) => {
event.preventDefault()
if (!renaming) return
try {
await updatePasskey.mutateAsync({ id: renaming.id, name: renameName.trim() || DEFAULT_NAME })
setRenaming(null)
toast.success('Passkey renombrada.')
} catch (error) {
toast.error(error instanceof Error ? error.message : 'No pudimos renombrar la passkey.')
}
}
const onDelete = async () => {
if (!deleting) return
try {
await deletePasskey.mutateAsync(deleting.id)
setDeleting(null)
toast.success('Passkey eliminada.')
} catch (error) {
toast.error(error instanceof Error ? error.message : 'No pudimos eliminar la passkey.')
}
}
return (
<Card>
<CardHeader>
<div className="flex items-start justify-between gap-3">
<div className="space-y-1.5">
<CardTitle>Passkeys</CardTitle>
<CardDescription>
Entra con Face ID, Touch ID o Windows Hello, sin escribir tu contraseña.
</CardDescription>
</div>
{supportsPasskeys && (
<Button variant="outline" size="sm" onClick={openAdd} disabled={addPasskey.isPending}>
<PlusIcon />
Añadir
</Button>
)}
</div>
</CardHeader>
<CardContent>
{!supportsPasskeys ? (
<p className="text-muted-foreground text-sm">
Este navegador no admite passkeys. Prueba con uno más reciente o con la app instalada.
</p>
) : passkeys.isPending ? (
<div className="space-y-2">
<Skeleton className="h-14 w-full" />
<Skeleton className="h-14 w-full" />
</div>
) : passkeys.isError ? (
<div className="flex flex-col items-start gap-2">
<p className="text-destructive text-sm">
{passkeys.error instanceof Error
? passkeys.error.message
: 'No pudimos cargar tus passkeys.'}
</p>
<Button variant="outline" size="sm" onClick={() => void passkeys.refetch()}>
Reintentar
</Button>
</div>
) : passkeys.data.length === 0 ? (
<div className="flex flex-col items-center gap-2 rounded-lg border border-dashed p-6 text-center">
<KeyRoundIcon className="text-muted-foreground size-6" />
<p className="text-sm font-medium">Todavía no tienes passkeys</p>
<p className="text-muted-foreground text-sm">
Añade una para entrar sin escribir tu contraseña.
</p>
</div>
) : (
<ul className="divide-y rounded-lg border">
{passkeys.data.map((passkey) => (
<li key={passkey.id} className="flex items-center gap-3 px-3 py-3">
<span className="bg-muted flex size-9 shrink-0 items-center justify-center rounded-full">
<FingerprintIcon className="size-4" />
</span>
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2">
<p className="truncate text-sm font-medium">{passkeyLabel(passkey)}</p>
{passkey.backedUp && (
<Badge variant="secondary" className="shrink-0">
Sincronizada
</Badge>
)}
</div>
<p className="text-muted-foreground truncate text-xs">
{passkeyDetails(passkey)}
</p>
</div>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="icon"
aria-label={`Acciones de ${passkeyLabel(passkey)}`}
>
<MoreHorizontalIcon />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40">
<DropdownMenuItem onClick={() => openRename(passkey)}>
<PencilIcon />
Renombrar
</DropdownMenuItem>
<DropdownMenuItem variant="destructive" onClick={() => setDeleting(passkey)}>
<Trash2Icon />
Eliminar
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</li>
))}
</ul>
)}
</CardContent>
<Dialog
open={addOpen}
onOpenChange={(open) => {
if (!addPasskey.isPending) setAddOpen(open)
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Añadir passkey</DialogTitle>
<DialogDescription>
Tu dispositivo te pedirá Face ID, Touch ID, Windows Hello o tu llave de seguridad.
</DialogDescription>
</DialogHeader>
<form onSubmit={onAdd} className="flex flex-col gap-4">
<Field>
<FieldLabel htmlFor="new-passkey-name">Nombre</FieldLabel>
<Input
id="new-passkey-name"
value={newName}
onChange={(event) => setNewName(event.target.value)}
maxLength={60}
autoFocus
/>
<FieldDescription>Te ayuda a reconocerla si añades más de una.</FieldDescription>
</Field>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setAddOpen(false)}
disabled={addPasskey.isPending}
>
Cancelar
</Button>
<Button type="submit" disabled={addPasskey.isPending}>
{addPasskey.isPending ? 'Creando…' : 'Crear passkey'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<Dialog
open={renaming !== null}
onOpenChange={(open) => {
if (!open && !updatePasskey.isPending) setRenaming(null)
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Renombrar passkey</DialogTitle>
<DialogDescription>
Elige un nombre que te ayude a reconocer este dispositivo o llave.
</DialogDescription>
</DialogHeader>
<form onSubmit={onRename} className="flex flex-col gap-4">
<Field>
<FieldLabel htmlFor="rename-passkey">Nombre</FieldLabel>
<Input
id="rename-passkey"
value={renameName}
onChange={(event) => setRenameName(event.target.value)}
maxLength={60}
autoFocus
/>
</Field>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setRenaming(null)}
disabled={updatePasskey.isPending}
>
Cancelar
</Button>
<Button type="submit" disabled={updatePasskey.isPending}>
{updatePasskey.isPending ? 'Guardando…' : 'Guardar'}
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
<Dialog
open={deleting !== null}
onOpenChange={(open) => {
if (!open && !deletePasskey.isPending) setDeleting(null)
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>Eliminar passkey</DialogTitle>
<DialogDescription>
{deleting
? `«${passkeyLabel(deleting)}» dejará de servir para iniciar sesión.`
: 'Esta passkey dejará de servir para iniciar sesión.'}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
type="button"
variant="outline"
onClick={() => setDeleting(null)}
disabled={deletePasskey.isPending}
>
Cancelar
</Button>
<Button
type="button"
variant="destructive"
onClick={() => void onDelete()}
disabled={deletePasskey.isPending}
>
{deletePasskey.isPending ? 'Eliminando…' : 'Eliminar passkey'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</Card>
)
}

View File

@@ -0,0 +1,76 @@
import { queryOptions, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { authClient } from '@/lib/auth-client'
export type Passkey = NonNullable<
Awaited<ReturnType<typeof authClient.passkey.listUserPasskeys>>['data']
>[number]
const PASSKEYS_QUERY_KEY = ['passkeys'] as const
export const passkeysQueryOptions = () =>
queryOptions({
queryKey: PASSKEYS_QUERY_KEY,
queryFn: async () => {
const { data, error } = await authClient.passkey.listUserPasskeys()
if (error) throw new Error(error.message ?? 'No pudimos cargar tus passkeys.')
return data ?? []
},
})
export function usePasskeys() {
return useQuery(passkeysQueryOptions())
}
function toError(error: { message?: string } | null, fallback: string) {
return new Error(error?.message ?? fallback)
}
export function useAddPasskey() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (name: string) => {
const { data, error } = await authClient.passkey.addPasskey({ name })
if (error) throw toError(error, 'No pudimos crear la passkey.')
return data
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: PASSKEYS_QUERY_KEY })
},
})
}
export function useUpdatePasskey() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async ({ id, name }: { id: string; name: string }) => {
const { error } = await authClient.passkey.updatePasskey({ id, name })
if (error) throw toError(error, 'No pudimos renombrar la passkey.')
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: PASSKEYS_QUERY_KEY })
},
})
}
export function useDeletePasskey() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: async (id: string) => {
const { error } = await authClient.passkey.deletePasskey({ id })
if (error) throw toError(error, 'No pudimos eliminar la passkey.')
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: PASSKEYS_QUERY_KEY })
},
})
}

View File

@@ -1,3 +1,4 @@
import { passkeyClient } from '@better-auth/passkey/client'
import { emailOTPClient } from 'better-auth/client/plugins'
import { createAuthClient } from 'better-auth/react'
@@ -8,7 +9,7 @@ import { createAuthClient } from 'better-auth/react'
*/
export const authClient = createAuthClient({
baseURL: import.meta.env.VITE_API_URL || window.location.origin,
plugins: [emailOTPClient()],
plugins: [emailOTPClient(), passkeyClient()],
})
export const { signIn, signUp, signOut, useSession, emailOtp } = authClient

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

View File

@@ -4,6 +4,7 @@ import { MonitorIcon, MoonIcon, SunIcon } from 'lucide-react'
import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { z } from 'zod'
import { PasskeysCard } from '@/components/settings/passkeys-card'
import { type Theme, useTheme } from '@/components/theme-provider'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
@@ -22,6 +23,7 @@ function SettingsPage() {
return (
<div className="mx-auto grid w-full max-w-2xl gap-4 md:gap-6">
<ProfileCard />
<PasskeysCard />
<AppearanceCard />
<Card>