Skip to content

Core\Passkey::registerOptions

Returns the options a browser needs to create a new passkey for an account, as a JSON string.

Send the JSON to the page. There, JavaScript passes it to PublicKeyCredential.parseCreationOptionsFromJSON(), and the result to navigator.credentials.create(). The browser asks the user to create the passkey and gives back its answer. Check that answer on the server with Core\Passkey::verifyRegistration.

The options contain a new random challenge, which is saved in the session. If the visitor has no session yet, the call creates one. A challenge can be checked once, and only for five minutes. The options also ask the device to check that the user is really there, with a fingerprint, a face or a PIN.

Good to know: pass the passkeys the account already has as $existing. A device that already has one of them does not create a second one.

The examples below show the options for a new account, an account that already has a passkey, and both halves of a page that adds a passkey.

Parameters

  • $rpIdstringThe domain of your site, such as example.com. The passkey works only on this domain and its subdomains.
  • $rpNamestringThe name of your site. The browser shows it to the user.
  • $userIdbytesA unique id for the account, from 1 to 64 bytes. Do not use an email address or a name. Core\Random::bytes(16) makes a good id.
  • $userNamestringThe name the user signs in with, such as an email address. The browser shows it in its list of passkeys.
  • $existingarray<Core\Passkey\Credential>default []The passkeys this account already has. A device that has one of them does not create a second one.

Return value

Returns string. A JSON string. In the browser, pass it to PublicKeyCredential.parseCreationOptionsFromJSON(), and pass the result to navigator.credentials.create().

Errors

  • LogicErrorThe program is not handling a request. A command-line program, a job and a test have no session.
  • RuntimeErrorThe session store, where the server keeps session data, cannot be opened. This happens only at the first call in the request that uses the session. With the default store, the cause is that the server has no data folder. With [session] backend = "shared", [cache.shared] url is not set, or the program does not have the cache.shared capability.
  • IOErrorThe store cannot be reached. The user may still have a session there, so do not treat them as signed out.
  • LogicErrorThe call is inside Core\Html::later or Core\Task::runAfterResponse. The response headers are already sent there, so the challenge cannot be saved in the session.
  • LogicError$rpId is empty, or $userId is empty or longer than 64 bytes.

Changelog

VersionChange
0.0.5Core\Csrf::token and the Core\Passkey methods that save or check a challenge open the session on their first use. You do not call anything before them. In a program that handles no request, they throw a LogicError.

Examples

The examples below run with this configuration file.

nvs.toml
# The challenge is saved in the session, and a session keeps its data in a store.
# These examples use the Redis server on this computer at port 16379,
# and allow the program to use it.
[capabilities.cache]
shared = true
[session]
backend = "shared"
[cache.shared]
url = "redis://127.0.0.1:16379"

The options for a new passkey

<?nvs
// Shows the options a server sends to the browser to create a passkey.
// requires: redis
// The account id is random bytes. It is not the email address.
bytes $accountId = Core\Random::bytes(16);
// `registerOptions` saves the challenge in the session.
// The session opens on this first use, so no other step is needed.
string $json = Core\Passkey::registerOptions('example.com', 'Example Shop', $accountId, 'ada@example.com');
// The challenge is random, so this prints only the fields that are the same each time.
var $options = Core\Json::decode($json) as array<mixed>;
var $site = $options['rp'] as array<mixed>;
var $user = $options['user'] as array<mixed>;
echo 'site: ', $site['id'] as string, ' (', $site['name'] as string, ")\n";
echo 'user: ', $user['name'] as string, "\n";
// `timeout` is in milliseconds. This prints `300000`, which is five minutes.
echo 'timeout: ', $options['timeout'] as int, "\n";
// The challenge is 32 random bytes, written as 43 characters.
echo 'challenge: ', Core\Str::length($options['challenge'] as string), " characters\n";
Output
site: example.com (Example Shop)
user: ada@example.com
timeout: 300000
challenge: 43 characters

An account with a passkey

<?nvs
// Shows how the passkeys an account already has go into the options for a new one.
// requires: redis
// The account already has a passkey on a laptop. The application stored its four values.
// Here they are made up: an Ed25519 public key from `Core\Crypto`, and a random id.
var $key = Core\Crypto::generateKeyPair(Core\Crypto\KeyKind::Ed25519);
bytes $raw = $key->publicKey()->write(Core\Crypto\PublicKey::Format::Raw);
bytes $publicKey = Core\Bytes::join([Core\Encoding::fromHex('a4010103272006215820'), $raw]);
Core\Passkey\Credential $laptop = Core\Passkey\Credential::of(
Core\Random::bytes(16),
$publicKey,
Core\Passkey\Credential::Algorithm::Ed25519,
0,
);
// `$existing` lists the passkeys the account has. The laptop does not create a second one.
string $json = Core\Passkey::registerOptions('example.com', 'Example Shop', Core\Random::bytes(16), 'ada@example.com', [$laptop]);
// The options list the laptop's passkey under `excludeCredentials`. This prints `1`.
var $options = Core\Json::decode($json) as array<mixed>;
var $excluded = $options['excludeCredentials'] as array<mixed>;
echo 'excluded passkeys: ', Core\Arr::count($excluded), "\n";
// The id in the options is the stored id, written in base64url.
var $first = $excluded[0] as array<mixed>;
bool $same = ($first['id'] as string) == Core\Encoding::toBase64Url($laptop->id());
echo 'it is the laptop: ', $same ? 'yes' : 'no', "\n";
Output
excluded passkeys: 1
it is the laptop: yes

A page that adds a passkey

<?nvs
// Shows the browser half and the server half of a page that adds a passkey to an account.
// requires: redis
class Account
{
public function constructor(public bytes $id, public string $email)
{}
}
class PasskeyPage
{
// The browser half. This JavaScript gets the options from the server,
// creates the passkey and sends the answer back to the server.
public static function script(): string
{
return "const response = await fetch('/account/passkey/options', { method: 'POST' });\n"
. "const options = PublicKeyCredential.parseCreationOptionsFromJSON(await response.json());\n"
. "const passkey = await navigator.credentials.create({ publicKey: options });\n"
. "await fetch('/account/passkey', { method: 'POST', body: JSON.stringify(passkey) });\n";
}
// The server half. It answers the first `fetch` in the script.
public static function options(Account $account, array<Core\Passkey\Credential> $passkeys): string
{
return Core\Passkey::registerOptions('example.com', 'Example Shop', $account->id, $account->email, $passkeys);
}
}
// The page contains this script.
echo PasskeyPage::script(), "\n";
// This request is the script's first `fetch`. The account has no passkey yet.
Account $ada = new Account(Core\Random::bytes(16), 'ada@example.com');
string $json = PasskeyPage::options($ada, []);
// The challenge is new for every request, so this prints only the user.
var $options = Core\Json::decode($json) as array<mixed>;
var $user = $options['user'] as array<mixed>;
echo 'options for ', $user['name'] as string, "\n";
Output
const response = await fetch('/account/passkey/options', { method: 'POST' });
const options = PublicKeyCredential.parseCreationOptionsFromJSON(await response.json());
const passkey = await navigator.credentials.create({ publicKey: options });
await fetch('/account/passkey', { method: 'POST', body: JSON.stringify(passkey) });
options for ada@example.com