Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion src/docs/fortify.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
- [Deleting Passkeys](#deleting-passkeys)
- [Customizing Passkeys](#customizing-passkeys)
- [Passkey Models](#passkey-models)
- [Authenticator Icons](#authenticator-icons)
- [Passkey Cleanup](#passkey-cleanup)
- [Standalone Passkeys](#standalone-passkeys)
- [Swoole And Worker State](#swoole-and-worker-state)
Expand Down Expand Up @@ -556,7 +557,7 @@ The resolved relying party ID must be a registrable-domain suffix of the resolve

The `user_handle_secret` defaults to the app key for convenience, but production applications should set a dedicated, long-lived value before registering passkeys. Changing it changes generated user handles.

Each user handle is derived from the owner's morph type, table, and primary key. If one relying party serves several tenant databases whose owners can share the same type and key, override `getPasskeyUserHandle()` on your passkey user model to include a stable tenant identifier that does not reveal personal information.
Each user handle is derived from the owner's morph type, table, and primary key. If one relying party serves several tenant databases whose owners can share the same type and key, override `getPasskeyUserHandle()` on your passkey user model to include a stable tenant identifier that does not reveal personal information. Return an ASCII value of at most 64 bytes, such as a hex-encoded HMAC: some platforms corrupt binary user handles, which breaks later sign-ins.

The published configuration applies a dedicated `passkeys` rate limiter to Fortify's passkey login, confirmation, and registration routes. If needed, you may customize it using the `fortify.limiters.passkeys` configuration option and a corresponding `RateLimiter::for(...)` definition, as described in [rate limiting](#rate-limiting).

Expand Down Expand Up @@ -827,6 +828,45 @@ use Hypervel\Passkeys\Passkeys;
Passkeys::usePasskeyModel(Passkey::class);
```

<a name="authenticator-icons"></a>
### Authenticator Icons

Each passkey's `authenticator` attribute contains the name of the password manager or device that created it, such as "Google Password Manager" or "1Password". Passkeys also expose the authenticator's icon as a `data:` URI in light and dark variants:

```php
$passkey->authenticator_icon_light;
$passkey->authenticator_icon_dark;
```

All three return `null` when the authenticator is unrecognized, and the icons also return `null` when the authenticator has no icon.

Icons are not serialized by default, since the icon data is considerably larger than the name. To include them in `toArray()` / `toJson()`, append them per instance:

```php
$passkey->append(['authenticator_icon_light', 'authenticator_icon_dark']);
```

Or on every passkey, by appending them on a [custom passkey model](#passkey-models):

```php
use Hypervel\Database\Eloquent\Attributes\Appends;
use Hypervel\Passkeys\Passkey as BasePasskey;

#[Appends(['authenticator_icon_light', 'authenticator_icon_dark'])]
class Passkey extends BasePasskey
{
}
```

You may also resolve an icon directly from an AAGUID. Icon data is loaded lazily, so resolving a name never loads it:

```php
use Hypervel\Passkeys\Support\Aaguids;

Aaguids::iconFor($aaguid); // light by default
Aaguids::iconFor($aaguid, theme: 'dark');
```

<a name="passkey-cleanup"></a>
### Passkey Cleanup

Expand Down
2 changes: 1 addition & 1 deletion src/docs/passport.md
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ PASSPORT_CACHE_STORE=redis
PASSPORT_CACHE_TTL=300
```

Caching is disabled by default. A null or empty `cache.store` uses your application's default cache store. JWT signatures and expiration are checked on every request. The user lookup is separate and may be cached through your [Eloquent user provider](/docs/{{version}}/authentication#user-lookup-cache).
Caching is disabled by default. Each member of the `cache` configuration is optional: omitting `enabled` disables caching, a null, empty, or omitted `store` uses your application's default cache store, and an omitted `ttl` or `prefix` defaults to 300 seconds or `passport`. JWT signatures and expiration are checked on every request. The user lookup is separate and may be cached through your [Eloquent user provider](/docs/{{version}}/authentication#user-lookup-cache).

Use a cache store shared by every process that changes clients or revokes tokens. Redis or a shared database cache works across application servers. A file store requires shared storage, and a Swoole store is suitable only when every writer runs in the same server. Request-local and worker-local array stores are not supported. Keep access to this cache as restricted as access to your session store.

Expand Down
2 changes: 1 addition & 1 deletion src/docs/socialite.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ These credentials should be placed in your application's `config/services.php` c
```

> [!NOTE]
> If the `redirect` option contains a relative path, it will automatically be resolved to a fully qualified URL.
> If the `redirect` option contains a relative path, it will automatically be resolved to a fully qualified URL using your application's `app.url` configuration value, which must then be an absolute HTTP or HTTPS URL.

The X OAuth 2 driver reads its credentials from the `x` key:

Expand Down
6 changes: 3 additions & 3 deletions src/docs/static-analysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,7 @@ The following sections explain the diagnostics and their remedies. Use this tabl
| [Starting Queries](#starting-queries) | `hypervel.noImplicitQueryBuilderCall` |
| [Schema Dumps](#schema-dumps) | `hypervel.schemaDump` |
| [Migration Column Types](#migration-column-types) | `hypervel.migrationColumnType` |
| [Dispatching Jobs and Events](#dispatching-jobs-and-events) | `hypervel.jobs.noConstructor`, `hypervel.events.noConstructor`, `argument.type` and the other argument identifiers |
| [Dispatching Jobs and Events](#dispatching-jobs-and-events) | `new.noConstructor`, `argument.type` and the other argument identifiers |
| [Dispatching Jobs in Transactions](#dispatching-jobs-in-transactions) | `hypervel.dispatchInTransactionAfterCommit` |
| [Models in Queued Jobs](#models-in-queued-jobs) | `hypervel.jobSerializesModels` |
| [Batched Jobs](#batched-jobs) | `hypervel.batchedJobIsBatchable`, `hypervel.noBatchedUniqueJob`, `hypervel.batchableJobChecksCancellation` |
Expand Down Expand Up @@ -1510,11 +1510,11 @@ The `checkMigrationColumnTypes` parameter enables reports for `json`, `enum` and
A job's `dispatch`, `dispatchIf`, `dispatchUnless`, `dispatchSync` and `dispatchAfterResponse` methods, and an event's `dispatch`, `dispatchIf`, `dispatchUnless` and `broadcast` methods, pass their arguments to the class's constructor, so the arguments are checked against it:

```php
// Parameter #1 $podcast of job class App\Jobs\ProcessPodcast constructor expects App\Models\Podcast...
// Parameter #1 $podcast of class App\Jobs\ProcessPodcast constructor expects App\Models\Podcast...
ProcessPodcast::dispatch($podcast->id);
```

The first argument of `dispatchIf` and `dispatchUnless` is the condition, so only the arguments after it are checked. A class that defines its own dispatch method is checked against that method instead.
The first argument of `dispatchIf` and `dispatchUnless` is the condition, so only the arguments after it are checked. A class that defines its own dispatch method is checked against that method instead. Since `dispatchAfterResponse` passes its arguments to `dispatch`, a class's own `dispatch` method is also used for its `dispatchAfterResponse` calls.

<a name="dispatching-jobs-in-transactions"></a>
### Dispatching Jobs in Transactions
Expand Down
266 changes: 266 additions & 0 deletions src/passkeys/resources/aaguid-icons.php

Large diffs are not rendered by default.

64 changes: 55 additions & 9 deletions src/passkeys/scripts/sync-aaguids.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ function publishAaguids(string $destination, string $contents): void
* @see https://github.com/passkeydeveloper/passkey-authenticator-aaguids
*/
$source = 'https://raw.githubusercontent.com/passkeydeveloper/passkey-authenticator-aaguids/main/aaguid.json';
$destination = __DIR__ . '/../resources/aaguids.php';
$namesDestination = __DIR__ . '/../resources/aaguids.php';
$iconsDestination = __DIR__ . '/../resources/aaguid-icons.php';

$json = @file_get_contents($source);

Expand All @@ -59,7 +60,8 @@ function publishAaguids(string $destination, string $contents): void
exit(1);
}

$aaguids = [];
$names = [];
$icons = [];

foreach ($data as $aaguid => $entry) {
if (! is_string($aaguid) || $aaguid === ''
Expand All @@ -70,14 +72,58 @@ function publishAaguids(string $destination, string $contents): void
exit(1);
}

$aaguids[$aaguid] = $entry['name'];
$names[$aaguid] = $entry['name'];

foreach (['light' => 'icon_light', 'dark' => 'icon_dark'] as $theme => $key) {
if (! array_key_exists($key, $entry)) {
continue;
}

// Applications render icons as image sources, so keep the list's documented SVG data URI form.
if (! is_string($entry[$key]) || ! str_starts_with($entry[$key], 'data:image/svg+xml;base64,')) {
fwrite(STDERR, "AAGUID list contains an invalid entry.\n");
exit(1);
}

$icons[$aaguid][$theme] = $entry[$key];
}
}

$exported = var_export($aaguids, true);
$exported = str_replace("\n ", "\n ", $exported);
$exported = substr_replace($exported, '[', 0, strlen('array ('));
$exported = substr_replace($exported, ']', -1);
/**
* Render a flat `key => scalar` array as a PHP file.
*
* @param array<string, string> $values
*/
$renderNames = function (array $values): string {
$lines = ['<?php', '', 'declare(strict_types=1);', '', 'return ['];

foreach ($values as $aaguid => $name) {
$lines[] = sprintf(' %s => %s,', var_export($aaguid, true), var_export($name, true));
}

return implode("\n", [...$lines, '];', '']);
};

/**
* Render a nested `key => [theme => icon]` array as a PHP file.
*
* @param array<string, array<string, string>> $values
*/
$renderIcons = function (array $values): string {
$lines = ['<?php', '', 'declare(strict_types=1);', '', 'return ['];

foreach ($values as $aaguid => $themes) {
$lines[] = sprintf(' %s => [', var_export($aaguid, true));
foreach ($themes as $theme => $icon) {
$lines[] = sprintf(' %s => %s,', var_export($theme, true), var_export($icon, true));
}
$lines[] = ' ],';
}

return implode("\n", [...$lines, '];', '']);
};

publishAaguids($destination, "<?php\n\ndeclare(strict_types=1);\n\nreturn {$exported};\n");
publishAaguids($namesDestination, $renderNames($names));
publishAaguids($iconsDestination, $renderIcons($icons));

echo 'Synced ' . count($aaguids) . " AAGUIDs.\n";
echo 'Synced ' . count($names) . ' AAGUIDs and ' . count($icons) . " icon sets.\n";
8 changes: 4 additions & 4 deletions src/passkeys/src/Actions/StorePasskey.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public function __invoke(
protected function getResponse(PublicKeyCredential $credential): AuthenticatorAttestationResponse
{
if (! $credential->response instanceof AuthenticatorAttestationResponse) {
throw InvalidPasskeyException::make('Unable to register passkey. Please try again.');
throw InvalidPasskeyException::make(__('Unable to register passkey. Please try again.'));
}

return $credential->response;
Expand All @@ -83,7 +83,7 @@ protected function validate(
host: $this->hostFromOptions($options),
);
} catch (WebauthnException) {
throw InvalidPasskeyException::make('Unable to register passkey. Please try again.');
throw InvalidPasskeyException::make(__('Unable to register passkey. Please try again.'));
}
}

Expand Down Expand Up @@ -114,7 +114,7 @@ public function createPasskey(
): Passkey {
if (! hash_equals($user->getPasskeyUserHandle(), $source->userHandle)) {
throw InvalidPasskeyException::make(
'Passkey registration options no longer match this account. Please try again.',
__('Passkey registration options no longer match this account. Please try again.'),
);
}

Expand All @@ -128,7 +128,7 @@ public function createPasskey(
'credential' => json_decode(WebAuthn::toJson($source), true, flags: JSON_THROW_ON_ERROR),
]);
} catch (UniqueConstraintViolationException) {
throw InvalidPasskeyException::make('Unable to register this passkey.');
throw InvalidPasskeyException::make(__('Unable to register this passkey.'));
}

return $passkey;
Expand Down
25 changes: 18 additions & 7 deletions src/passkeys/src/Actions/VerifyPasskey.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use RuntimeException;
use Webauthn\AuthenticatorAssertionResponse;
use Webauthn\CredentialRecord;
use Webauthn\Exception\InvalidUserHandleException;
use Webauthn\Exception\WebauthnException;
use Webauthn\PublicKeyCredential;
use Webauthn\PublicKeyCredentialRequestOptions;
Expand Down Expand Up @@ -78,7 +79,7 @@ public function __invoke(
protected function getResponse(PublicKeyCredential $credential): AuthenticatorAssertionResponse
{
if (! $credential->response instanceof AuthenticatorAssertionResponse) {
throw InvalidPasskeyException::make('Unable to verify passkey. Please try again.');
throw InvalidPasskeyException::make(__('Unable to verify passkey. Please try again.'));
}

return $credential->response;
Expand All @@ -93,7 +94,7 @@ public function getPasskey(PublicKeyCredential $credential, bool $lock = false):
{
// Assertion ceremonies do not run CheckCredentialId, so enforce its CTAP2 limit before lookup.
if (strlen($credential->rawId) > 1023) {
throw InvalidPasskeyException::make('Passkey not recognized. It may have been removed from your account.');
throw InvalidPasskeyException::make(__('Passkey not recognized. It may have been removed from your account.'));
}

$credentialId = Base64UrlSafe::encodeUnpadded($credential->rawId);
Expand All @@ -108,7 +109,7 @@ public function getPasskey(PublicKeyCredential $credential, bool $lock = false):
$passkey = $query->first();

if (! $passkey instanceof Passkey) {
throw InvalidPasskeyException::make('Passkey not recognized. It may have been removed from your account.');
throw InvalidPasskeyException::make(__('Passkey not recognized. It may have been removed from your account.'));
}

return $passkey;
Expand All @@ -130,7 +131,7 @@ public function ensurePasskeyBelongsToUser(Passkey $passkey, ?PasskeyUser $user)
if (! is_scalar($identifier)
|| $passkey->user_type !== $user->getMorphClass()
|| (string) $passkey->user_id !== (string) $identifier) {
throw InvalidPasskeyException::make('Passkey not recognized. It may have been removed from your account.');
throw InvalidPasskeyException::make(__('Passkey not recognized. It may have been removed from your account.'));
}
}

Expand All @@ -143,13 +144,13 @@ protected function resolvePasskeyOwner(Passkey $passkey, string $ownerType): Pas
{
// Compare the stored type first so another provider's owner type is never resolved.
if ($passkey->user_type !== $ownerType) {
throw InvalidPasskeyException::make('Passkey not recognized. It may have been removed from your account.');
throw InvalidPasskeyException::make(__('Passkey not recognized. It may have been removed from your account.'));
}

$user = $passkey->user;

if (! $user instanceof PasskeyUser) {
throw InvalidPasskeyException::make('Passkey not recognized. It may have been removed from your account.');
throw InvalidPasskeyException::make(__('Passkey not recognized. It may have been removed from your account.'));
}

return $user;
Expand Down Expand Up @@ -178,6 +179,8 @@ protected function ownerMorphClassForGuard(StatefulGuard $guard): string

/**
* Validate the credential against the stored passkey.
*
* @throws InvalidPasskeyException
*/
protected function validate(
AuthenticatorAssertionResponse $response,
Expand All @@ -199,8 +202,16 @@ protected function validate(
host: $this->hostFromOptions($options),
userHandle: $source->userHandle,
);
} catch (InvalidUserHandleException) {
// Some platforms corrupt binary user handles by treating them as
// UTF-8 text, so the handle returned by the authenticator never
// matches the stored one again. Surface a validation error so
// the user can re-register the passkey instead of hitting a 500.
throw InvalidPasskeyException::make(
__('This passkey can no longer be used. Please remove it from your account and register a new one.')
);
} catch (WebauthnException) {
throw InvalidPasskeyException::make('Unable to verify passkey. Please try again.');
throw InvalidPasskeyException::make(__('Unable to verify passkey. Please try again.'));
}
}

Expand Down
6 changes: 4 additions & 2 deletions src/passkeys/src/Exceptions/InvalidPasskeyException.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,13 @@ class InvalidPasskeyException extends ValidationException
{
/**
* Create a new invalid passkey exception.
*
* @param null|array<array-key, mixed>|string $message
*/
public static function make(string $message = 'Unable to register passkey. Please try again.'): static
public static function make(array|string|null $message = null): static
{
return static::withMessages([
'credential' => __($message),
'credential' => $message ?? __('Unable to register passkey. Please try again.'),
]);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public function store(
$user = $passkey->user;

if (! $user instanceof PasskeyUser || ! Passkeys::allowsLogin($request, $passkey)) {
throw InvalidPasskeyException::make('Unable to sign in with this account.');
throw InvalidPasskeyException::make(__('Unable to sign in with this account.'));
}

Passkeys::guard()->login($user, $request->remember());
Expand Down
Loading