/** * WebAuthn/Passkey Functions * * Uses ts-auth for native WebAuthn implementation (no external dependencies) */ import type { VerifiedRegistrationResponse } from '@stacksjs/ts-auth' import { Buffer } from 'node:buffer' import type { Insertable } from '@stacksjs/database/runtime' import { db, getDatabaseDialect, mutationCount, parseSqlDateTime, sqlDateTime } from '@stacksjs/database/runtime' import { User } from '@stacksjs/orm' type UserModel = NonNullable>> // Re-export WebAuthn functions from ts-auth export { generateRegistrationOptions, generateAuthenticationOptions, verifyRegistrationResponse, verifyAuthenticationResponse, // Browser-side functions (for client use) startRegistration, startAuthentication, browserSupportsWebAuthn, browserSupportsWebAuthnAutofill, platformAuthenticatorIsAvailable, } from '@stacksjs/ts-auth' // Re-export WebAuthn types from ts-auth export type { VerifiedRegistrationResponse, VerifiedAuthenticationResponse, RegistrationCredential, AuthenticationCredential, PublicKeyCredentialCreationOptions, PublicKeyCredentialRequestOptions, RegistrationOptions, AuthenticationOptions, } from '@stacksjs/ts-auth' /** * A credential descriptor as it crosses the wire. * * `ts-auth`'s `PublicKeyCredentialRequestOptions` describes the shape the * BROWSER wants: `id` as an ArrayBuffer. A server handing those options to a * client has to send JSON, and an ArrayBuffer serializes to `{}` - so ids * travel as the base64url strings the passkey rows already store, and the * client turns them back into buffers before calling `navigator.credentials`. * * The passkey actions were already written against these names; they simply * had nowhere to import them from, so the whole file typechecked as `any`. */ export interface PublicKeyCredentialDescriptorJSON { /** base64url, as stored in `passkeys.id`. */ id: string /** Required by the WebAuthn spec; the actions were omitting it. */ type: 'public-key' transports?: Array<'ble' | 'internal' | 'nfc' | 'usb' | 'hybrid'> } export interface PublicKeyCredentialRequestOptionsJSON { challenge: Uint8Array rpId?: string allowCredentials?: PublicKeyCredentialDescriptorJSON[] userVerification?: 'required' | 'preferred' | 'discouraged' timeout?: number } export interface PublicKeyCredentialCreationOptionsJSON { challenge: Uint8Array rp: { name: string, id?: string } user: { id: Uint8Array | string, name: string, displayName: string } pubKeyCredParams: Array<{ alg: number, type: 'public-key' }> timeout?: number attestation?: string authenticatorSelection?: { authenticatorAttachment?: 'platform' | 'cross-platform' requireResidentKey?: boolean residentKey?: 'discouraged' | 'preferred' | 'required' userVerification?: 'required' | 'preferred' | 'discouraged' } excludeCredentials?: PublicKeyCredentialDescriptorJSON[] } /** * Turn a user's stored passkeys into credential descriptors for the options a * server hands the browser. * * Both `GenerateRegistrationAction` (as `excludeCredentials`) and * `GenerateAuthenticationAction` (as `allowCredentials`) need the same three * facts: the stored base64url id, the `type: 'public-key'` the spec requires, * and the transports. Building it in one place is also where the * ArrayBuffer-vs-JSON boundary gets explained once rather than at each call. */ export function passkeyDescriptors( passkeys: readonly PasskeyAttribute[], ): PublicKeyCredentialDescriptorJSON[] { return passkeys.map(passkey => ({ id: passkey.id, type: 'public-key' as const, transports: parseTransports(passkey.transports), })) } /** `transports` is stored as a JSON array string; anything else means unknown. */ function parseTransports(stored: string | undefined): PublicKeyCredentialDescriptorJSON['transports'] { if (!stored) return undefined try { const parsed = JSON.parse(stored) return Array.isArray(parsed) && parsed.length ? parsed.filter(value => ['ble', 'internal', 'nfc', 'usb', 'hybrid'].includes(value)) : undefined } catch { return undefined } } type PasskeyInsertable = Insertable export interface PasskeyAttribute { id: string cred_public_key: string user_id: number webauthn_user_id: string counter: number credential_type: string device_type: string backup_eligible: boolean backup_status: boolean transports?: string created_at?: Date last_used_at: string | null } export async function getUserPasskeys(userId: number): Promise { const rows = await db.primary.selectFrom('passkeys').selectAll().where('user_id', '=', userId).execute() return rows as unknown as PasskeyAttribute[] } export async function getUserPasskey(userId: number, passkeyId: string): Promise { const row = await db.primary .selectFrom('passkeys') .selectAll() .where('id', '=', passkeyId) .where('user_id', '=', userId) .executeTakeFirst() return row as unknown as PasskeyAttribute | undefined } /** * Persist the post-verification authenticator counter and refresh the * passkey's last-used timestamp. WebAuthn's anti-cloning guarantee * depends on the relying party rejecting any authentication whose * `newCounter` is **not strictly greater** than the stored value — * authenticators monotonically increment their counter on every use, * so a counter that doesn't advance (or goes backwards) signals a * cloned or replayed credential. * * Returns `true` when the counter was updated successfully; `false` * when the new counter is not greater than the stored one (the * authentication MUST be rejected by the caller in that case). * stacksjs/stacks#1861 A-4. */ export async function updatePasskeyCounter( userId: number, passkeyId: string, newCounter: number, verifiedCredential?: Pick, ): Promise { if (!Number.isSafeInteger(newCounter) || newCounter < 0) return false // Authenticators that don't implement a counter (some platform // authenticators) always send 0 — accept those at face value as // long as the stored value is also 0. The strictly-greater check // applies only when the device claims a non-zero counter. const passkey = verifiedCredential ?? await getUserPasskey(userId, passkeyId) if (!passkey) return false const stored = Number(passkey.counter ?? 0) // Reject any counter that fails to advance — that is the clone/replay // signal. The ONLY exception is the genuine no-counter authenticator, // which reports 0 and whose stored value is therefore also 0. The old // `newCounter !== 0 && ...` form accepted an incoming 0 unconditionally, // so a cloned authenticator replaying counter 0 against a stored value of // (say) 50 passed the check AND reset the stored counter to 0, defeating // the anti-cloning backstop. See stacksjs/stacks#1985. if (newCounter <= stored && !(newCounter === 0 && stored === 0)) { return false } if (newCounter === 0) { // MySQL reports zero changed rows for repeated no-counter assertions in // the same second. Lock and verify existence instead of treating that // no-op as a failed claim or using emulated RETURNING as a CAS result. return db.transaction(async () => { let query = db.primary.selectFrom('passkeys') .selectAll() .where('id', '=', passkeyId) .where('user_id', '=', userId) .where('counter', '=', 0) .where('cred_public_key', '=', passkey.cred_public_key) // SQLite serializes its write transaction and has no FOR UPDATE. if (getDatabaseDialect() !== 'sqlite') query = query.lockForUpdate() const current = await query.executeTakeFirst() if (!current) return false await db.updateTable('passkeys') .set({ last_used_at: sqlDateTime() } as never) .where('id', '=', passkeyId) .where('user_id', '=', userId) .execute() return true }) } const claimed = await db .updateTable('passkeys') .set({ counter: newCounter, last_used_at: sqlDateTime() } as never) .where('id', '=', passkeyId) .where('user_id', '=', userId) .where('counter', '=', stored) .where('cred_public_key', '=', passkey.cred_public_key) .execute() return mutationCount(claimed) === 1 } export async function setCurrentRegistrationOptions( // Declared as what it reads rather than as the whole ORM model. The caller // holds an authenticated user, which is no longer a `UserModel` now that the // types package has stopped importing the ORM, and this only ever needed the // two columns it writes onto the passkey row. user: { id: number, email?: string }, verified: VerifiedRegistrationResponse, ): Promise { // WebAuthn registrations without a credential id or public key are // useless for future authentication — inserting `id: ''` would create // a "passkey" that nothing can ever match. Reject up front so the // caller sees a clear error instead of a soft-fail at next login. if (!verified.verified) throw new Error('[auth/passkey] Registration is not verified') const credentialId = verified.registrationInfo?.credential.id const credentialPublicKey = verified.registrationInfo?.credential.publicKey if (!credentialId) { throw new Error('[auth/passkey] WebAuthn registration response is missing credential.id') } if (!credentialPublicKey) { throw new Error('[auth/passkey] WebAuthn registration response is missing credential.publicKey') } const passkeyData: PasskeyInsertable = { id: credentialId, cred_public_key: JSON.stringify(Array.from(new Uint8Array(credentialPublicKey))), user_id: user.id as number, webauthn_user_id: user.email || '', counter: verified.registrationInfo?.credential.counter || 0, credential_type: verified.registrationInfo?.credentialType || '', device_type: verified.registrationInfo?.credentialDeviceType || '', backup_eligible: false, backup_status: verified.registrationInfo?.credentialBackedUp || false, transports: JSON.stringify(['internal']), last_used_at: sqlDateTime(), } await db.insertInto('passkeys').values(passkeyData).executeTakeFirstOrThrow() } // ============================================================================= // WebAuthn challenge persistence (stacksjs/stacks#1866) // ============================================================================= // // WebAuthn relying parties MUST verify the assertion's challenge // against a server-issued nonce. Previously Stacks returned the // challenge in `generateOptions` and trusted the client to echo it // back on verify — so any attacker who captured the assertion AND the // challenge could replay the response. Persisting the challenge // server-side and consuming it on verify closes that gap. // // The default TTL is 5 minutes — long enough for slow biometric // flows, short enough to bound the replay window. Override per-call // via the `ttlSeconds` parameter. export type WebAuthnChallengePurpose = 'registration' | 'authentication' const DEFAULT_CHALLENGE_TTL_SECONDS = 5 * 60 /** * Persist a server-issued WebAuthn challenge for the given user + * purpose. Deletes any prior challenge for the same (user, purpose) * pair so a fresh `generateOptions` invalidates the previous one. * * The unique index on `(user_id, purpose)` enforces single-outstanding * at the DB layer; this delete makes the upsert safe even on installs * that ran an earlier auth:setup before the unique index existed. */ export async function storeWebAuthnChallenge( userId: number, challenge: string | Uint8Array, purpose: WebAuthnChallengePurpose, ttlSeconds: number = DEFAULT_CHALLENGE_TTL_SECONDS, ): Promise { const expiresAt = sqlDateTime(new Date(Date.now() + ttlSeconds * 1000)) const encodedChallenge = typeof challenge === 'string' ? challenge : Buffer.from(challenge).toString('base64url') await db.transaction(async () => { await db.deleteFrom('webauthn_challenges') .where('user_id', '=', userId).where('purpose', '=', purpose).execute() await db.insertInto('webauthn_challenges').values({ user_id: userId, challenge: encodedChallenge, purpose, expires_at: expiresAt, } as never).execute() // Keep the prior challenge if replacement fails, including silent trigger // rejection. Retain the legacy-schema path without requiring a new index. const stored = await db.primary.selectFrom('webauthn_challenges') .where('user_id', '=', userId).where('purpose', '=', purpose) .select('challenge').execute() if (stored.length !== 1 || stored[0]?.challenge !== encodedChallenge) throw new Error('[auth] WebAuthn challenge could not be stored.') }) } /** * Read + delete (single-use) a WebAuthn challenge for the given user * + purpose. Returns `null` when no outstanding challenge exists or * when the stored challenge has expired. * * Single-use semantics matter: a successful verify must invalidate * the challenge so a captured assertion can't be replayed even within * the TTL window. Callers MUST treat a `null` return as a verification * failure. */ export async function consumeWebAuthnChallenge( userId: number, purpose: WebAuthnChallengePurpose, ): Promise { const row = await db.primary .selectFrom('webauthn_challenges') .where('user_id', '=', userId) .where('purpose', '=', purpose) .select(['challenge', 'expires_at']) .executeTakeFirst() if (!row) return null // Delete BEFORE checking expiry so an expired row doesn't linger // and consume the unique slot for the next legitimate generate. const claimed = await db .deleteFrom('webauthn_challenges') .where('user_id', '=', userId) .where('purpose', '=', purpose) .where('challenge', '=', row.challenge) .where('expires_at', '=', row.expires_at) .execute() if (mutationCount(claimed) !== 1) return null const expiresAt = parseSqlDateTime(row.expires_at)?.getTime() ?? 0 if (Date.now() >= expiresAt) return null return Buffer.from(String(row.challenge), 'base64url') }