Add passkeys (WebAuthn): register from the profile, log in without email
New library dependency: lbuchs/webauthn (^2.2, MIT, zero transitive deps
beyond PHP+OpenSSL+Mbstring, both already required). 'none' attestation --
this only confirms "the same device that registered", not hardware
provenance, the standard trust model for a public site's own passkey login.
Backend
- migrations/010: `passkeys` (one row per registered credential: owner,
credential_id, public_key, sign_count, label) and `webauthn_challenges`
(short-lived, single-use, bridging each ceremony's "options" and "verify"
calls -- user_id set for a registration, null for a login since who's
signing in isn't known until the credential comes back).
- Config: WEBAUTHN_RP_ID (defaults to APP_URL's host) and WEBAUTHN_RP_NAME.
- PasskeyRepository, WebAuthnChallengeRepository, PasskeyController:
GET/POST /api/passkeys, POST /api/passkeys/options, DELETE
/api/passkeys/{id} (all auth), plus the public POST /api/auth/passkey/
options and /verify for login. Registration always asks for a
discoverable, user-verified credential -- what makes login usernameless:
the browser offers whatever passkeys it has for the site, no email first.
- SessionPayload now also exposes `has_passkey` on every user object
(PasskeyRepository::countForUser() > 0), reused by both the profile page
and the dismissible notice.
- PasskeyTest: auth guards, options response shape, challenge single-use/
expiry/purpose/cross-user rules, malformed-input handling, list/remove
CRUD (seeded rows) -- everything short of a real signature, which isn't
practical from PHPUnit. 73 tests pass.
Frontend
- lib/webauthn.ts: base64url <-> ArrayBuffer conversion and the two
ceremonies (registerPasskey, loginWithPasskey), matching the API's wire
format exactly.
- ProfileView: a Passkeys section -- list with Remove buttons, an "Add a
passkey" form (label pre-filled from a UA guess).
- LoginView: a "Log in with a passkey" button above the email form, shown
only when the browser supports WebAuthn.
- PasskeyNotice.vue: dismissible banner across the top of the page
(`user.has_passkey === false`); dismissal is a week-long localStorage
timestamp.
Verified against the rebuilt container using a Chrome DevTools Protocol
*virtual authenticator* (real ECDSA signing, no human interaction) end to
end: notice shown -> register a passkey -> notice gone (same page and after
navigating) -> log out -> "Log in with a passkey" with no email typed ->
correct account, notice still gone -> remove the passkey -> notice back ->
dismiss -> stays hidden for ~7 days across pages. Along the way, caught and
fixed a real bug: AuthenticatorData::getCredentialId() returns a raw binary
string, not a ByteBuffer like most of this library's other binary fields --
bin2hex() it directly rather than calling ->getHex().
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,119 @@
|
||||
import { apiRequest } from './api'
|
||||
import type { AuthResponse, Passkey } from '../types'
|
||||
|
||||
/** Loosely-typed shape of the `publicKey` options the API sends -- binary
|
||||
* fields (challenge, ids) travel as base64url strings over JSON. */
|
||||
interface RawPublicKey {
|
||||
[key: string]: unknown
|
||||
challenge: string
|
||||
user?: { id: string; [key: string]: unknown }
|
||||
excludeCredentials?: Array<{ id: string; [key: string]: unknown }>
|
||||
allowCredentials?: Array<{ id: string; [key: string]: unknown }>
|
||||
}
|
||||
|
||||
export function passkeysSupported(): boolean {
|
||||
return typeof window !== 'undefined' && typeof window.PublicKeyCredential !== 'undefined'
|
||||
}
|
||||
|
||||
function base64urlToBuffer(base64url: string): ArrayBuffer {
|
||||
const padded = base64url.replace(/-/g, '+').replace(/_/g, '/').padEnd(Math.ceil(base64url.length / 4) * 4, '=')
|
||||
const binary = atob(padded)
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
|
||||
return bytes.buffer
|
||||
}
|
||||
|
||||
function bufferToBase64url(buffer: ArrayBuffer): string {
|
||||
let binary = ''
|
||||
for (const byte of new Uint8Array(buffer)) binary += String.fromCharCode(byte)
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
function decodeCreationOptions(publicKey: RawPublicKey): PublicKeyCredentialCreationOptions {
|
||||
return {
|
||||
...publicKey,
|
||||
challenge: base64urlToBuffer(publicKey.challenge),
|
||||
user: {
|
||||
...publicKey.user,
|
||||
id: base64urlToBuffer(publicKey.user!.id),
|
||||
},
|
||||
excludeCredentials: (publicKey.excludeCredentials ?? []).map((c) => ({
|
||||
...c,
|
||||
id: base64urlToBuffer(c.id),
|
||||
})),
|
||||
} as PublicKeyCredentialCreationOptions
|
||||
}
|
||||
|
||||
function decodeRequestOptions(publicKey: RawPublicKey): PublicKeyCredentialRequestOptions {
|
||||
return {
|
||||
...publicKey,
|
||||
challenge: base64urlToBuffer(publicKey.challenge),
|
||||
allowCredentials: (publicKey.allowCredentials ?? []).map((c) => ({
|
||||
...c,
|
||||
id: base64urlToBuffer(c.id),
|
||||
})),
|
||||
} as PublicKeyCredentialRequestOptions
|
||||
}
|
||||
|
||||
function serializeCreatedCredential(credential: PublicKeyCredential): unknown {
|
||||
const response = credential.response as AuthenticatorAttestationResponse
|
||||
return {
|
||||
id: credential.id,
|
||||
response: {
|
||||
clientDataJSON: bufferToBase64url(response.clientDataJSON),
|
||||
attestationObject: bufferToBase64url(response.attestationObject),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function serializeAssertion(credential: PublicKeyCredential): unknown {
|
||||
const response = credential.response as AuthenticatorAssertionResponse
|
||||
return {
|
||||
id: credential.id,
|
||||
response: {
|
||||
clientDataJSON: bufferToBase64url(response.clientDataJSON),
|
||||
authenticatorData: bufferToBase64url(response.authenticatorData),
|
||||
signature: bufferToBase64url(response.signature),
|
||||
userHandle: response.userHandle ? bufferToBase64url(response.userHandle) : null,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Register a new passkey for the signed-in caller. */
|
||||
export async function registerPasskey(label: string): Promise<Passkey> {
|
||||
const { challenge_id, options } = await apiRequest<{
|
||||
challenge_id: number
|
||||
options: { publicKey: RawPublicKey }
|
||||
}>('/passkeys/options', { method: 'POST', auth: true })
|
||||
|
||||
const credential = await navigator.credentials.create({ publicKey: decodeCreationOptions(options.publicKey) })
|
||||
if (!(credential instanceof PublicKeyCredential)) {
|
||||
throw new Error('Could not create a passkey.')
|
||||
}
|
||||
|
||||
const { passkey } = await apiRequest<{ passkey: Passkey }>('/passkeys', {
|
||||
method: 'POST',
|
||||
auth: true,
|
||||
body: { challenge_id, credential: serializeCreatedCredential(credential), label },
|
||||
})
|
||||
|
||||
return passkey
|
||||
}
|
||||
|
||||
/** Sign in with a passkey. No email needed -- the browser offers whatever it has stored for this site. */
|
||||
export async function loginWithPasskey(): Promise<AuthResponse> {
|
||||
const { challenge_id, options } = await apiRequest<{
|
||||
challenge_id: number
|
||||
options: { publicKey: RawPublicKey }
|
||||
}>('/auth/passkey/options', { method: 'POST' })
|
||||
|
||||
const credential = await navigator.credentials.get({ publicKey: decodeRequestOptions(options.publicKey) })
|
||||
if (!(credential instanceof PublicKeyCredential)) {
|
||||
throw new Error('Could not sign in with that passkey.')
|
||||
}
|
||||
|
||||
return apiRequest<AuthResponse>('/auth/passkey/verify', {
|
||||
method: 'POST',
|
||||
body: { challenge_id, credential: serializeAssertion(credential) },
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user