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
+274
View File
@@ -0,0 +1,274 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Auth\SessionPayload;
use App\Exception\ApiException;
use App\Repository\PasskeyRepository;
use App\Repository\UserRepository;
use App\Repository\WebAuthnChallengeRepository;
use lbuchs\WebAuthn\Binary\ByteBuffer;
use lbuchs\WebAuthn\WebAuthn;
use lbuchs\WebAuthn\WebAuthnException;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
/**
* Passkeys (WebAuthn): registering one or more per-device credentials while
* signed in, and using one to sign in instead of a magic link. Registration
* always asks for a discoverable ("resident key") credential with required
* user verification -- that combination is what makes it a passkey rather
* than a bare security key, and it's what lets login be usernameless: the
* browser prompts the user to pick from whatever passkeys it holds for this
* site, with no email typed first.
*/
final class PasskeyController extends Controller
{
private const LABEL_MAX = 100;
public function __construct(
private readonly WebAuthn $webAuthn,
private readonly PasskeyRepository $passkeys,
private readonly WebAuthnChallengeRepository $challenges,
private readonly UserRepository $users,
private readonly SessionPayload $session,
) {
}
/**
* GET /api/passkeys (auth)
*/
public function index(Request $request, Response $response): Response
{
$passkeys = $this->passkeys->allForUser($this->user($request)['id']);
return $this->json($response, ['passkeys' => array_map($this->present(...), $passkeys)]);
}
/**
* POST /api/passkeys/options (auth) -- a registration challenge.
*/
public function registerOptions(Request $request, Response $response): Response
{
$user = $this->user($request);
$excludeIds = array_map(
static fn (array $p): ByteBuffer => ByteBuffer::fromHex($p['credential_id']),
$this->passkeys->allForUser($user['id']),
);
$args = $this->webAuthn->getCreateArgs(
(string) $user['id'],
$user['email'],
$user['email'],
WebAuthnChallengeRepository::TTL_SECONDS,
true, // requireResidentKey: must be discoverable for usernameless login
'required', // requireUserVerification: what makes this a passkey
null,
$excludeIds,
);
$challengeId = $this->challenges->create($user['id'], 'register', $this->webAuthn->getChallenge()->getHex());
return $this->json($response, ['challenge_id' => $challengeId, 'options' => $args]);
}
/**
* POST /api/passkeys (auth) -- verify the browser's response and store the credential.
*/
public function store(Request $request, Response $response): Response
{
$userId = $this->user($request)['id'];
$body = $this->body($request);
$challengeId = $body['challenge_id'] ?? null;
if (!is_int($challengeId)) {
throw new ApiException('challenge_id is required.', 422);
}
$credential = $body['credential'] ?? null;
if (!is_array($credential)) {
throw new ApiException('credential is required.', 422);
}
$challenge = $this->challenges->consume($challengeId, 'register', $userId);
if ($challenge === null) {
throw new ApiException('This registration request has expired. Please try again.', 400);
}
try {
$data = $this->webAuthn->processCreate(
$this->decodeField($credential, 'clientDataJSON'),
$this->decodeField($credential, 'attestationObject'),
ByteBuffer::fromHex($challenge['challenge']),
true, // requireUserVerification
true, // requireUserPresent
false, // failIfRootMismatch -- we don't check attestation provenance
false, // requireCtsProfileMatch
);
} catch (WebAuthnException $e) {
throw new ApiException('Could not add that passkey: ' . $e->getMessage(), 400);
}
// AuthenticatorData::getCredentialId() returns a raw binary string, not
// a ByteBuffer (unlike most other binary fields in this library).
$credentialId = bin2hex($data->credentialId);
if ($this->passkeys->findByCredentialId($credentialId) !== null) {
throw new ApiException('That passkey is already registered.', 409);
}
$passkey = $this->passkeys->create(
$userId,
$credentialId,
$data->credentialPublicKey,
$data->signatureCounter ?? 0,
$this->labelFrom($body),
);
return $this->json($response, ['passkey' => $this->present($passkey)], 201);
}
/**
* DELETE /api/passkeys/{passkeyId} (auth)
*/
public function destroy(Request $request, Response $response, array $args): Response
{
$passkey = $this->passkeys->findOwnedBy((int) $args['passkeyId'], $this->user($request)['id']);
if ($passkey === null) {
throw new ApiException('Passkey not found.', 404);
}
$this->passkeys->delete($passkey['id']);
return $response->withStatus(204);
}
/**
* POST /api/auth/passkey/options (public) -- a discoverable login challenge.
* No email needed: allowCredentials is left empty, so the browser prompts
* the user to choose from any passkey it has stored for this site.
*/
public function loginOptions(Request $request, Response $response): Response
{
$args = $this->webAuthn->getGetArgs(
[],
WebAuthnChallengeRepository::TTL_SECONDS,
true,
true,
true,
true,
true,
'required',
);
$challengeId = $this->challenges->create(null, 'login', $this->webAuthn->getChallenge()->getHex());
return $this->json($response, ['challenge_id' => $challengeId, 'options' => $args]);
}
/**
* POST /api/auth/passkey/verify (public)
*/
public function loginVerify(Request $request, Response $response): Response
{
$body = $this->body($request);
$challengeId = $body['challenge_id'] ?? null;
if (!is_int($challengeId)) {
throw new ApiException('challenge_id is required.', 422);
}
$credential = $body['credential'] ?? null;
if (!is_array($credential) || !is_string($credential['id'] ?? null) || $credential['id'] === '') {
throw new ApiException('credential is required.', 422);
}
$challenge = $this->challenges->consume($challengeId, 'login');
if ($challenge === null) {
throw new ApiException('This sign-in request has expired. Please try again.', 400);
}
$credentialId = ByteBuffer::fromBase64Url($credential['id'])->getHex();
$passkey = $this->passkeys->findByCredentialId($credentialId);
if ($passkey === null) {
throw new ApiException('This passkey is not recognised.', 401);
}
$userHandle = $this->decodeField($credential, 'userHandle', required: false);
if ($userHandle !== null && $userHandle !== (string) $passkey['user_id']) {
throw new ApiException('This passkey is not recognised.', 401);
}
try {
$verified = $this->webAuthn->processGet(
$this->decodeField($credential, 'clientDataJSON'),
$this->decodeField($credential, 'authenticatorData'),
$this->decodeField($credential, 'signature'),
$passkey['public_key'],
ByteBuffer::fromHex($challenge['challenge']),
$passkey['sign_count'],
true, // requireUserVerification
);
} catch (WebAuthnException $e) {
throw new ApiException('Could not verify that passkey: ' . $e->getMessage(), 401);
}
if (!$verified) {
throw new ApiException('Could not verify that passkey.', 401);
}
$this->passkeys->markUsed($passkey['id'], $this->webAuthn->getSignatureCounter() ?? $passkey['sign_count']);
$user = $this->users->findById($passkey['user_id']);
if ($user === null) {
throw new ApiException('This account no longer exists.', 404);
}
return $this->json($response, $this->session->forUser($user));
}
/**
* @param array<string, mixed> $credential
*/
private function decodeField(array $credential, string $field, bool $required = true): ?string
{
$value = $credential['response'][$field] ?? null;
if (!is_string($value) || $value === '') {
if ($required) {
throw new ApiException("Malformed passkey response ({$field}).", 422);
}
return null;
}
return ByteBuffer::fromBase64Url($value)->getBinaryString();
}
/**
* @param array<string, mixed> $body
*/
private function labelFrom(array $body): string
{
$label = $body['label'] ?? null;
if (is_string($label) && trim($label) !== '') {
return mb_substr(trim($label), 0, self::LABEL_MAX);
}
return 'Passkey added ' . gmdate('j M Y');
}
/**
* @param array{id: int, label: string, created_at: string, last_used_at: string|null} $passkey
* @return array<string, mixed>
*/
private function present(array $passkey): array
{
return [
'id' => $passkey['id'],
'label' => $passkey['label'],
'created_at' => $passkey['created_at'],
'last_used_at' => $passkey['last_used_at'],
];
}
}