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>
211 lines
7.0 KiB
Vue
211 lines
7.0 KiB
Vue
<script setup lang="ts">
|
|
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()
|
|
|
|
const cooldown = ref(0)
|
|
let timer: ReturnType<typeof setInterval> | undefined
|
|
|
|
function startCooldown(seconds: number) {
|
|
cooldown.value = Math.max(0, Math.ceil(seconds))
|
|
clearInterval(timer)
|
|
timer = setInterval(() => {
|
|
cooldown.value -= 1
|
|
if (cooldown.value <= 0) clearInterval(timer)
|
|
}, 1000)
|
|
}
|
|
|
|
onBeforeUnmount(() => clearInterval(timer))
|
|
|
|
// --- change email ------------------------------------------------------
|
|
const newEmail = ref('')
|
|
const changing = ref(false)
|
|
const changeMessage = ref('')
|
|
const changeError = ref<ApiError | null>(null)
|
|
|
|
async function onChangeEmail() {
|
|
changing.value = true
|
|
changeMessage.value = ''
|
|
changeError.value = null
|
|
try {
|
|
const { pending_email, retry_after } = await auth.requestEmailChange(newEmail.value)
|
|
changeMessage.value = `Confirmation link sent to ${pending_email}. Your address changes once you open it.`
|
|
newEmail.value = ''
|
|
startCooldown(retry_after)
|
|
} catch (e) {
|
|
changeError.value = e instanceof ApiError ? e : new ApiError('Could not request the change.', 0)
|
|
if (e instanceof ApiError && e.status === 429) startCooldown(e.retryAfter ?? 60)
|
|
} finally {
|
|
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>
|
|
<section class="card">
|
|
<p><RouterLink to="/">← Dashboard</RouterLink></p>
|
|
<h1>Your profile</h1>
|
|
|
|
<p><strong>Email:</strong> {{ auth.user?.email }}</p>
|
|
|
|
<div v-if="auth.user?.pending_email" class="notice">
|
|
A change to <strong>{{ auth.user.pending_email }}</strong> is pending. Open the
|
|
link we sent to that address to complete it. The link expires 15 minutes
|
|
after it was sent.
|
|
</div>
|
|
|
|
<section>
|
|
<h2>Change email address</h2>
|
|
<p class="muted">
|
|
We'll email a confirmation link to the new address; the change only
|
|
takes effect once you open it.
|
|
</p>
|
|
<form class="form" @submit.prevent="onChangeEmail">
|
|
<label>
|
|
<span>New email</span>
|
|
<input v-model="newEmail" type="email" maxlength="255" required />
|
|
<small v-if="changeError?.fieldError('email')" class="field-error">
|
|
{{ changeError.fieldError('email') }}
|
|
</small>
|
|
</label>
|
|
|
|
<p v-if="changeError && Object.keys(changeError.details).length === 0" class="form-error">
|
|
{{ changeError.message }}
|
|
</p>
|
|
<p v-if="changeMessage" class="muted">{{ changeMessage }}</p>
|
|
|
|
<button type="submit" :disabled="changing || cooldown > 0">
|
|
{{ changing ? 'Sending…' : cooldown > 0 ? `Wait ${cooldown}s` : 'Send confirmation link' }}
|
|
</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>
|