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:
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user