# Second factors: codes and passkeys

A code from an authenticator app ([totp](../extensions/totp/README.md)),
and passkeys ([passkey](../extensions/passkey/README.md)), checked on the
back end and fitted into the accounts and sessions of
[`auth`](back-end.md#signing-in): an account that has one is not signed in
by its password alone, and a call can ask for a factor shown lately.
Back to the [map](README.md).

```text
use "pkg:totp/totp.mote"
use "pkg:passkey/passkey.mote"

// Money leaves only for someone who showed a second factor in the last ten minutes.
server fn payout(cents: number): string requires secondFactor(10)
  …

action enter
  auth.signIn(email, password) else err => (err.kind == "second" ? askForCode = true : none)
```

## In auth

| | |
|---|---|
| `auth.secondFactor(userId, kind, on)` | Whether the account has a second factor of that kind (`"totp"`, `"passkey"`, a word of the program's). The extensions say so as one is added and the last taken away. Back end only. |
| `auth.hasSecondFactor(userId)` | Whether it has one of any kind. |
| `auth.signIn(email, password)` | For an account with one: the password is checked, and the call **fails with the kind `"second"`** ("a second factor is asked for: …"). The browser has a session that owes it: nobody's (`auth.me()` is none, `requires signedIn` is `401`) until the factor is shown. |
| `auth.owed()` | Who owes theirs in this session, `{id, email}`, or none. A page may ask it, to show the field for the code. |
| `auth.secondPassed()` | The program checked a factor of this call's person (the one owed, or the one signed in): their session has it as of now. Back end only: what calls it is the check. |
| `auth.secondAt()` | When this session last showed one (ms), 0 for never. |
| `auth.signInAs(userId, {second: true})` | For a way in that was two factors itself (a passkey that checked it was the person): nothing is owed. Without it, an account with a factor owes one after `signInAs` too (a sign-in with Google, say). |
| `requires secondFactor(10)` | A session that showed a factor in the last ten minutes (`secondFactor` alone: in this session at all). Refused, the call fails with the kind `"second"`, so that the page asks for it and calls again. Never true for an API key or token. |

Sessions an account had before it got a factor are left as they are (they
have shown none: `secondFactor(…)` refuses them until they do). Acting as
someone shows nothing of theirs.

## Codes from an app: totp

`TOTP_KEY` (a secret) seals the apps' secrets; `TOTP_ISSUER` is what the app
shows the code under (the app's name unset).

| `server fn` | |
|---|---|
| `totpBegin()` | A new secret for whoever is signed in: `{secret, uri, svg}`: the secret to type (base32, in fours), the `otpauth://` address, and its QR code as an SVG. `TotpQr uri=…` shows it. |
| `totpConfirm(code)` | The first code from the app: it is on, the session has shown it, and ten recovery codes are given, once. |
| `totpCheck(code)` | A code, or a recovery code, for whoever owes one or is signed in: `auth.secondPassed()`. |
| `totpNewRecovery()`, `totpOff()` | For someone who showed a factor in the last five minutes. |
| `totpState()` | `{on, recoveryLeft}`. |

RFC 6238 (30-second steps, six digits, SHA-1, as every app has it) over RFC
4226. The step before and after are taken; **a step whose code was taken is
never taken again**, nor any before it; ten wrong codes in a row and the
account takes none for a quarter of an hour (and ten a minute from one
address). Recovery codes are kept as hashes, each good once.

**The QR code** is drawn by `extensions/totp/qr.mote`, a QR writer in
ordinary Mote (byte mode, level M, versions 1 to 10, the mask of least
penalty): `qrGrid(text)`, `qrSvg(text, scale)`, `qrUrl(text)`. It is for
any short text, in a page or on the back end.

## Passkeys

`PASSKEY_RP_ID` (the domain they are made for; unset, the host the request
came to), `PASSKEY_ORIGINS` (the addresses a page may ask from), `PASSKEY_NAME`.

| | |
|---|---|
| `press=passkeyAdd` | Makes a passkey on this device for whoever is signed in. (Someone with a factor shows it first.) |
| `press=passkeySignIn` | Signs in with one: any of this site's on the device, the person chooses. |
| `passkeyRegisterBegin()`, `passkeyRegisterFinish(handle, made, name)` | The two halves of making one, for a page of the program's own. |
| `passkeySignInBegin()`, `passkeySignInFinish(handle, got)` | Of signing in. A passkey that checked it was the person (UV) is both factors: nothing is owed. |
| `passkeyCheck(handle, got)` | A passkey as the second factor of whoever owes one, or is asked again. |
| `passkeyList()`, `passkeyRemove(id)` | Theirs, each `{id, name, made, last, aaguid, backup, transports}`; taking one away asks for a factor in the last five minutes. |
| `passkeysOf(userId)`, `passkeySalt(id)` | For the back end's own code: an account's passkeys (the same rows), and the salt one's PRF output is asked with. |

What the back end checks, every byte (WebAuthn Level 2, 7.1 and 7.2): the
client data's `type`, `challenge` (made here, five minutes, once) and
`origin` (never another site's frame); the authenticator data's hash of the
RP ID, its flags (UP; UV to sign in), its counter (one that goes back is a
copied passkey, refused and said in the log); the public key from its COSE
form (ES256, RS256, EdDSA: [`cbor`](data.md#cbor)); the signature over the
authenticator data and the client data's hash (ECDSA in DER:
[`der: true`](data.md#signatures-with-a-key-pair)); the user handle.
Where the program asks for attestation, its statement and its chain
([below](#attestation-checked)).

### What a program may say of its passkeys

Five fns the extension [wants](language.md#what-a-package-wants-of-its-taker),
each with a default: a program that declares none has what it had.

```text
fn passkeyMax(user: string): number = 2
fn passkeyPrf(): bool = true
fn passkeyAttestation(): string = "direct"
fn passkeyRoots(aaguid: string): string[] = [env("KEY_ROOTS")]
fn passkeyMay(about: PasskeyAbout): bool = about.attested && !about.backup
```

| | |
|---|---|
| `passkeyMax(user)` | How many passkeys that account may keep. `0`, the default: any number. One more is refused as it is begun and as it is finished (two begun at once are not both kept), with the kind `"limited"`. |
| `passkeyPrf()` | Whether each passkey is asked for a [PRF output](#a-key-from-a-passkey-the-prf-extension). The back end makes a salt of 32 random bytes as the passkey is begun, keeps it with the passkey, and says it again with every challenge to someone it knows (signed in, or owing a second factor): `extensions.prf` is in the options, and the page does nothing more than hand them to `passkey.create` and `passkey.get`. The output itself stays in the page. |
| `passkeyAttestation()` | The attestation asked for: `"none"` (the default), `"indirect"`, `"direct"`, `"enterprise"`. Other than `"none"`, the statement is [checked](#attestation-checked). |
| `passkeyRoots(aaguid)` | The roots the program trusts for that make and model: certificates in PEM (a text may hold several), or folders of `.pem` and `.crt` files. `[]`, the default: no chain reaches a root, and no passkey is `attested`. For [the FIDO Metadata Service's](#the-fido-metadata-service) list, `passkeyMdsRoots(aaguid)?`. |
| `passkeyMay(about)` | Whether this passkey may be kept, asked last, once all else has been checked. `about` is `{user, id, aaguid, fmt, verified, backup, transports, attested, attestation, others}`: `verified` is UV, `backup` whether it may be backed up and so be on several devices (a synced passkey, not one bound to a piece of hardware), `attested` whether its maker vouches for it (below), `attestation` what its statement was found to be, `others` the account's passkeys so far. A no (or a failure) keeps nothing. |

**The AAGUID** (`aaguid`, written `ea9b8d66-4d01-1d21-3ce4-b6b48cb575d4`) says
which make and model made a passkey, not which one of them: two security
keys of one model say the same, and so it cannot show that two passkeys are
on two authenticators. What does is `excludeCredentials`, which the
extension always says: an authenticator that holds one of the account's
passkeys refuses to make another, so an account's passkeys are on as many
authenticators as there are passkeys (a synced one is on every device of
its owner's). A rule of "two before the account is whole" is `passkeysOf(user)?.length >= 2`.
A browser gives zeros for most security keys' AAGUID unless attestation is
asked for; with `"direct"` it is the authenticator's, and only an
attestation that is checked up to a root proves it (`about.attested`).

With nobody known (a sign-in by a discoverable passkey, no name given)
which passkey will answer is not known either, so no salt is asked with
that challenge. Signed in, the next `passkeySignInBegin()` has it.

### Attestation checked

An attestation statement is the authenticator maker's signature that this
passkey was made inside one of its devices. With `passkeyAttestation()`
other than `"none"` the browser passes it on, and the extension
(`extensions/passkey/attest.mote`) checks it as WebAuthn Level 3 section 8
has each format, then checks its certificates up to the roots the program
names for that AAGUID ([`crypto.cert.chain`](data.md#certificates-read-whole-and-their-chains)).

| Format | What is checked | `trust` |
|---|---|---|
| `packed` with `x5c` | The signature over the authenticator data and the client data's hash, by the certificate's key, with the statement's `alg`; the certificate: version 3, a subject with `C`, `O`, `OU=Authenticator Attestation` and `CN`, no CA, and its AAGUID extension, if any, the passkey's. | `"basic"` |
| `packed`, no `x5c` | Self attestation: signed by the passkey's own key, with its own alg. | `"self"` |
| `fido-u2f` | One certificate, of a P-256 key; its signature over 0, the RP ID's hash, the client data's hash, the credential's id and its key as U2F writes it. | `"basic"` |
| `tpm` | Version 2.0; the public area (`pubArea`, a `TPMT_PUBLIC`, RSA or ECC) holds the passkey's key; `certInfo` (a `TPMS_ATTEST`) was made by a TPM (its magic), is a certify, its `extraData` the hash of what is attested (by the alg's hash), its name the public area's (`nameAlg` and its hash); its signature by the AIK certificate's key; the AIK certificate: version 3, no subject, the TPM's manufacturer, model and version in its alternative name, the EKU `2.23.133.8.3`, no CA, its AAGUID extension, if any, the passkey's. | `"attca"` |
| `android-key` | The signature by the certificate's key, which is the passkey's; the key description's challenge is the client data's hash; no `allApplications` in either list; the key made in the device (`origin` 0) and for signing (`purpose` 2), in the TEE's list or the software's. | `"basic"` |
| `apple` | The nonce in the certificate (`1.2.840.113635.100.8.2`) is SHA-256 of the authenticator data and the client data's hash; the certificate's key is the passkey's. | `"anonca"` |
| `none` | An empty statement. | `"none"` |

A statement that does not hold **refuses the passkey** (`That passkey
could not be taken (its tpm attestation does not hold: its extraData is not
the hash of this passkey and challenge).`). One that holds is then
followed up its chain (`x5c`, the first certificate the attestation's own)
to `passkeyRoots(aaguid)`. A chain that reaches none of them does not
refuse the passkey: it is not `attested`, and `attestation.why` says why.
Any other format (`android-safetynet`, `compound`, one to come) is kept
and not checked: its trust is `"none"`.

`about.attestation` is `{fmt, trust, root, rootSubject, aaguid, why}`:
`root` the SHA-256 fingerprint (hex) of the root the chain reached
(`""` for none), `rootSubject` its name. `about.attested` is true when the
trust is `"basic"`, `"attca"` or `"anonca"` and a root was reached: the
maker of that model vouches that the passkey is in one of its devices.
The passkey keeps `trust` and `root` (in `passkeyList()` and
`passkeysOf(user)`), beside the statement and client data as they came.

**Security keys only.** A synced passkey (iCloud Keychain, Google
Password Manager) gives no attestation, or Apple's, and is backed up;
a platform authenticator of a laptop gives `tpm` or none. So an
organization's rule of hardware security keys alone is

```text
fn passkeyAttestation(): string = "direct"
fn passkeyRoots(aaguid: string): string[] = passkeyMdsRoots(aaguid)?
fn passkeyMay(about: PasskeyAbout): bool = about.attested && !about.backup && about.attestation.trust == "basic" && about.transports.includes("usb")
```

with the roots of the makers it buys from (or the FIDO Metadata
Service's, below). `about.transports` is what the browser says, and
proves nothing; `about.attested` with the roots of security key makers
alone is what does.

What is not checked: whether a certificate was **revoked** (CRLs, OCSP),
and `enterprise` attestation's own rules (an enterprise statement is
checked as its format is). The counter, the flags, the RP ID and the
signature are checked as before, attestation or not.

### The FIDO Metadata Service

The FIDO Alliance publishes a list of authenticator models (MDS3), each by
its AAGUID with the roots its attestation chains up to and its status
(certified, revoked, its attestation key compromised, …): a JWT, the
**BLOB**, signed by a certificate whose chain goes up to the FIDO
Alliance's root. `extensions/passkey/metadata.mote` reads it; the program
fetches it and **gives the root**, which it fetched once and keeps (it is
not in Mote).

```text
use "pkg:passkey/passkey.mote"
use "pkg:passkey/metadata.mote"

fn passkeyAttestation(): string = "direct"
fn passkeyRoots(aaguid: string): string[] = passkeyMdsRoots(aaguid)?

// The list is renewed each month (its `nextUpdate`): fetched each day, a list no newer is taken again.
server every 86400000 once
  let blob = net.text("https://mds3.fidoalliance.org/")?
  passkeyMdsLoad(blob, env("FIDO_MDS_ROOT"))?
```

| | |
|---|---|
| `passkeyMdsRead(blob, root)?` | The BLOB checked (its `x5c` chain up to `root`, its signature by the first certificate's key, RS256/PS256/ES256/EdDSA) and read: `{no, nextUpdate, entries}`, each entry `{aaguid, description, roots, status, statusAt}` (roots in PEM; the status of its latest report). Nothing kept. Fails (kind `"invalid"`) saying why. |
| `passkeyMdsLoad(blob, root)?` | Checked, then kept (the model `PasskeyMetadata`) in place of what was: how many models it lists. A BLOB of a lower serial number (`no`) than the one kept is refused. |
| `passkeyMdsRoots(aaguid)?` | A model's roots, as `passkeyRoots` wants them; `[]` for a model not listed, or whose status is `REVOKED`, `ATTESTATION_KEY_COMPROMISE`, `USER_VERIFICATION_BYPASS`, `USER_KEY_REMOTE_COMPROMISE` or `USER_KEY_PHYSICAL_COMPROMISE`. |
| `passkeyMdsOf(aaguid)?` | What is kept of a model, or none. |

Only models with an AAGUID (FIDO2) are kept: a U2F key's attestation is
listed by its certificate's key identifier, and its roots are the
program's to name for the AAGUID of zeros. All of it is the back end's.

### In the page: passkey

A page cannot reach `navigator.credentials` otherwise, so four built-ins
are there for it (`runtime/page/passkey.mote`):

| | |
|---|---|
| `passkey.create(options)?` | A new passkey: `{id, clientData, attestation, transports, authenticator, aaguid, attachment, prf}`. `attachment` is `"platform"` (the device's own: Touch ID, Windows Hello) or `"cross-platform"` (a security key, a phone), `""` where the browser does not say; `aaguid` as above; `authenticator` the authenticator data. |
| `passkey.get(options)?` | A passkey's signature of the challenge: `{id, clientData, authenticator, signature, userHandle, attachment, prf}`. |
| `passkey.supported()` | Whether the browser has passkeys at all. |
| `passkey.prfSupported()?` | Whether the browser can ask a passkey for a PRF output at all. A browser that cannot say (one older than `getClientCapabilities`) counts as yes: whether a given passkey can is `prf.enabled` of what `passkey.create` gave. |

The options are WebAuthn's own
([`PublicKeyCredentialCreationOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-publickeycredentialcreationoptions),
[`…RequestOptions`](https://www.w3.org/TR/webauthn-3/#dictdef-publickeycredentialrequestoptions)),
as the back end made them or as the page writes them: `excludeCredentials`,
`allowCredentials` (`[{id}]`), `authenticatorSelection`, `userVerification`,
`attestation`, `hints`, `timeout`, `extensions`. Every binary value in them
(`challenge`, `user.id`, a credential's `id`, a PRF salt) is base64url text
or `bytes`; what comes back is base64url, but for the PRF's outputs, which
are `bytes`. In `passkey.create`, `userVerification`, `residentKey` and
`attachment` said beside the rest are `authenticatorSelection`'s.

Nothing is checked in the page. A prompt the person closes, or that times
out, fails with the kind `"cancelled"`; a browser with none,
`"unsupported"`; an authenticator that holds one of `excludeCredentials`,
or an address passkeys are not to be had at, `"invalid"`. They are the
page's alone: a worker has no `navigator.credentials`, and on the back end
they are refused (`H092`): a passkey is the person's device's. Passkeys
need a secure address (https, or `localhost`).

### A key from a passkey: the PRF extension

The PRF extension (CTAP2 `hmac-secret`) has a passkey make 32 bytes from a
salt: the same bytes for the same passkey and salt every time, others for
any other, and only after it checked it was the person where
`userVerification` is `"required"`. It is a key that is kept nowhere: a
vault wraps what the device remembers under it.

```text
extensions: {prf: {eval: {first: salt}}}                      one salt, whichever passkey answers
extensions: {prf: {eval: {first: salt, second: other}}}       two outputs (to change a salt in one touch)
extensions: {prf: {evalByCredential: {[id]: {first: salt}}}}  passkey.get: each passkey its own salt
```

What it gave is `prf` of the result: `{enabled, first, second}` from
`passkey.create` (`enabled`: this passkey can; some authenticators give
`first` as it is made, others only when next used, so ask again where it is
`none`), `{first, second}` from `passkey.get`. `first` and `second` are
`bytes`, or `none` where nothing was asked or the authenticator has no PRF.

**The output is a secret**, and the result is made so that it does not
travel by accident: `prf` and its two outputs are not enumerable. A result
handed whole to a `server fn` (`passkeyRegisterFinish(handle, made, "")`),
written with `JSON.stringify`, spread into another (`{...made}`), logged or
put in a state goes without them; only `made.prf.first`, said outright,
reaches them. Nothing in Mote writes them to a log or a failure, and the
compiler refuses a program that sends `prf.first`, or anything made of it,
to `persist`, `store`, `db`, a log, a failure, the page's text or a `server
fn` ([`H460`](data.md#key-bytes-kept-or-shown)). Derive the key that is
needed and let the output go: `crypto.hkdf.key(made.prf.first)` holds it
where nothing reads it back, and `crypto.hkdf(material, {info, as: "aes"})`
derives an AES key that is never bytes
([data.md](data.md#a-derived-key-that-is-never-bytes)).

### Passkeys with no back end

`passkey.create` and `passkey.get` need no `server fn`: a page that keeps a
key under a passkey makes and asks its passkeys itself, sends nothing
anywhere and checks nothing, and uses only the PRF output. What it does not
say has a default: a `challenge` of 32 random bytes, `rp` the page's host,
`user.id` 16 random bytes, `pubKeyCredParams` ES256, EdDSA and RS256.

```mote
// docs: whole
app "Vault"

// (The salt and the ids are not secrets: they are kept with the wrapped key.)
state salt = ""
state ids: string[] = []
state said = ""

// What the vault would wrap its device key under. It is not kept, and not shown.
fn wrapKey(out: bytes?): bytes
  if out == none fail("That passkey gives no key (it has no PRF).", {kind: "invalid"})?
  return crypto.hkdf(out, {salt: "vault/v1", info: "device-wrap", length: 32})?

// One more authenticator: verification required, nothing left on a security key, never the
// same authenticator twice.
action enroll
  if salt == "" salt = (bytes.hex(crypto.random(32))?).base64url()
  let made = passkey.create({user: {name: "Vault key"}, userVerification: "required", residentKey: "discouraged", attestation: "none", excludeCredentials: ids.map(id => ({id})), extensions: {prf: {eval: {first: salt}}}})?
  if !made.prf.enabled fail("This authenticator cannot protect a key (it has no PRF).", {kind: "invalid"})?
  // (Some give the output as the passkey is made; the others at a first touch.)
  let out = made.prf.first ?? (passkey.get({allowCredentials: [{id: made.id}], userVerification: "required", extensions: {prf: {eval: {first: salt}}}})?).prf.first
  let key = wrapKey(out)?
  ids = [...ids, made.id]
  said = `${ids.length} registered (${made.attachment == "cross-platform" ? "a security key" : "this device"}), a key of ${key.length} bytes`

// One touch of any of them.
action unlock
  let got = passkey.get({allowCredentials: ids.map(id => ({id})), userVerification: "required", extensions: {prf: {eval: {first: salt}}}})?
  let key = wrapKey(got.prf.first)?
  said = `unlocked by passkey ${ids.indexOf(got.id) + 1}, a key of ${key.length} bytes`

column gap=8 padding=16
  button "Add a passkey" press=enroll
  button "Unlock" press=unlock
  text `${said}${failure(enroll) ?? ""}${failure(unlock) ?? ""}`
```

A record such a vault keeps (a device key wrapped once per passkey under a
key HKDF makes of that passkey's PRF output, an escrow of it under the vault
key, the secrets sealed under it, each with
[`crypto.aes`](data.md#keys-of-the-pages-own) and `crypto.hkdf`) is
written in Mote in `tests/passkey/device.mote`, where it round-trips.

## Tested

- `tests/all.sh real_totp`: RFC 4226 appendix D and RFC 6238 appendix B
  (SHA-1, SHA-256, SHA-512), turning it on, a password that owes it, a code
  taken once, the steps around now, recovery codes, ten wrong codes,
  `secondFactor(10)` before and after ten minutes; then QR codes of 1 to 200
  characters (versions 1 to 10) read back in Chrome by Mote's reader and by
  the browser's own.
- `tests/all.sh real_passkey`: a pretend authenticator written in Mote
  (ES256, RS256, EdDSA), and every answer made to be refused (another
  origin, another RP ID, another challenge, a challenge used twice or too
  late, nobody there, no UV, another key's signature, a counter that went
  back, another's user handle, a create for a get); then the same page in
  Chrome with its virtual authenticator (CTAP2), through `passkey.create`
  and `passkey.get`: made, signed in with, a call that asks for a factor.
  The WebAuthn specification's own examples were not to hand: Chrome's
  authenticator is the check that shares no code with this one.
- `tests/all.sh real_passkey_prf`: the device record round-tripped (`mote
  test`, an authenticator's PRF written out as HMAC-SHA-256); the extension's tests under a
  program that says `passkeyMax` 2, `passkeyPrf`, `passkeyAttestation`
  `"direct"` and a `passkeyMay` that refuses one AAGUID; then Chrome with
  two virtual authenticators that have the PRF, one the device's and one a
  security key, in a page with no back end (served as files) and in one
  with it: two passkeys made, an assertion answered by either, the same key
  from the same passkey and salt each time, another for another salt,
  `evalByCredential`, `second`, an authenticator not let make a second,
  a third passkey refused, the PRF output absent from what the back end is
  sent and from its log.
- `tests/all.sh real_attest`: certificates and chains (above, and
  [data.md](data.md#certificates-read-whole-and-their-chains)); each
  attestation format made by a pretend authenticator with certificates
  OpenSSL makes for the run (`tests/attest/make.sh`), through
  `passkeyRegisterFinish`, up to roots named as PEM text and as a folder,
  and each made to be refused (another signature, alg, AAGUID, certificate,
  nonce, challenge, `allApplications`, public area, `extraData`, magic,
  key); a chain that reaches no root; a program of security keys only
  that refuses self attestation, none, a synced passkey and an
  unrooted key, and takes an attested one; BLOBs of the Metadata Service
  made and signed in the test (one that holds, its statuses, an older one,
  another root, another signature, a payload changed); then Chrome's
  virtual authenticators (CTAP2 over USB and internal, and U2F): `packed`
  with an `x5c` of Chrome's own test certificate and `fido-u2f`, a second
  key attested once the first's certificate is named as the root, a
  synced passkey and an unrooted U2F key refused under the policy; then
  py_webauthn's fixtures of real authenticators (a YubiKey's `packed` and
  `fido-u2f`, the FIDO conformance tools' `fido-u2f`, four Windows TPMs,
  RSA and ECC, an iPhone's `apple`, two Pixels' `android-key`), fetched at
  a pinned commit with a SHA-256 check by `tests/attest/fetch.sh` (not
  kept in the repository), each statement checked and each chain up to
  Apple's WebAuthn root and Google's hardware attestation roots at the
  time it was made.
- Not met: a phone, a security key, iCloud Keychain or Google Password
  Manager. To check one, serve the page over https at its domain (passkeys
  need a secure origin; `localhost` counts), set `PASSKEY_RP_ID`, make one
  and sign in with it, and see `passkeyList()`.
