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
+5 -3
View File
@@ -5,18 +5,19 @@ declare(strict_types=1);
namespace App\Auth;
use App\Repository\EmailVerificationRepository;
use App\Repository\PasskeyRepository;
/**
* Builds the JSON representation of a user and the session envelope returned
* when a magic link is opened (sign-up, sign-in, and email-change confirmation
* all go through the same verify-email endpoint). Shared so every entry point
* agrees on the shape.
* when a magic link (or a passkey) signs someone in. Shared so every entry
* point agrees on the shape.
*/
final class SessionPayload
{
public function __construct(
private readonly JwtService $jwt,
private readonly EmailVerificationRepository $tokens,
private readonly PasskeyRepository $passkeys,
) {
}
@@ -49,6 +50,7 @@ final class SessionPayload
'email_verified' => $verifiedAt !== null,
'email_verified_at' => $verifiedAt,
'pending_email' => $this->tokens->pendingEmailFor((int) $user['id']),
'has_passkey' => $this->passkeys->countForUser((int) $user['id']) > 0,
'created_at' => $user['created_at'] ?? null,
];
}
+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'],
];
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace App\Repository;
use PDO;
/**
* Data access for the `passkeys` table (registered WebAuthn credentials).
*
* @phpstan-type PasskeyRow array{
* id: int, user_id: int, credential_id: string, public_key: string,
* sign_count: int, label: string, created_at: string, last_used_at: string|null
* }
*/
final class PasskeyRepository
{
public function __construct(private readonly PDO $pdo)
{
}
/**
* @return PasskeyRow[]
*/
public function allForUser(int $userId): array
{
$stmt = $this->pdo->prepare(
'SELECT * FROM passkeys WHERE user_id = :user ORDER BY created_at ASC, id ASC'
);
$stmt->execute(['user' => $userId]);
return array_map($this->cast(...), $stmt->fetchAll());
}
public function countForUser(int $userId): int
{
$stmt = $this->pdo->prepare('SELECT COUNT(*) FROM passkeys WHERE user_id = :user');
$stmt->execute(['user' => $userId]);
return (int) $stmt->fetchColumn();
}
/**
* @return PasskeyRow|null
*/
public function findByCredentialId(string $credentialId): ?array
{
$stmt = $this->pdo->prepare('SELECT * FROM passkeys WHERE credential_id = :id');
$stmt->execute(['id' => $credentialId]);
$row = $stmt->fetch();
return $row === false ? null : $this->cast($row);
}
/**
* @return PasskeyRow|null
*/
public function findOwnedBy(int $id, int $userId): ?array
{
$stmt = $this->pdo->prepare('SELECT * FROM passkeys WHERE id = :id AND user_id = :user');
$stmt->execute(['id' => $id, 'user' => $userId]);
$row = $stmt->fetch();
return $row === false ? null : $this->cast($row);
}
/**
* @return PasskeyRow
*/
public function create(int $userId, string $credentialId, string $publicKey, int $signCount, string $label): array
{
$stmt = $this->pdo->prepare(
'INSERT INTO passkeys (user_id, credential_id, public_key, sign_count, label)
VALUES (:user, :credential_id, :public_key, :sign_count, :label)'
);
$stmt->execute([
'user' => $userId,
'credential_id' => $credentialId,
'public_key' => $publicKey,
'sign_count' => $signCount,
'label' => $label,
]);
/** @var PasskeyRow $passkey */
$passkey = $this->findByCredentialId($credentialId);
return $passkey;
}
/** Record a successful login: bump the signature counter and last-used timestamp. */
public function markUsed(int $id, int $signCount): void
{
$this->pdo->prepare(
"UPDATE passkeys SET sign_count = :count, last_used_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = :id"
)->execute(['count' => $signCount, 'id' => $id]);
}
public function delete(int $id): void
{
$this->pdo->prepare('DELETE FROM passkeys WHERE id = :id')->execute(['id' => $id]);
}
/**
* @param array<string, mixed> $row
* @return PasskeyRow
*/
private function cast(array $row): array
{
$row['id'] = (int) $row['id'];
$row['user_id'] = (int) $row['user_id'];
$row['sign_count'] = (int) $row['sign_count'];
/** @var PasskeyRow $row */
return $row;
}
}
@@ -0,0 +1,84 @@
<?php
declare(strict_types=1);
namespace App\Repository;
use PDO;
/**
* Short-lived, single-use challenges bridging a WebAuthn ceremony's "options"
* and "verify" steps (see PasskeyController). A registration challenge is
* tied to the signed-in caller; a login challenge has no user_id, since who's
* logging in isn't known until the credential comes back.
*
* @phpstan-type ChallengeRow array{
* id: int, user_id: int|null, purpose: string, challenge: string,
* expires_at: string, consumed_at: string|null
* }
*/
final class WebAuthnChallengeRepository
{
public const TTL_SECONDS = 300; // 5 minutes
public function __construct(private readonly PDO $pdo)
{
}
public function create(?int $userId, string $purpose, string $challengeHex): int
{
$expiresAt = gmdate('Y-m-d\TH:i:s\Z', time() + self::TTL_SECONDS);
$stmt = $this->pdo->prepare(
'INSERT INTO webauthn_challenges (user_id, purpose, challenge, expires_at)
VALUES (:user, :purpose, :challenge, :expires_at)'
);
$stmt->execute([
'user' => $userId,
'purpose' => $purpose,
'challenge' => $challengeHex,
'expires_at' => $expiresAt,
]);
return (int) $this->pdo->lastInsertId();
}
/**
* Atomically consume a challenge: valid, right purpose, right owner (when
* given), not expired, not already used. Returns null if any of that
* fails -- the caller should treat that as an invalid/expired request.
*
* @return ChallengeRow|null
*/
public function consume(int $id, string $purpose, ?int $expectedUserId = null): ?array
{
$stmt = $this->pdo->prepare('SELECT * FROM webauthn_challenges WHERE id = :id');
$stmt->execute(['id' => $id]);
$row = $stmt->fetch();
if ($row === false
|| $row['purpose'] !== $purpose
|| $row['consumed_at'] !== null
|| strtotime($row['expires_at']) < time()
|| ($expectedUserId !== null && (int) $row['user_id'] !== $expectedUserId)
) {
return null;
}
$update = $this->pdo->prepare(
"UPDATE webauthn_challenges SET consumed_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
WHERE id = :id AND consumed_at IS NULL"
);
$update->execute(['id' => $id]);
if ($update->rowCount() === 0) {
return null; // lost a race with a concurrent consume
}
$row['id'] = (int) $row['id'];
$row['user_id'] = $row['user_id'] === null ? null : (int) $row['user_id'];
/** @var ChallengeRow $row */
return $row;
}
}
+21 -1
View File
@@ -19,6 +19,10 @@ final class Config
public readonly bool $allowRegistration,
/** Base URL of the frontend, used to build magic links. */
public readonly string $appUrl,
/** WebAuthn relying party ID -- the domain a passkey is bound to. */
public readonly string $webauthnRpId,
/** WebAuthn relying party display name, shown by the browser/OS passkey prompt. */
public readonly string $webauthnRpName,
public readonly MailConfig $mail,
) {
}
@@ -46,6 +50,12 @@ final class Config
$appUrl = rtrim(self::env('APP_URL', 'http://localhost:5173'), '/');
// A passkey is bound to a domain (the "relying party ID"), never a full
// origin -- defaults to the frontend's host. WebAuthn requires this to
// be `localhost` or a real domain served over HTTPS; a LAN IP won't work.
$webauthnRpId = self::env('WEBAUTHN_RP_ID') ?? (parse_url($appUrl, PHP_URL_HOST) ?: 'localhost');
$webauthnRpName = self::env('WEBAUTHN_RP_NAME', 'Projects');
$mailLogPath = self::env('MAIL_LOG_PATH', $storagePath . '/mail.log');
if (!self::isAbsolutePath($mailLogPath)) {
$mailLogPath = $basePath . '/' . ltrim($mailLogPath, '/');
@@ -63,7 +73,17 @@ final class Config
smtpEncryption: strtolower(self::env('MAIL_SMTP_ENCRYPTION', 'tls')),
);
return new self($databasePath, $jwtSecret, $jwtTtl, $displayErrors, $allowRegistration, $appUrl, $mail);
return new self(
$databasePath,
$jwtSecret,
$jwtTtl,
$displayErrors,
$allowRegistration,
$appUrl,
$webauthnRpId,
$webauthnRpName,
$mail,
);
}
private static function env(string $key, ?string $default = null): ?string
+25 -1
View File
@@ -9,6 +9,7 @@ use App\Http\Controllers\AuthController;
use App\Http\Controllers\CardController;
use App\Http\Controllers\CardStatusController;
use App\Http\Controllers\EmailVerificationController;
use App\Http\Controllers\PasskeyController;
use App\Http\Controllers\ProjectController;
use App\Http\JsonErrorHandler;
use App\Mail\EmailVerifier;
@@ -18,10 +19,13 @@ use App\Mail\PhpMailerMailer;
use App\Repository\CardRepository;
use App\Repository\CardStatusRepository;
use App\Repository\EmailVerificationRepository;
use App\Repository\PasskeyRepository;
use App\Repository\ProjectRepository;
use App\Repository\UserRepository;
use App\Repository\WebAuthnChallengeRepository;
use App\Support\Config;
use App\Support\Database;
use lbuchs\WebAuthn\WebAuthn;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;
@@ -47,8 +51,10 @@ $projects = new ProjectRepository($database->pdo());
$cards = new CardRepository($database->pdo());
$cardStatuses = new CardStatusRepository($database->pdo());
$verificationTokens = new EmailVerificationRepository($database->pdo());
$passkeys = new PasskeyRepository($database->pdo());
$webauthnChallenges = new WebAuthnChallengeRepository($database->pdo());
$jwt = new JwtService($config->jwtSecret, $config->jwtTtl);
$session = new SessionPayload($jwt, $verificationTokens);
$session = new SessionPayload($jwt, $verificationTokens, $passkeys);
/** @var Mailer $mailer */
$mailer = $config->mail->transport === 'log'
@@ -56,11 +62,19 @@ $mailer = $config->mail->transport === 'log'
: new PhpMailerMailer($config->mail);
$verifier = new EmailVerifier($verificationTokens, $users, $mailer, $config->appUrl);
// 'none' attestation: verify the credential is a legitimate WebAuthn response
// without checking authenticator provenance against a root CA -- the usual
// choice for "log in with the same device you registered", not a fleet of
// company-issued security keys. useBase64UrlEncoding=true so the challenge/
// ids in getCreateArgs()/getGetArgs() JSON straight to the frontend.
$webAuthn = new WebAuthn($config->webauthnRpName, $config->webauthnRpId, ['none'], true);
$authController = new AuthController($users, $session, $verifier, $config->allowRegistration);
$emailController = new EmailVerificationController($users, $verificationTokens, $verifier, $session);
$projectController = new ProjectController($projects, $cardStatuses);
$cardController = new CardController($projects, $cards, $cardStatuses);
$cardStatusController = new CardStatusController($projects, $cardStatuses);
$passkeyController = new PasskeyController($webAuthn, $passkeys, $webauthnChallenges, $users, $session);
$authMiddleware = new AuthMiddleware($jwt, $users);
// --- Routes ---------------------------------------------------------------
@@ -71,6 +85,7 @@ $app->group('/api', function (RouteCollectorProxy $group) use (
$projectController,
$cardController,
$cardStatusController,
$passkeyController,
$authMiddleware,
) {
$group->get('/health', function (Request $request, Response $response): Response {
@@ -80,10 +95,19 @@ $app->group('/api', function (RouteCollectorProxy $group) use (
$group->post('/auth/magic-link', [$authController, 'requestLoginLink']);
$group->post('/auth/verify-email', [$emailController, 'verify']);
$group->post('/auth/passkey/options', [$passkeyController, 'loginOptions']);
$group->post('/auth/passkey/verify', [$passkeyController, 'loginVerify']);
$group->get('/me', [$authController, 'me'])->add($authMiddleware);
$group->post('/email/change', [$emailController, 'requestChange'])->add($authMiddleware);
$group->group('/passkeys', function (RouteCollectorProxy $passkeys) use ($passkeyController) {
$passkeys->get('', [$passkeyController, 'index']);
$passkeys->post('', [$passkeyController, 'store']);
$passkeys->post('/options', [$passkeyController, 'registerOptions']);
$passkeys->delete('/{passkeyId:[0-9]+}', [$passkeyController, 'destroy']);
})->add($authMiddleware);
$group->group('/projects', function (RouteCollectorProxy $projects) use (
$projectController,
$cardController,