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:
2026-09-04 19:34:53 +01:00
co-authored by Claude Sonnet 5
parent 7da881bb78
commit afdd53ec4c
22 changed files with 1366 additions and 22 deletions
+3
View File
@@ -2,6 +2,7 @@
import { computed } from 'vue'
import { RouterLink, RouterView, useRoute, useRouter } from 'vue-router'
import AppSidebar from './components/AppSidebar.vue'
import PasskeyNotice from './components/PasskeyNotice.vue'
import { useAuthStore } from './stores/auth'
import { useCardsStore } from './stores/cards'
import { useInboxStore } from './stores/inbox'
@@ -38,6 +39,8 @@ async function onLogout() {
</div>
</header>
<PasskeyNotice />
<div class="app__body">
<AppSidebar v-if="showSidebar" />
+46
View File
@@ -0,0 +1,46 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import { useAuthStore } from '../stores/auth'
const auth = useAuthStore()
const DISMISS_KEY = 'passkeyNoticeDismissedUntil'
const WEEK_MS = 7 * 24 * 60 * 60 * 1000
function readDismissedUntil(): number {
try {
return Number(localStorage.getItem(DISMISS_KEY) ?? 0)
} catch {
return 0
}
}
const dismissedUntil = ref(readDismissedUntil())
const visible = computed(
() => auth.isAuthenticated && auth.user?.has_passkey === false && Date.now() > dismissedUntil.value,
)
function dismiss() {
const until = Date.now() + WEEK_MS
dismissedUntil.value = until
try {
localStorage.setItem(DISMISS_KEY, String(until))
} catch {
/* storage unavailable -- the notice just won't stay dismissed across reloads */
}
}
</script>
<template>
<div v-if="visible" class="passkey-notice">
<p>
You don't have a passkey yet add one on your
<RouterLink to="/profile">profile</RouterLink> to sign in faster, without
waiting on an email.
</p>
<button type="button" class="passkey-notice__dismiss" aria-label="Dismiss" @click="dismiss">
&#x2715;
</button>
</div>
</template>
+119
View File
@@ -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) },
})
}
+7
View File
@@ -1,6 +1,7 @@
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { apiRequest, setAuthToken } from '../lib/api'
import { loginWithPasskey as loginWithPasskeyCeremony } from '../lib/webauthn'
import type { AuthResponse, User } from '../types'
const TOKEN_KEY = 'todo.token'
@@ -62,6 +63,11 @@ export const useAuthStore = defineStore('auth', () => {
)
}
/** Sign in with a passkey instead of a magic link. */
async function loginWithPasskey(): Promise<void> {
adopt(await loginWithPasskeyCeremony())
}
/** Request a deferred email change. Returns the pending address and cooldown. */
async function requestEmailChange(
email: string,
@@ -99,6 +105,7 @@ export const useAuthStore = defineStore('auth', () => {
fetchMe,
requestLoginLink,
verifyEmail,
loginWithPasskey,
requestEmailChange,
}
})
+103
View File
@@ -221,6 +221,109 @@ h1 {
font-size: 0.9rem;
}
.divider {
display: flex;
align-items: center;
gap: 0.75rem;
margin: 1.25rem 0;
color: var(--muted);
font-size: 0.85rem;
}
.divider::before,
.divider::after {
content: '';
flex: 1;
height: 1px;
background: var(--border);
}
/* --- top-of-page "add a passkey" notice, dismissible for a week -------- */
.passkey-notice {
display: flex;
align-items: center;
justify-content: center;
gap: 1rem;
padding: 0.6rem 1.25rem;
background: var(--warn-bg);
border-bottom: 1px solid var(--warn-border);
font-size: 0.9rem;
text-align: center;
}
.passkey-notice p {
margin: 0;
}
.passkey-notice__dismiss {
flex: none;
border: none;
background: none;
color: var(--muted);
cursor: pointer;
font-size: 0.9rem;
padding: 0.2rem 0.4rem;
border-radius: 6px;
}
.passkey-notice__dismiss:hover {
background: var(--bg);
color: var(--text);
}
/* --- passkey list (profile) -------------------------------------------- */
.passkeys {
list-style: none;
margin: 1rem 0;
padding: 0;
display: grid;
gap: 0.5rem;
}
.passkeys__item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
padding: 0.6rem 0.75rem;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg);
}
.passkeys__info {
display: flex;
flex-direction: column;
gap: 0.15rem;
min-width: 0;
}
.passkeys__label {
font-weight: 600;
}
.passkeys__meta {
font-size: 0.8rem;
}
.passkeys__remove {
flex: none;
border: none;
background: none;
color: var(--muted);
cursor: pointer;
font-size: 0.85rem;
padding: 0.3rem 0.5rem;
border-radius: 6px;
}
.passkeys__remove:hover {
color: var(--error);
background: var(--surface);
}
/* --- dashboard: grid of projects --------------------------------------- */
.dashboard__grid {
+9
View File
@@ -5,6 +5,8 @@ export interface User {
email_verified_at: string | null
/** A confirmed-but-not-yet-applied email change is waiting on this address. */
pending_email: string | null
/** Whether this user has at least one registered passkey. */
has_passkey: boolean
created_at: string | null
}
@@ -14,6 +16,13 @@ export interface AuthResponse {
expires_at: string
}
export interface Passkey {
id: number
label: string
created_at: string
last_used_at: string | null
}
export interface Project {
id: number
title: string
+37
View File
@@ -1,9 +1,13 @@
<script setup lang="ts">
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ApiError } from '../lib/api'
import { passkeysSupported } from '../lib/webauthn'
import { useAuthStore } from '../stores/auth'
const auth = useAuthStore()
const router = useRouter()
const route = useRoute()
const email = ref('')
const error = ref<ApiError | null>(null)
@@ -22,11 +26,44 @@ async function onSubmit() {
submitting.value = false
}
}
// --- passkey login -------------------------------------------------------
const passkeySupported = passkeysSupported()
const passkeySubmitting = ref(false)
const passkeyError = ref('')
async function onPasskeyLogin() {
passkeySubmitting.value = true
passkeyError.value = ''
try {
await auth.loginWithPasskey()
const redirect = typeof route.query.redirect === 'string' ? route.query.redirect : '/'
await router.push(redirect)
} catch (e) {
if (e instanceof DOMException && e.name === 'NotAllowedError') {
passkeyError.value = 'Cancelled.'
} else {
passkeyError.value = e instanceof ApiError ? e.message : 'Could not sign in with a passkey.'
}
} finally {
passkeySubmitting.value = false
}
}
</script>
<template>
<section class="card">
<h1>Log in</h1>
<template v-if="passkeySupported">
<button type="button" :disabled="passkeySubmitting" @click="onPasskeyLogin">
{{ passkeySubmitting ? 'Waiting for your passkey' : 'Log in with a passkey' }}
</button>
<p v-if="passkeyError" class="form-error">{{ passkeyError }}</p>
<div class="divider"><span>or</span></div>
</template>
<p class="muted">
Enter your email and we'll send you a link to sign in — no password
needed. New here? The same link creates your account.
+127 -2
View File
@@ -1,7 +1,9 @@
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { ApiError } from '../lib/api'
import { onBeforeUnmount, onMounted, ref } from 'vue'
import { ApiError, apiRequest } from '../lib/api'
import { passkeysSupported, registerPasskey } from '../lib/webauthn'
import { useAuthStore } from '../stores/auth'
import type { Passkey } from '../types'
const auth = useAuthStore()
@@ -41,6 +43,80 @@ async function onChangeEmail() {
changing.value = false
}
}
// --- passkeys ------------------------------------------------------------
const supported = passkeysSupported()
const passkeys = ref<Passkey[]>([])
const loadingPasskeys = ref(true)
const passkeysError = ref('')
const newLabel = ref(guessDeviceLabel())
const adding = ref(false)
const addError = ref('')
const removingId = ref<number | null>(null)
function guessDeviceLabel(): string {
const ua = typeof navigator === 'undefined' ? '' : navigator.userAgent
if (/iPhone/.test(ua)) return 'iPhone'
if (/iPad/.test(ua)) return 'iPad'
if (/Android/.test(ua)) return 'Android device'
if (/Macintosh/.test(ua)) return 'Mac'
if (/Windows/.test(ua)) return 'Windows PC'
if (/Linux/.test(ua)) return 'Linux PC'
return 'This device'
}
onMounted(loadPasskeys)
async function loadPasskeys() {
if (!supported) {
loadingPasskeys.value = false
return
}
loadingPasskeys.value = true
passkeysError.value = ''
try {
const { passkeys: fetched } = await apiRequest<{ passkeys: Passkey[] }>('/passkeys', { auth: true })
passkeys.value = fetched
} catch (e) {
passkeysError.value = e instanceof ApiError ? e.message : 'Could not load your passkeys.'
} finally {
loadingPasskeys.value = false
}
}
async function onAddPasskey() {
adding.value = true
addError.value = ''
try {
const passkey = await registerPasskey(newLabel.value.trim() || guessDeviceLabel())
passkeys.value.push(passkey)
newLabel.value = guessDeviceLabel()
await auth.fetchMe() // clears the "add a passkey" notice once there's one
} catch (e) {
if (e instanceof DOMException && e.name === 'NotAllowedError') {
addError.value = 'Cancelled.'
} else {
addError.value = e instanceof ApiError ? e.message : 'Could not add that passkey.'
}
} finally {
adding.value = false
}
}
async function onRemovePasskey(passkey: Passkey) {
removingId.value = passkey.id
passkeysError.value = ''
try {
await apiRequest(`/passkeys/${passkey.id}`, { method: 'DELETE', auth: true })
passkeys.value = passkeys.value.filter((p) => p.id !== passkey.id)
await auth.fetchMe() // the notice comes back if that was the last one
} catch (e) {
passkeysError.value = e instanceof ApiError ? e.message : 'Could not remove that passkey.'
} finally {
removingId.value = null
}
}
</script>
<template>
@@ -81,5 +157,54 @@ async function onChangeEmail() {
</button>
</form>
</section>
<section>
<h2>Passkeys</h2>
<template v-if="!supported">
<p class="muted">Passkeys aren't supported in this browser.</p>
</template>
<template v-else>
<p class="muted">
Sign in with your device's fingerprint, face, or PIN instead of an
email link. You can add more than one, e.g. for a phone and a laptop.
</p>
<p v-if="passkeysError" class="form-error">{{ passkeysError }}</p>
<p v-else-if="loadingPasskeys" class="muted">Loading…</p>
<p v-else-if="passkeys.length === 0" class="muted">No passkeys yet.</p>
<ul v-else class="passkeys">
<li v-for="passkey in passkeys" :key="passkey.id" class="passkeys__item">
<div class="passkeys__info">
<span class="passkeys__label">{{ passkey.label }}</span>
<span class="passkeys__meta muted">
{{ passkey.last_used_at ? `Last used ${new Date(passkey.last_used_at).toLocaleDateString()}` : 'Never used' }}
</span>
</div>
<button
type="button"
class="passkeys__remove"
:disabled="removingId === passkey.id"
@click="onRemovePasskey(passkey)"
>
{{ removingId === passkey.id ? 'Removing' : 'Remove' }}
</button>
</li>
</ul>
<form class="form form--new-card" @submit.prevent="onAddPasskey">
<label>
<span>Label</span>
<input v-model="newLabel" type="text" maxlength="100" />
</label>
<p v-if="addError" class="form-error">{{ addError }}</p>
<button type="submit" :disabled="adding">
{{ adding ? 'Waiting for your passkey' : 'Add a passkey' }}
</button>
</form>
</template>
</section>
</section>
</template>