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
+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>