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',
|
||||
}
|
||||
Reference in New Issue
Block a user