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:
@@ -10,7 +10,9 @@ NODE_ENV="development"
|
||||
# RESEND_API_KEY="re_xxxxxxxx"
|
||||
# From address for outgoing email (must be a verified Resend sender)
|
||||
# MAIL_FROM="Superlist <invitaciones@superlist.app>"
|
||||
# Public URL of the web app, used to build the accept-invitation links
|
||||
# Public URL of the web app. Used to build invitation links and as the WebAuthn
|
||||
# relying-party origin for passkeys (no trailing slash), so it must be the exact
|
||||
# public origin users open in the browser.
|
||||
WEB_APP_URL="http://localhost:7153"
|
||||
# Dictation: AI Studio (Gemini API) key, backend only. NEVER prefix it with VITE_
|
||||
# or Vite would put it in the browser bundle. Without it, dictated text is split
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"db:studio": "prisma studio"
|
||||
},
|
||||
"dependencies": {
|
||||
"@better-auth/passkey": "1.7.7",
|
||||
"@hono/zod-validator": "^0.9.1",
|
||||
"@prisma/adapter-pg": "^7.10.0",
|
||||
"@prisma/client": "^7.10.0",
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
-- CreateTable
|
||||
CREATE TABLE "passkeys" (
|
||||
"id" TEXT NOT NULL,
|
||||
"name" TEXT,
|
||||
"public_key" TEXT NOT NULL,
|
||||
"user_id" TEXT NOT NULL,
|
||||
"credential_id" TEXT NOT NULL,
|
||||
"counter" INTEGER NOT NULL,
|
||||
"device_type" TEXT NOT NULL,
|
||||
"backed_up" BOOLEAN NOT NULL,
|
||||
"transports" TEXT,
|
||||
"created_at" TIMESTAMP(3) DEFAULT CURRENT_TIMESTAMP,
|
||||
"aaguid" TEXT,
|
||||
|
||||
CONSTRAINT "passkeys_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "passkeys_user_id_idx" ON "passkeys"("user_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "passkeys_credential_id_idx" ON "passkeys"("credential_id");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "passkeys" ADD CONSTRAINT "passkeys_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -34,6 +34,7 @@ model User {
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
sessions Session[]
|
||||
accounts Account[]
|
||||
passkeys Passkey[]
|
||||
ownedLists ShoppingList[] @relation("ListOwner")
|
||||
memberships ShoppingListMember[]
|
||||
invitations ShoppingListInvitation[] @relation("InvitedBy")
|
||||
@@ -90,6 +91,29 @@ model Verification {
|
||||
@@map("verifications")
|
||||
}
|
||||
|
||||
// WebAuthn credentials registered through the BetterAuth passkey plugin.
|
||||
// `credentialID` is the raw credential id and `publicKey` the stored public key;
|
||||
// the plugin reads and writes these rows directly, so keep the column names it
|
||||
// expects (mapped to snake_case like the rest of the schema).
|
||||
model Passkey {
|
||||
id String @id
|
||||
name String?
|
||||
publicKey String @map("public_key")
|
||||
userId String @map("user_id")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
credentialID String @map("credential_id")
|
||||
counter Int
|
||||
deviceType String @map("device_type")
|
||||
backedUp Boolean @map("backed_up")
|
||||
transports String?
|
||||
createdAt DateTime? @default(now()) @map("created_at")
|
||||
aaguid String?
|
||||
|
||||
@@index([userId])
|
||||
@@index([credentialID])
|
||||
@@map("passkeys")
|
||||
}
|
||||
|
||||
// --- Domain models ----------------------------------------------------------
|
||||
|
||||
/// A collaborative shopping list. Membership (and therefore access) lives in
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { passkey } from '@better-auth/passkey'
|
||||
import { betterAuth } from 'better-auth'
|
||||
import { prismaAdapter } from 'better-auth/adapters/prisma'
|
||||
import { emailOTP } from 'better-auth/plugins'
|
||||
@@ -6,6 +7,7 @@ import { passwordResetEmail } from '@/lib/emails/password-reset'
|
||||
import { acceptPendingInvitations, ensurePrimaryList } from '@/lib/list-membership'
|
||||
import { logger } from '@/lib/logger'
|
||||
import { sendEmail } from '@/lib/mailer'
|
||||
import { passkeyConfig } from '@/lib/passkey-config'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
|
||||
const trustedOrigins = (process.env.CORS_ORIGIN ?? '')
|
||||
@@ -57,6 +59,15 @@ export const auth = betterAuth({
|
||||
})
|
||||
},
|
||||
}),
|
||||
// Passkeys (Face ID, Touch ID, Windows Hello, security keys). Sign-in is
|
||||
// username-less, so credentials must be discoverable: `residentKey` is
|
||||
// required instead of the plugin's `preferred` default.
|
||||
passkey({
|
||||
...passkeyConfig,
|
||||
authenticatorSelection: {
|
||||
residentKey: 'required',
|
||||
},
|
||||
}),
|
||||
],
|
||||
databaseHooks: {
|
||||
user: {
|
||||
|
||||
37
apps/api/src/lib/passkey-config.test.ts
Normal file
37
apps/api/src/lib/passkey-config.test.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
|
||||
import { passkeyOrigins } from './passkey-config'
|
||||
|
||||
describe('passkeyOrigins', () => {
|
||||
test('keeps the development port in the origin but not in the RP ID', () => {
|
||||
expect(passkeyOrigins('http://localhost:7153')).toEqual({
|
||||
origin: 'http://localhost:7153',
|
||||
rpID: 'localhost',
|
||||
})
|
||||
})
|
||||
|
||||
test('normalises trailing slashes and paths to a bare origin', () => {
|
||||
expect(passkeyOrigins('https://superlist.app/')).toEqual({
|
||||
origin: 'https://superlist.app',
|
||||
rpID: 'superlist.app',
|
||||
})
|
||||
expect(passkeyOrigins('https://superlist.app/settings')).toEqual({
|
||||
origin: 'https://superlist.app',
|
||||
rpID: 'superlist.app',
|
||||
})
|
||||
})
|
||||
|
||||
test('uses a subdomain as the RP ID', () => {
|
||||
expect(passkeyOrigins('https://app.superlist.app')).toEqual({
|
||||
origin: 'https://app.superlist.app',
|
||||
rpID: 'app.superlist.app',
|
||||
})
|
||||
})
|
||||
|
||||
test('falls back to localhost when the URL is invalid', () => {
|
||||
expect(passkeyOrigins('not a url')).toEqual({
|
||||
origin: 'http://localhost:7153',
|
||||
rpID: 'localhost',
|
||||
})
|
||||
})
|
||||
})
|
||||
30
apps/api/src/lib/passkey-config.ts
Normal file
30
apps/api/src/lib/passkey-config.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { webAppUrl } from '@/lib/web-app-url'
|
||||
|
||||
const FALLBACK_ORIGIN = 'http://localhost:7153'
|
||||
|
||||
/**
|
||||
* WebAuthn ceremonies happen in the browser, so the relying party is the public
|
||||
* web origin, not the API one: in development the web runs on :7153 while the
|
||||
* API listens on :4100. `WEB_APP_URL` is already the canonical public URL of
|
||||
* the frontend (used for invitation links), so derive both values from it.
|
||||
*
|
||||
* The RP ID must be a registrable suffix of the origin and cannot include the
|
||||
* port; `new URL().hostname` does the right thing for both `localhost` and a
|
||||
* production domain.
|
||||
*/
|
||||
export function passkeyOrigins(webUrl: string) {
|
||||
let origin: string
|
||||
|
||||
try {
|
||||
origin = new URL(webUrl).origin
|
||||
} catch {
|
||||
origin = FALLBACK_ORIGIN
|
||||
}
|
||||
|
||||
return { origin, rpID: new URL(origin).hostname }
|
||||
}
|
||||
|
||||
export const passkeyConfig = {
|
||||
...passkeyOrigins(webAppUrl),
|
||||
rpName: 'Superlist',
|
||||
}
|
||||
@@ -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:*",
|
||||
|
||||
336
apps/web/src/components/settings/passkeys-card.tsx
Normal file
336
apps/web/src/components/settings/passkeys-card.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
76
apps/web/src/hooks/use-passkeys.ts
Normal file
76
apps/web/src/hooks/use-passkeys.ts
Normal 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 })
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in New Issue
Block a user