~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1427 lines · 89.5 KB Raw History
// Passkeys (spec/PASSKEYS.md), on the server alone: the reference has none.
// Each passkey, and each answer of a ceremony, is the harness's own
// authenticator's (lib/webauthn.mjs), written byte by byte, so that every
// refusal can be made with one thing wrong and the rest as a browser makes
// it. The passkey page is loaded and the API called as lib/oauth.mjs's
// browser does, from the issuer's origin. The routes' auth and what they
// refuse; adding through a link and its page; signing in, for each issuer,
// and each way a sign-in is refused; removing; the account's states; with
// --commands, the routes' tools and commands; and, in a run with crashes,
// what was added, removed and signed in before a restart, after it. Each
// check makes accounts of its own, on both sides alike, and changes their
// states on both sides alike; their passkeys are the server's alone.

import { randomBytes } from 'node:crypto'
import { isDeepStrictEqual } from 'node:util'
import { COMMANDS, STORE } from '../lib/args.mjs'
import { ADMIN_PASSWORD } from '../lib/env.mjs'
import { checkMail } from '../lib/mail.mjs'
import { Browser, Dpop, answer, form, fresh, newKey, pkce, signInCall, target } from '../lib/oauth.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { below, chance, pick } from '../lib/random.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts, didOf, nextBatch, tokenOf } from '../lib/state.mjs'
import { issuer, own, pageApi } from '../lib/server.mjs'
import { MCP_LEGACY, MCP_VERSION, PASSKEY_ROUTES, viaRouteCommand, viaRouteTool } from '../lib/via.mjs'
import { assertion, b64u, cbor, coseKey, newPasskey, onCurve, otherKey, registration, rsa, rsaKey, sha256 } from '../lib/webauthn.mjs'
import { both, normalize, shown, xrpc, xrpcHttp } from '../lib/xrpc.mjs'
import { createAccount } from './accounts.mjs'
import { setEmailFactor } from './email.mjs'
import { mcpPage, mcpRedeem, mcpSession, mcpToolCall } from './oauth-mcp.mjs'

/// Passkeys are Monolith's own (spec/PASSKEYS.md), and the checks sign in
/// through the reference's page API.
export const passkeysAble = () => own() && pageApi()
const able = passkeysAble

const LIST = '_passkeyList'
const ADD = '_passkeyAdd'
const REMOVE = '_passkeyRemove'
const ROUTES = [LIST, ADD, REMOVE]
/// A route's HTTP method, and the other one (spec/PASSKEYS.md).
const methodOf = (route) => (route === LIST ? 'GET' : 'POST')
const otherMethod = (route) => (methodOf(route) === 'GET' ? 'POST' : 'GET')

/// The sections of spec/PASSKEYS.md, cited as they are.
const CITE = {
  rp: 'spec/PASSKEYS.md, "The relying party"',
  auth: 'spec/PASSKEYS.md, "Auth"',
  requests: 'spec/PASSKEYS.md, "Requests"',
  list: 'spec/PASSKEYS.md, "_passkeyList"',
  add: 'spec/PASSKEYS.md, "_passkeyAdd"',
  remove: 'spec/PASSKEYS.md, "_passkeyRemove"',
  page: 'spec/PASSKEYS.md, "The passkey page"',
  register: 'spec/PASSKEYS.md, "passkey-register"',
  signing: 'spec/PASSKEYS.md, "Signing in"',
  options: 'spec/PASSKEYS.md, "passkey-options"',
  signIn: 'spec/PASSKEYS.md, "passkey-sign-in"',
  states: 'spec/PASSKEYS.md, "The account\'s states"',
  durability: 'spec/PASSKEYS.md, "Durability"',
}

const JSON_TYPE = 'application/json; charset=utf-8'
const FORBIDDEN = { status: 403, error: 'Forbidden', message: 'OAuth credentials are not supported for this endpoint' }
const INVALID_TOKEN = { status: 400, error: 'InvalidToken' }
const INVALID_REQUEST = { status: 400, error: 'InvalidRequest' }
/// A link's life, and a passkey's most (spec/PASSKEYS.md, "_passkeyAdd").
const LINK_MS = 900 * 1000
const MOST = 20
/// A datetime in UTC with milliseconds (spec/PASSKEYS.md, "_passkeyList").
const TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
/// The transports a passkey keeps (spec/PASSKEYS.md, "passkey-register").
const TRANSPORTS = ['usb', 'nfc', 'ble', 'smart-card', 'hybrid', 'internal']

/// The server failing what `cite` cites of spec/PASSKEYS.md.
const broke = (cite, what, request, want, got) => differ(`the server's ${what}`, request, want, got, cite)
/// The server failing a step of OAuth's flow these checks take.
const flowBroke = (what, request, want, got) => differ(`the server's ${what}`, request, want, got, 'spec/OAUTH.md, signing in for spec/PASSKEYS.md\'s checks')

const bearer = (token) => `Bearer ${token}`
const iso = ([lo, hi]) => `${new Date(lo).toISOString()} to ${new Date(hi).toISOString()}`
/// Whether `t` is a datetime within a second of the window `[lo, hi]`.
const near = (t, [lo, hi]) => typeof t === 'string' && TIME.test(t) && Date.parse(t) >= lo - 1000 && Date.parse(t) <= hi + 1000
/// Whether `s` is `n` bytes as base64url without padding (spec/PASSKEYS.md,
/// "The relying party": "Encoding").
const bytesOf = (s, n) => typeof s === 'string' && /^[A-Za-z0-9_-]*$/.test(s) && Buffer.from(s, 'base64url').length === n && Buffer.from(s, 'base64url').toString('base64url') === s
/// A name of its own, as `_passkeyAdd` takes one.
const newName = () => pick(['Laptop', 'Phone', 'Security key', 'Ключ', '🔑 passkey', 'Work laptop'])

/// The RP ID: the issuer's host, without its port; and the origin, the
/// issuer itself (spec/PASSKEYS.md, "The relying party").
export const rpId = () => new URL(issuer(cand)).hostname
export const origin = () => issuer(cand)
/// The issuer's origin with another port.
const otherPort = () => {
  const u = new URL(origin())
  u.port = String(Number(u.port || (u.protocol === 'https:' ? 443 : 80)) === 9 ? 10 : 9)
  return u.origin
}

// --------------------------------------------------------------- accounts

/// Each account's user handle, by DID, as the first page of a link of it
/// gave it: the same for all its links and passkeys, before its first
/// passkey and after, after a password reset and a restart, and of no
/// other account (spec/PASSKEYS.md, "The relying party").
const handles = new Map()

/// An account as these checks take it: its DID, handle and password
/// session on the server, read as they are now; the passkeys the harness
/// added it and knows it still has; and whether it is the harness's own, so
/// that it has no profile (`bare`).
export function whoOf(acct, { bare = false } = {}) {
  return {
    acct,
    get did() {
      return didOf(cand, acct)
    },
    get handle() {
      return acct.handle
    },
    get token() {
      return tokenOf(cand, acct)
    },
    label: `<did:${acct.n}>`,
    bare,
    passkeys: [],
    others: [],
  }
}

/// An account of the server alone, as `whoOf` gives one: `{did, handle,
/// token}`, with no profile.
export function serverWho({ did, handle, token }) {
  return { did, handle, token, label: handle, bare: true, passkeys: [], others: [] }
}

/// Two accounts of their own, with passwords, on both sides alike; or null.
async function twoAccounts() {
  const a = await createAccount({ withPassword: true })
  const b = a && (await createAccount({ withPassword: true }))
  return b ? [whoOf(a, { bare: true }), whoOf(b, { bare: true })] : null
}

/// A session of `acct` made with an app password of its own, made on both
/// sides alike so that their app passwords stay the same: its access token
/// on the server (spec/SESSIONS.md), or null.
async function appPasswordToken(acct) {
  const nsid = 'com.atproto.server.createAppPassword'
  const request = { token: acct, body: { name: `passkeys-${nextBatch()}` } }
  const [a, b] = await Promise.all([xrpc(ref, nsid, request), xrpc(cand, nsid, request)])
  const masked = (side, res) => {
    const n = normalize(side, res, nsid)
    return n.status === 200 ? { ...n, body: { ...n.body, password: '<password>', createdAt: '<createdAt>' } } : n
  }
  const [na, nb] = [masked(ref, a), masked(cand, b)]
  if (!isDeepStrictEqual(na, nb)) await differ(nsid, shown(request), na, nb)
  if (b.status !== 200) return null
  const s = await xrpcHttp(cand, 'com.atproto.server.createSession', { body: { identifier: didOf(cand, acct), password: b.body.password } })
  if (s.status !== 200) return void (await flowBroke('createSession with an app password', { account: `<did:${acct.n}>` }, 200, s))
  return s.body.accessJwt
}

const basic = (user, password) => `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`
const adminOf = (side) => (side === ref ? basic('admin', ADMIN_PASSWORD) : cand.admin)

/// The admin applies or lifts the account's takedown on both sides alike,
/// compared; then, lifted, the account signs in again on both, as a
/// takedown ends its password sessions (spec/LIFECYCLE.md,
/// "updateSubjectStatus").
async function takedownBoth(who, applied) {
  const nsid = 'com.atproto.admin.updateSubjectStatus'
  const send = async (side) => answer(await fetch(`${side.url}/xrpc/${nsid}`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: adminOf(side) }, body: JSON.stringify({ subject: { $type: 'com.atproto.admin.defs#repoRef', did: didOf(side, who.acct) }, takedown: { applied } }) }))
  const [a, b] = await Promise.all([ref, cand].map(send))
  const [na, nb] = [normalize(ref, a, nsid), normalize(cand, b, nsid)]
  if (!isDeepStrictEqual(na, nb)) await differ(nsid, { subject: who.label, takedown: { applied } }, na, nb)
  count(`passkeys: updateSubjectStatus, takedown ${applied ? 'applied' : 'lifted'}`, a.status < 400)
  if (!applied) await newSessions(who, 'after a takedown is lifted')
}

/// createSession on both sides alike, the account carrying on with the new
/// sessions.
async function newSessions(who, why) {
  const acct = who.acct
  const [a, b] = await both(`createSession ${why} (passkeys)`, 'com.atproto.server.createSession', { body: { identifier: acct.handle, password: acct.password } })
  if (a.status === 200 && b.status === 200) {
    acct.sides.reference = { ...acct.sides.reference, token: a.body.accessJwt, refresh: a.body.refreshJwt }
    acct.sides.server = { ...acct.sides.server, token: b.body.accessJwt, refresh: b.body.refreshJwt }
  }
}

// ----------------------------------------------------------------- routes

/// A call of `route` on the server: by its method, or `method`; with
/// `auth`'s `authorization` as the whole header, or its OAuth session's
/// access token as DPoP with a proof; `body` sent as it is, with `type` as
/// its Content-Type (JSON's when there is a body); `query` after the path.
/// Answers its status, Content-Type and body.
async function call(route, { auth = {}, method = methodOf(route), body, type = body === undefined ? undefined : 'application/json', query = '' } = {}) {
  const headers = type ? { 'content-type': type } : {}
  if (auth.oauth) {
    const r = await auth.oauth.dpop.send(`${origin()}/xrpc/${route}${query}`, { method, headers, body, accessToken: auth.oauth.access })
    return { status: r.status, type: r.headers['content-type'] ?? null, body: r.body }
  }
  if (auth.authorization) headers.authorization = auth.authorization
  try {
    const r = await answer(await fetch(`${cand.url}/xrpc/${route}${query}`, { method, headers, body }))
    return { status: r.status, type: r.headers['content-type'] ?? null, body: r.body }
  } catch (err) {
    return { status: 0, type: null, body: { error: `request failed: ${err.message}` } }
  }
}

const password = (who) => ({ authorization: bearer(who.token) })

/// An answer as the auth and request checks hold it.
const refusal = (res, want) => ({ status: res.status, error: res.body?.error ?? null, ...(want.message ? { message: res.body?.message ?? null } : {}) })

/// `_passkeyRemove` of `id` with the account's password session: `200 {}`
/// (spec/PASSKEYS.md, "_passkeyRemove").
async function removeOf(who, id, what, cite = CITE.remove) {
  const input = { id, ...(chance(0.2) ? { reason: 'harness' } : {}) }
  const res = await call(REMOVE, { auth: password(who), body: JSON.stringify(input) })
  if (res.status !== 200 || res.type !== JSON_TYPE || !isDeepStrictEqual(res.body, {})) await broke(cite, `${REMOVE} of ${what}`, { account: who.label, input }, { status: 200, type: JSON_TYPE, body: {} }, res)
}

/// Forget `pk` as one of the account's passkeys.
const forget = (who, pk) => (who.passkeys = who.passkeys.filter((x) => x !== pk))

const LIST_KEYS = ['backedUp', 'createdAt', 'id', 'lastUsedAt', 'name']

/// `_passkeyList` of the account held to the passkeys the harness added it:
/// with `exact`, those of `want` and no other, else those among others;
/// none of `gone`. Each with its name, `createdAt` within a second of its
/// `passkey-register`, `lastUsedAt` of its last sign-in or left out, and
/// `backedUp` the BS last given; the latest `createdAt` first, then by `id`
/// (spec/PASSKEYS.md, "_passkeyList").
export async function checkList(who, what, want = who.passkeys, { exact = true, gone = [], cite = CITE.list } = {}) {
  const request = { account: who.label, at: what }
  const res = await call(LIST, { auth: password(who) })
  const list = res.body?.passkeys
  if (res.status !== 200 || res.type !== JSON_TYPE || !Array.isArray(list) || Object.keys(res.body).length !== 1) return broke(cite, `${LIST} ${what}`, request, { status: 200, type: JSON_TYPE, body: { passkeys: '[…]' } }, res)
  for (const x of list) {
    const keys = Object.keys(x ?? {})
    const fine = keys.every((k) => LIST_KEYS.includes(k)) && ['id', 'name', 'createdAt', 'backedUp'].every((k) => keys.includes(k)) && typeof x.id === 'string' && typeof x.name === 'string' && TIME.test(x.createdAt) && (x.lastUsedAt === undefined || TIME.test(x.lastUsedAt)) && typeof x.backedUp === 'boolean'
    if (!fine) await broke(CITE.list, `${LIST} ${what}`, request, '{id, name, createdAt, lastUsedAt?, backedUp}, the datetimes in UTC with milliseconds', x)
  }
  const order = [...list].sort((a, b) => (a.createdAt < b.createdAt ? 1 : a.createdAt > b.createdAt ? -1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0)).map((x) => x.id)
  if (!isDeepStrictEqual(list.map((x) => x.id), order)) await broke(CITE.list, `${LIST} ${what}`, request, 'the latest createdAt first, then by id', list)
  if (exact && list.length !== want.length) await broke(cite, `${LIST} ${what}`, request, `exactly its ${want.length} passkeys: ${want.map((pk) => b64u(pk.id).slice(0, 12)).join(', ')}`, list)
  for (const pk of want) {
    const id = b64u(pk.id)
    const x = list.find((y) => y.id === id)
    const wanted = { id, name: pk.name, createdAt: `within a second of ${iso(pk.created)}`, lastUsedAt: pk.used ? `within a second of ${iso(pk.used)}` : 'left out', backedUp: pk.backedUp }
    if (!x) {
      await broke(cite, `${LIST} ${what}`, request, wanted, 'not listed')
      continue
    }
    const fine = x.name === pk.name && near(x.createdAt, pk.created) && (pk.used ? near(x.lastUsedAt, pk.used) : x.lastUsedAt === undefined) && x.backedUp === pk.backedUp
    if (!fine) await broke(cite, `${LIST} ${what}`, request, wanted, x)
  }
  for (const pk of gone) if (list.some((y) => y.id === b64u(pk.id))) await broke(cite, `${LIST} ${what}`, request, `no passkey ${b64u(pk.id).slice(0, 12)}…: removed, or another account's`, list)
  return list
}

// ------------------------------------------------------------------ links

/// The link's token in `url`, if it is `<issuer>/oauth/passkey?token=` and
/// 32 bytes as base64url (spec/PASSKEYS.md, "_passkeyAdd"); else null.
function linkToken(url) {
  const prefix = `${origin()}/oauth/passkey?token=`
  if (typeof url !== 'string' || !url.startsWith(prefix)) return null
  const t = url.slice(prefix.length)
  return bytesOf(t, 32) ? t : null
}

/// Whether `body` is `_passkeyAdd`'s answer made within `[lo, hi]`: `{url,
/// expiresAt}`, the link's token 32 bytes, `expiresAt` 900 seconds on
/// (spec/PASSKEYS.md, "_passkeyAdd").
const linkShaped = (body, [lo, hi]) => body && typeof body === 'object' && isDeepStrictEqual(Object.keys(body).sort(), ['expiresAt', 'url']) && linkToken(body.url) !== null && near(body.expiresAt, [lo + LINK_MS, hi + LINK_MS])

/// `_passkeyAdd` of `name` for the account: a link, held to the spec
/// (spec/PASSKEYS.md, "_passkeyAdd"). Answers `{url, token, expiresAt,
/// name, who}`, or null.
export async function addLink(who, name = newName(), { body, cite = CITE.add } = {}) {
  const input = body ?? JSON.stringify({ name, ...(chance(0.2) ? { note: 'ignored' } : {}) })
  const before = Date.now()
  const res = await call(ADD, { auth: password(who), body: input })
  const at = [before, Date.now()]
  if (res.status !== 200 || res.type !== JSON_TYPE || !linkShaped(res.body, at)) return broke(cite, `${ADD} of ${JSON.stringify(name).slice(0, 80)}`, { account: who.label }, { status: 200, type: JSON_TYPE, body: { url: `${origin()}/oauth/passkey?token=<32 random bytes, base64url>`, expiresAt: `900 seconds on: ${iso([at[0] + LINK_MS, at[1] + LINK_MS])}` } }, res)
  return { url: res.body.url, token: linkToken(res.body.url), expiresAt: res.body.expiresAt, name, who }
}

/// The passkey page of `url` loaded on `b` as a navigation, with `headers`
/// (one `undefined`, left out) over a browser's.
const loadPage = (b, url, headers = {}) => b.navigate(url, { site: 'none', headers })

/// Whether `r` is the error page `invalid_request`, `400` (spec/OAUTH.md,
/// "The authorization page").
const errorPage = (r) => r.status === 400 && r.data.__errorData?.error === 'invalid_request'

/// The passkey page of a link that holds, on `b`, held to the spec: `200`,
/// `Cache-Control: no-store`, the `csrf-token` cookie and no other, and one
/// statement, `__passkeyData`, of the account, the link's name and end, and
/// the registration's options, member by member: the RP, the account's
/// user handle (the same for each of its links, of no other account), the
/// link's challenge, ES256, `excludeCredentials` the account's passkeys,
/// with the transports each kept (spec/PASSKEYS.md, "The passkey page").
/// Answers `{challenge, userHandle}`, or null.
export async function checkPage(b, link, what, cite = CITE.page) {
  const { who } = link
  const r = await loadPage(b, link.url)
  const request = { account: who.label, link: what }
  const cookies = (r.headers['set-cookie'] ?? []).map((c) => c.split('=')[0].trim())
  const csrf = (r.headers['set-cookie'] ?? []).find((c) => c.startsWith('csrf-token='))
  const head = { status: r.status, 'cache-control': r.headers['cache-control'] ?? null, cookies, csrf: csrf ?? null, statements: Object.keys(r.data) }
  const headOk = r.status === 200 && head['cache-control'] === 'no-store' && cookies.every((c) => c === 'csrf-token') && b.jar.has('csrf-token') && (!csrf || (/;\s*samesite=lax/i.test(csrf) && /;\s*path=\/(;|$)/i.test(csrf) && !/;\s*httponly/i.test(csrf))) && isDeepStrictEqual(head.statements, ['__passkeyData'])
  if (!headOk) return broke(cite, 'passkey page', request, { status: 200, 'cache-control': 'no-store', cookies: 'csrf-token alone (not HttpOnly, SameSite=Lax, Path=/), no device cookies', statements: ['__passkeyData'] }, { ...head, text: r.status === 200 ? undefined : r.text.slice(0, 200) })
  const d = r.data.__passkeyData
  const o = d?.options ?? {}
  const account = d?.account ?? {}
  const { did, handle, ...rest } = account
  const accountOk = did === who.did && handle === who.handle && (who.bare ? Object.keys(rest).length === 0 : Object.entries(rest).every(([k, v]) => ['name', 'picture'].includes(k) && typeof v === 'string'))
  const displayName = typeof account.name === 'string' ? account.name : who.handle
  // Those the harness added, whole; those it found the account had
  // (`others`), by their IDs, their transports not known to it.
  const exclude = (xs) => [...xs].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
  const wantExclude = exclude(who.passkeys.map((pk) => ({ type: 'public-key', id: b64u(pk.id), ...(pk.transports.length ? { transports: pk.transports } : {}) })))
  const wantIds = [...wantExclude.map((x) => x.id), ...(who.others ?? [])].sort()
  const excludeOk = (got) => Array.isArray(got) && isDeepStrictEqual(got.map((x) => x?.id).sort(), wantIds) && got.every((x) => x?.type === 'public-key') && isDeepStrictEqual(exclude(got.filter((x) => wantExclude.some((w) => w.id === x.id))), wantExclude)
  const wantOptions = {
    rp: { id: rpId(), name: rpId() },
    user: { id: '<the account\'s user handle, 32 bytes>', name: who.handle, displayName },
    challenge: '<32 random bytes>',
    pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }],
    timeout: 300000,
    excludeCredentials: wantExclude,
    authenticatorSelection: { residentKey: 'required', requireResidentKey: true, userVerification: 'required' },
    attestation: 'none',
  }
  const fine = isDeepStrictEqual(Object.keys(d ?? {}).sort(), ['account', 'expiresAt', 'name', 'options']) && accountOk && d.name === link.name && d.expiresAt === link.expiresAt &&
    isDeepStrictEqual(Object.keys(o).sort(), Object.keys(wantOptions).sort()) && isDeepStrictEqual(o.rp, wantOptions.rp) &&
    isDeepStrictEqual(Object.keys(o.user ?? {}).sort(), ['displayName', 'id', 'name']) && bytesOf(o.user.id, 32) && o.user.name === who.handle && o.user.displayName === displayName &&
    bytesOf(o.challenge, 32) && isDeepStrictEqual(o.pubKeyCredParams, wantOptions.pubKeyCredParams) && o.timeout === 300000 &&
    excludeOk(o.excludeCredentials) &&
    isDeepStrictEqual(o.authenticatorSelection, wantOptions.authenticatorSelection) && o.attestation === 'none'
  if (!fine) return broke(cite, 'passkey page\'s __passkeyData', request, { account: { did: who.label, handle: who.handle, '…': who.bare ? 'nothing more' : 'name and picture when it has them' }, name: link.name, expiresAt: link.expiresAt, options: wantOptions }, d ?? null)
  // The user handle: the account's, the same for each of its links, and of
  // no other account (spec/PASSKEYS.md, "The relying party").
  const kept = handles.get(who.did)
  if (kept && o.user.id !== kept) await broke(CITE.rp, 'passkey page\'s user.id', request, `the account's user handle, ${kept}, as each of its links gives it`, o.user.id)
  const theirs = [...handles].find(([x, h]) => x !== who.did && h === o.user.id)
  if (theirs) await broke(CITE.rp, 'passkey page\'s user.id', request, 'a user handle of no other account', { userHandle: o.user.id, alsoOf: theirs[0] })
  handles.set(who.did, o.user.id)
  return { challenge: o.challenge, userHandle: o.user.id }
}

/// `passkey-register` of `credential` through `link`, from its page on `b`
/// (spec/PASSKEYS.md, "passkey-register"): `{status, json, at}`.
async function registerOn(b, link, credential) {
  const before = Date.now()
  const r = await b.api(link.url, '/passkey-register', { credential })
  return { status: r.status, json: r.json, headers: r.headers, at: [before, Date.now()] }
}

/// Whether `r` is `400 {error, error_description}` of `error`.
const apiRefused = (r, error) => r.status === 400 && r.json?.error === error && typeof r.json?.error_description === 'string' && Object.keys(r.json).length === 2

/// The flags a registration or assertion of `pk` with `f` gave BS.
const bsOf = (pk, f) => (f.BS ?? (pk.be && pk.bs))

/// The transports `given` keeps: the known ones, each once, in their
/// order (spec/PASSKEYS.md, "passkey-register").
const keptOf = (given) => [...new Set((given ?? []).filter((t) => TRANSPORTS.includes(t)))]

/// What the harness knows of `pk` once `passkey-register` added it through
/// `link`, answered within `at`, with `f`.
function added(who, pk, link, page, at, f = {}) {
  pk.userHandle = page.userHandle
  pk.name = link.name
  pk.created = at
  pk.used = null
  pk.stored = f.count ?? pk.count
  pk.backedUp = bsOf(pk, f)
  pk.transports = keptOf(f.transports ?? ['internal', 'hybrid'])
  who.passkeys.push(pk)
}

/// A passkey added to the account through a link of its own, its page and
/// `passkey-register`, all held to the spec: `200 {}`. `opts` are the
/// passkey's (`newPasskey`'s), with `f` what its registration takes.
/// Answers the passkey, or null.
export async function addPasskey(who, { name = newName(), f = {}, ...opts } = {}) {
  const link = await addLink(who, name)
  if (!link) return null
  const b = new Browser()
  const page = await checkPage(b, link, 'a new link')
  if (!page) return null
  const pk = newPasskey({ rpId: rpId(), ...opts })
  const reg = registration(pk, { challenge: page.challenge, origin: origin() }, f)
  const r = await registerOn(b, link, reg.json)
  if (r.status !== 200 || !isDeepStrictEqual(r.json, {})) return broke(CITE.register, 'passkey-register', { account: who.label, credential: 'as a browser makes it' }, { status: 200, body: {} }, { status: r.status, body: r.json })
  added(who, pk, link, page, r.at, f)
  count('passkeys: added', true)
  return pk
}

// ---------------------------------------------------------------- devices

let serial = 0

/// A loopback client of its own (spec/OAUTH.md, "Clients").
export function newClient() {
  serial += 1
  const scope = 'atproto transition:generic'
  const redirect = `http://127.0.0.1:${20000 + (serial % 40000)}/callback`
  return { scope, redirect, clientId: `http://localhost?${new URLSearchParams({ scope, redirect_uri: redirect })}` }
}

/// A browser of its own, with a `User-Agent` of its own sent with each of
/// its requests, and the accounts it has signed in, by DID.
export function newDevice() {
  serial += 1
  const ua = `harness-passkeys/${serial} (${pick(['Macintosh', 'X11; Linux', 'iPhone'])})`
  return { b: new Browser(), ua, headers: { 'user-agent': ua }, signedIn: new Set(), req: null }
}

/// A request of a client of its own PAR'd on the server, with `extra`
/// parameters, as `login_hint` (spec/OAUTH.md, "Pushed authorization
/// requests"): `{client, dpop, pk, page, state}`, or null.
export async function serverRequest(client = newClient(), extra = {}) {
  const dpop = new Dpop(await newKey())
  const pk = pkce()
  const state = fresh()
  const p = form({ client_id: client.clientId, response_type: 'code', redirect_uri: client.redirect, scope: client.scope, state, code_challenge: pk.challenge, code_challenge_method: 'S256', ...extra })
  const parred = await dpop.send(`${origin()}/oauth/par`, { method: 'POST', ...p })
  if (parred.status !== 201) return void (await flowBroke('PAR', { client_id: client.clientId }, 201, { status: parred.status, body: parred.body }))
  const page = `${origin()}/oauth/authorize?${new URLSearchParams({ client_id: client.clientId, request_uri: parred.body.request_uri })}`
  return { client, dpop, pk, page, state }
}

/// A request PAR'd on the server and its authorization page loaded on
/// device `d`, which so has its device cookies and `csrf-token`
/// (spec/OAUTH.md, "The authorization page", "Devices"); `d.req` from then
/// on. Answers the request with the page's answer (`shown`), or null.
export async function parOn(d) {
  const req = await serverRequest()
  if (!req) return null
  const shownPage = await d.b.navigate(req.page, { headers: d.headers })
  if (shownPage.status !== 200) return void (await flowBroke('authorization page', { client_id: req.client.clientId }, 200, { status: shownPage.status, text: shownPage.text.slice(0, 200) }))
  if (!(await pageOptions(d, shownPage))) return null
  d.req = { ...req, shown: shownPage }
  return d.req
}

/// Whether `o` is a challenge's options: exactly `{challenge, rpId,
/// timeout, userVerification, allowCredentials}`, the challenge 32 bytes
/// (spec/PASSKEYS.md, "Signing in").
const optionsShaped = (o) => o && typeof o === 'object' && isDeepStrictEqual(Object.keys(o).sort(), OPTION_KEYS) && bytesOf(o.challenge, 32) && o.rpId === rpId() && o.timeout === 300000 && o.userVerification === 'required' && isDeepStrictEqual(o.allowCredentials, [])
const OPTIONS_WANT = () => ({ challenge: '<32 random bytes, a new one>', rpId: rpId(), timeout: 300000, userVerification: 'required', allowCredentials: [] })

/// The authorization page `shownPage` loaded on device `d`: its
/// `__passkeyOptions` a new challenge's options, the device's challenge
/// from then on (spec/PASSKEYS.md, "The page's options"). Answers the
/// challenge, or null.
async function pageOptions(d, shownPage) {
  const o = shownPage.data.__passkeyOptions
  if (!optionsShaped(o) || o.challenge === d.challenge) return broke('spec/PASSKEYS.md, "The page\'s options"', 'authorization page\'s __passkeyOptions', { device: d.ua, before: d.challenge ?? null }, OPTIONS_WANT(), o ?? null)
  d.challenge = o.challenge
  return o.challenge
}

/// Whether a new authorization page on `d` lists the account
/// (spec/OAUTH.md, "The authorization page"); its options, the device's
/// challenge from then on, held as `pageOptions` holds them.
async function listedOn(d, who) {
  const req = await serverRequest()
  if (!req) return false
  const page = await d.b.navigate(req.page, { headers: d.headers })
  if (page.status === 200) await pageOptions(d, page)
  return (page.data.__sessions ?? []).some((x) => x.account?.did === who.did)
}

const OPTION_KEYS = ['allowCredentials', 'challenge', 'rpId', 'timeout', 'userVerification']

/// `passkey-options` `{}` on device `d`'s page `req`: the options held to
/// the spec, a new challenge, `Cache-Control: no-store` (spec/PASSKEYS.md,
/// "passkey-options"; spec/OAUTH.md, "The API"), the device's challenge
/// from then on. Answers the challenge, or null.
export async function optionsOn(d, req = d.req) {
  const r = await d.b.api(req.page, '/passkey-options', {}, { headers: d.headers })
  const o = r.json?.options
  const fine = r.status === 200 && r.headers['cache-control'] === 'no-store' && isDeepStrictEqual(Object.keys(r.json ?? {}), ['options']) && optionsShaped(o) && o.challenge !== d.challenge
  if (!fine) return broke(CITE.options, 'passkey-options', { device: d.ua, before: d.challenge ?? null }, { status: 200, 'cache-control': 'no-store', body: { options: OPTIONS_WANT() } }, { status: r.status, 'cache-control': r.headers['cache-control'] ?? null, body: r.json })
  d.challenge = o.challenge
  return o.challenge
}

/// `passkey-sign-in` with `credential` on device `d`'s page `req`, with
/// `remember` (left out when undefined): `{status, json, at}`.
export async function signInOn(d, credential, { remember, req = d.req, locale = 'en' } = {}) {
  const before = Date.now()
  const r = await d.b.api(req.page, '/passkey-sign-in', { locale, credential, ...(remember === undefined ? {} : { remember }) }, { headers: d.headers })
  return { status: r.status, json: r.json, headers: r.headers, at: [before, Date.now()] }
}

/// `pk` signs the account in on device `d`, on its page `req`: a challenge
/// of `passkey-options`, the assertion with `f`, and `passkey-sign-in` with
/// `remember`, held to the spec: `{account}` of the account, and an
/// `ephemeralToken` too unless the account is now signed in on the device
/// (spec/PASSKEYS.md, "passkey-sign-in"). The passkey's count, BS and
/// last use, and the device's sign-in, noted. Answers the answer's JSON, or
/// null.
export async function passkeySignIn(who, pk, d, { remember, f = {}, req = d.req, what = 'a passkey sign-in', cite = CITE.signIn, challenge: given } = {}) {
  const challenge = given ?? (await optionsOn(d, req))
  if (!challenge) return null
  const a = assertion(pk, { challenge, origin: origin() }, f)
  const r = await signInOn(d, a.json, { remember, req })
  const stays = remember === true || (remember === undefined && d.signedIn.has(who.did))
  const keys = stays ? ['account'] : ['account', 'ephemeralToken']
  const fine = r.status === 200 && isDeepStrictEqual(Object.keys(r.json ?? {}).sort(), keys) && r.json.account?.did === who.did && (stays || typeof r.json.ephemeralToken === 'string')
  if (!fine) return broke(cite, `passkey-sign-in, ${what}`, { account: who.label, remember: remember ?? 'left out', signedInThere: d.signedIn.has(who.did) }, { status: 200, body: stays ? { account: { did: who.label } } : { account: { did: who.label }, ephemeralToken: '<a string>' } }, { status: r.status, body: r.json })
  pk.stored = a.count
  pk.used = r.at
  pk.backedUp = bsOf(pk, f)
  if (f.BS !== undefined) pk.bs = f.BS
  if (stays) d.signedIn.add(who.did)
  else d.signedIn.delete(who.did)
  count('passkeys: signed in', true)
  return r.json
}

/// What a sign-in refused answers: `400 invalid_request`, with
/// `error_description` as `description` gives it, or any.
const REFUSED = (description) => ({ status: 400, error: 'invalid_request', error_description: description ?? '<any>' })
const refusedAs = (r, description) => r.status === 400 && r.json?.error === 'invalid_request' && typeof r.json?.error_description === 'string' && Object.keys(r.json).length === 2 && (description === undefined || r.json.error_description === description)

/// `passkey-sign-in` with `pk` on device `d` with one thing wrong, `f`, and
/// `remember: true`: refused, `400 invalid_request` (or `description`).
/// `challenge` is the one to sign: by default the device's new one, `null`
/// for none the device holds.
async function signInRefused(who, pk, d, what, f = {}, { challenge, description, cite = CITE.signIn } = {}) {
  const c = challenge === undefined ? await optionsOn(d) : challenge
  if (challenge === undefined && !c) return
  const a = assertion(pk, { challenge: c ?? b64u(randomBytes(32)), origin: origin() }, f)
  const r = await signInOn(d, a.json, { remember: true })
  if (!refusedAs(r, description)) await broke(cite, `passkey-sign-in with ${what}`, { account: who.label }, REFUSED(description), { status: r.status, body: r.json })
  count(`passkeys: sign-in refused, ${what}`, false)
}

/// A sign-in with `pk` on a new device, refused as `signInRefused` holds
/// it, and the account not signed in there.
export async function passkeyRefused(who, pk, what, cite, { f = {}, description } = {}) {
  const d = newDevice()
  if (!(await parOn(d))) return
  await signInRefused(who, pk, d, what, f, { description, cite })
  if (await listedOn(d, who)) await broke(cite, `the authorization page after passkey-sign-in with ${what}`, { account: who.label }, 'not listing the account', 'listing it')
}

/// Consent for the account on `req`'s page on device `d` (with `ephemeral`,
/// its sign-in's token, if it is not signed in there), the redirect, and
/// the code grant (spec/OAUTH.md, "The API", "The redirect", "The token
/// endpoint"). Answers the session, `{dpop, access, refresh}`, or null.
async function approve(who, d, req, ephemeral) {
  const c = await d.b.api(req.page, '/consent', { did: who.did }, { headers: d.headers, bearer: ephemeral })
  const url = c.json?.url
  const back = typeof url === 'string' ? await d.b.navigate(new URL(url, origin()).href, { site: 'same-origin', referer: req.page, headers: d.headers }) : null
  const code = target(back?.headers?.location)?.params?.code
  if (c.status !== 200 || !code) return void (await flowBroke('consent and its redirect, after a passkey sign-in', { account: who.label, ephemeral: Boolean(ephemeral) }, 'a code', { status: c.status, body: c.json, location: back?.headers?.location ?? null }))
  const t = await redeem(req, code)
  if (!t) return null
  return { dpop: req.dpop, access: t.access_token, refresh: t.refresh_token }
}

/// The code grant of `code`, approved for `req` (`serverRequest`'s), at
/// the token endpoint (spec/OAUTH.md, "The token endpoint"): its answer,
/// or null.
export async function redeem(req, code) {
  const t = await req.dpop.send(`${origin()}/oauth/token`, { method: 'POST', ...form({ grant_type: 'authorization_code', client_id: req.client.clientId, redirect_uri: req.client.redirect, code, code_verifier: req.pk.verifier }) })
  if (t.status !== 200 || typeof t.body?.access_token !== 'string') return void (await flowBroke('token: code, after a passkey sign-in', { client_id: req.client.clientId }, 200, { status: t.status, body: t.body }))
  return t.body
}

/// getSession with an OAuth session's access token: the account's.
async function works(who, s, what, cite) {
  const r = await s.dpop.send(`${origin()}/xrpc/com.atproto.server.getSession`, { accessToken: s.access })
  if (r.status !== 200 || r.body?.did !== who.did) await broke(cite, `getSession with ${what}`, { account: who.label }, { status: 200, did: who.label }, { status: r.status, body: r.body })
}

/// The account's devices, as `_oauthDevices` lists them (spec/OAUTH-ACCOUNT.md).
async function devicesOf(who) {
  const r = await call('_oauthDevices', { auth: password(who), method: 'GET' })
  return Array.isArray(r.body?.devices) ? r.body.devices : []
}

/// The account's passkeys, as `_passkeyList` lists them, or null.
export async function passkeysOf(who) {
  const r = await call(LIST, { auth: password(who) })
  return Array.isArray(r.body?.passkeys) ? r.body.passkeys : null
}

// ------------------------------------------------------------------ steps

/// Each route with no token, a token the server did not give out, an app
/// password's session, a refresh token, the admin's `Basic`, and an OAuth
/// access token with its proof: the errors spec/PASSKEYS.md gives, and
/// nothing listed, made or removed; with --commands, an MCP session's token
/// at a `passkey_` tool, `403 Forbidden`. Then, with the password session,
/// the other HTTP method; `_passkeyAdd` and `_passkeyRemove` with no body,
/// a body that is not JSON or not an object, with no `name` or `id`, one
/// not a string, a `name` of 0 and of 65 characters, another Content-Type:
/// `400 InvalidRequest`; a `name` of 64 characters of four bytes each,
/// taken; one of 153601 bytes, `413 PayloadTooLargeError`, and of 153600,
/// answered; `_passkeyList` the same whatever parameters it is given
/// (spec/PASSKEYS.md, "Auth", "Requests").
export async function passkeyAuth() {
  if (!able()) return
  const acct = await createAccount({ withPassword: true })
  if (!acct) return
  const who = whoOf(acct, { bare: true })
  const pk = await addPasskey(who)
  if (!pk) return
  const d = newDevice()
  if (!(await parOn(d)) || !(await passkeySignIn(who, pk, d, { remember: true, what: 'for an OAuth session' }))) return
  const s = await approve(who, d, d.req)
  const app = s && (await appPasswordToken(acct))
  if (!app) return
  const link = await addLink(who)
  if (!link) return
  const input = (route) => (route === ADD ? JSON.stringify({ name: 'refused' }) : route === REMOVE ? JSON.stringify({ id: b64u(pk.id) }) : undefined)
  const t = who.token
  const auths = [
    ['no Authorization header', {}, { status: 401, error: 'AuthMissing' }],
    ['a token the server did not give out', { authorization: bearer(pick([`${t.slice(0, -4)}${t.endsWith('AAAA') ? 'BBBB' : 'AAAA'}`, 'not-a-token'])) }, INVALID_TOKEN],
    ['an app password\'s session', { authorization: bearer(app) }, INVALID_TOKEN],
    ['a refresh token', { authorization: bearer(acct.sides.server.refresh) }, INVALID_TOKEN],
    ['the admin\'s Basic', { authorization: cand.admin }, INVALID_TOKEN],
    ['an OAuth access token, as DPoP with its proof', { oauth: s }, FORBIDDEN],
  ]
  for (const [how, auth, want] of auths) {
    for (const route of ROUTES) {
      const got = refusal(await call(route, { auth, body: input(route) }), want)
      if (!isDeepStrictEqual(got, want)) await broke(CITE.auth, `${route} with ${how}`, { route, auth: how }, want, got)
    }
    // The token is checked before the HTTP method.
    const route = pick(ROUTES)
    const method = otherMethod(route)
    const got = refusal(await call(route, { auth, method, body: method === 'POST' ? input(REMOVE) : undefined }), want)
    if (!isDeepStrictEqual(got, want)) await broke(CITE.auth, `${route} by ${method}, with ${how}`, { route, method, auth: how }, want, got)
  }
  if (COMMANDS) {
    // An MCP session's token at a passkey tool: a tool error, as a method
    // that takes no OAuth token answers it (spec/PASSKEYS.md, "Auth").
    const mcp = await mcpSession('refused at a passkey_ tool', acct)
    if (mcp) {
      const r = pick(PASSKEY_ROUTES)
      const args = r.route === ADD ? { name: 'refused' } : r.route === REMOVE ? { id: b64u(pk.id) } : {}
      const got = await mcpToolCall(r.tool, args, bearer(mcp.access))
      const view = { http: got.http, isError: got.result?.isError ?? null, structuredContent: got.result?.structuredContent ?? null }
      const want = { http: 200, isError: true, structuredContent: { error: FORBIDDEN.error, message: FORBIDDEN.message } }
      if (!isDeepStrictEqual(view, want)) await broke(CITE.auth, `tool ${r.tool} with an MCP session's token`, { tool: r.tool, args }, want, { ...view, challenge: got.challenge, body: got.body })
    }
  }
  await checkList(who, 'after calls refused for their auth', [pk], { cite: CITE.auth })
  await linkHolds(link, 'after _passkeyAdd was refused for its auth', CITE.auth)
  count('passkeys: auth refused', true)

  const auth = password(who)
  for (const route of ROUTES) {
    const method = otherMethod(route)
    const got = refusal(await call(route, { auth, method, ...(method === 'POST' ? { body: '{}' } : { query: `?${new URLSearchParams(route === ADD ? { name: 'x' } : { id: b64u(pk.id) })}` }) }), INVALID_REQUEST)
    if (!isDeepStrictEqual(got, INVALID_REQUEST)) await broke(CITE.requests, `${route} by ${method}`, { route, method }, INVALID_REQUEST, got)
  }
  const id = b64u(pk.id)
  const faults = {
    [ADD]: [
      ['no body', { type: pick([undefined, 'application/json']) }],
      ['a body that is not JSON', { body: pick(['{"name":', 'name=x', '']) }],
      ['a body that is not an object', { body: JSON.stringify(pick([['x'], 'x', 5, null])) }],
      ['no name', { body: JSON.stringify(pick([{}, { Name: 'x' }, { id }])) }],
      ['a name that is not a string', { body: JSON.stringify({ name: pick([5, null, true, ['x'], { name: 'x' }]) }) }],
      ['a name of 0 characters', { body: JSON.stringify({ name: '' }) }],
      ['a name of 65 characters', { body: JSON.stringify({ name: pick(['a'.repeat(65), '🔑'.repeat(65), `${'é'.repeat(64)}x`]) }) }],
      ['another Content-Type', { body: JSON.stringify({ name: 'x' }), type: pick(['text/plain', 'application/x-www-form-urlencoded']) }],
    ],
    [REMOVE]: [
      ['no body', { type: pick([undefined, 'application/json']) }],
      ['a body that is not JSON', { body: pick(['{"id":', `id=${id}`, '']) }],
      ['a body that is not an object', { body: JSON.stringify(pick([[id], id, 5, null])) }],
      ['no id', { body: JSON.stringify(pick([{}, { ID: id }, { name: id }])) }],
      ['an id that is not a string', { body: JSON.stringify({ id: pick([5, null, true, [id], { id }]) }) }],
      ['another Content-Type', { body: JSON.stringify({ id }), type: pick(['text/plain', 'application/x-www-form-urlencoded']) }],
    ],
  }
  for (const [route, list] of Object.entries(faults)) {
    for (const [name, opts] of list) {
      const got = refusal(await call(route, { auth, ...opts }), INVALID_REQUEST)
      if (!isDeepStrictEqual(got, INVALID_REQUEST)) await broke(CITE.requests, `${route} with ${name}`, { route, body: opts.body ?? null, type: opts.type ?? null }, INVALID_REQUEST, got)
    }
  }
  await checkList(who, 'after requests refused', [pk], { cite: CITE.requests })
  await linkHolds(link, 'after _passkeyAdd was refused for its input', CITE.requests)
  // A body past 153600 bytes, before its Content-Type or JSON is looked at:
  // `413`; one of exactly 153600, answered (spec/PASSKEYS.md, "Requests").
  const sized = (n, base) => {
    const head = JSON.stringify({ ...base, pad: '' })
    return JSON.stringify({ ...base, pad: 'x'.repeat(n - head.length) })
  }
  const tooLarge = { status: 413, error: 'PayloadTooLargeError' }
  for (const [route, base] of [[ADD, { name: 'too large' }], [REMOVE, { id }]]) {
    const over = { body: sized(153601, base), type: pick(['application/json', 'text/plain']) }
    const big = refusal(await call(route, { auth, ...over }), tooLarge)
    if (!isDeepStrictEqual(big, tooLarge)) await broke(CITE.requests, `${route} with a body of 153601 bytes`, { route, bytes: 153601, type: over.type }, tooLarge, big)
  }
  await checkList(who, 'after bodies too large', [pk], { cite: CITE.requests })
  await linkHolds(link, 'after a body too large', CITE.requests)
  const full = await call(REMOVE, { auth, body: sized(153600, { id: b64u(randomBytes(32)) }) })
  if (full.status !== 200 || !isDeepStrictEqual(full.body, {})) await broke(CITE.requests, `${REMOVE} with a body of exactly 153600 bytes`, { route: REMOVE, bytes: 153600 }, { status: 200, body: {} }, { status: full.status, body: full.body })
  const fullAdd = await addLink(who, 'exactly 153600 bytes', { body: sized(153600, { name: 'exactly 153600 bytes' }), cite: CITE.requests })
  if (!fullAdd) return
  // A name of 64 characters of four bytes each, 256 bytes of UTF-8.
  const wide = await addLink(who, pick(['🔑', '𝒜', '😀']).repeat(64), { cite: CITE.requests })
  if (!wide || !(await checkPage(new Browser(), wide, 'named with 64 characters of four bytes each', CITE.requests))) return
  const plain = await call(LIST, { auth })
  const query = `?${new URLSearchParams({ limit: String(1 + below(3)), cursor: pick(['x', id]), id })}`
  const given = await call(LIST, { auth, query })
  if (!isDeepStrictEqual(given, plain)) await broke(CITE.requests, `${LIST} with parameters`, { route: LIST, query }, plain, given)
  await checkList(who, 'after the requests', [pk], { cite: CITE.requests })
  count('passkeys: requests refused', true)
}

/// Whether `link` still holds: its page answers.
async function linkHolds(link, what, cite) {
  const r = await loadPage(new Browser(), link.url)
  if (r.status !== 200 || r.data.__passkeyData?.name !== link.name) await broke(cite, `passkey page of a link ${what}`, { account: link.who.label }, { status: 200, __passkeyData: { name: link.name } }, { status: r.status, data: r.data })
}

/// The link ended: its page the error page, and its `passkey-register`
/// `400 access_denied`, adding nothing (spec/PASSKEYS.md, "The passkey
/// page", "passkey-register").
async function linkEnded(link, what, cite = CITE.register) {
  const b = new Browser()
  const r = await loadPage(b, link.url)
  if (!errorPage(r)) await broke(CITE.page, `passkey page of a link ${what}`, { account: link.who.label }, { status: 400, __errorData: { error: 'invalid_request' } }, { status: r.status, data: r.data })
  b.jar.set('csrf-token', randomBytes(12).toString('hex'))
  const pk = newPasskey({ rpId: rpId() })
  const reg = registration(pk, { challenge: b64u(randomBytes(32)), origin: origin() })
  const res = await registerOn(b, link, reg.json)
  if (!apiRefused(res, 'access_denied')) await broke(cite, `passkey-register through a link ${what}`, { account: link.who.label }, { status: 400, error: 'access_denied', error_description: '<any>' }, { status: res.status, body: res.json })
}

/// The registration faults of "How it is checked", each one thing wrong,
/// for the ES256 passkey `pk`, the RSA ones with a key of 2048 bits of
/// their own: `[what, f]`.
function registrationFaults(pk) {
  const { n, e } = rsa(2048)
  const id = b64u(pk.id)
  const off = Buffer.from(pk.y)
  do {
    off[31] ^= 1 << below(8)
  } while (onCurve(pk.x, off))
  const forms = [
    ['id other than rawId', (j) => ({ ...j, id: b64u(randomBytes(pk.id.length)) })],
    ['rawId with padding', (j) => ({ ...j, id: `${id}=`, rawId: `${id}=` })],
    ['no rawId', ({ rawId: _, ...j }) => j],
    ['type other than public-key', (j) => ({ ...j, type: pick(['public-key ', 'webauthn', 'Public-Key']) })],
    ['no type', ({ type: _, ...j }) => j],
    ['no clientDataJSON', (j) => ({ ...j, response: { ...j.response, clientDataJSON: undefined } })],
    ['clientDataJSON not a string', (j) => ({ ...j, response: { ...j.response, clientDataJSON: 5 } })],
    ['attestationObject in base64 with padding', (j) => ({ ...j, response: { ...j.response, attestationObject: `${Buffer.from(j.response.attestationObject, 'base64url').toString('base64')}=` } })],
    ['no attestationObject', (j) => ({ ...j, response: { ...j.response, attestationObject: undefined } })],
    ['transports not an array', (j) => ({ ...j, response: { ...j.response, transports: 'internal' } })],
    ['transports not all strings', (j) => ({ ...j, response: { ...j.response, transports: ['internal', 5] } })],
    ['a response that is not an object', (j) => ({ ...j, response: pick(['x', null, [j.response]]) })],
    ['a credential that is not an object', (j) => pick([JSON.stringify(j), null, [j]])],
  ]
  const [formName, formFn] = pick(forms)
  return [
    [`the credential's form: ${formName}`, { form: formFn }],
    ['type webauthn.get', { type: 'webauthn.get' }],
    ['another challenge', { challenge: b64u(randomBytes(32)) }],
    ['another origin', { origin: pick(['https://example.com', `https://${rpId()}.example.com`, `${new URL(origin()).protocol === 'http:' ? 'https' : 'http'}://${new URL(origin()).host}`]) }],
    ['the issuer with another port', { origin: otherPort() }],
    ['crossOrigin: true', { crossOrigin: true }],
    ['a topOrigin', { topOrigin: pick([origin(), 'https://example.com']) }],
    ['another rpIdHash', { rpIdHash: sha256(pick(['example.com', `${rpId()}.example.com`, rpId() === 'localhost' ? '127.0.0.1' : 'localhost'])) }],
    ['UP clear', { UP: false }],
    ['UV clear', { UV: false }],
    ['BS without BE', { BE: false, BS: true }],
    ['AT clear', { AT: false }],
    ['fmt packed', { fmt: 'packed' }],
    ['a non-empty attStmt', { attStmt: pick([{ alg: -7, sig: randomBytes(70) }, { x: 1 }]) }],
    ['an attestation object with a fourth key', { extraMember: [pick(['ep', 'epAtt', 'largeBlobKey']), pick([true, 1, 'x'])] }],
    ['a byte after the attestation object', { trailing: Buffer.from([pick([0x00, 0xa0, 0xf6])]) }],
    ['a credential ID other than rawId', { credentialId: randomBytes(pk.id.length) }],
    ['a key of alg -257 with kty 2', { key: coseKey(pk.x, pk.y, { over: { 3: -257 } }) }],
    ['a key of alg -7 with kty 3', { key: rsaKey(n, e, { over: { 3: -7 } }) }],
    ['an RS256 key with n of 255 bytes', { key: rsaKey(Buffer.concat([Buffer.from([0xc1]), n.subarray(2)]), e) }],
    ['an RS256 key with n of 513 bytes', { key: rsaKey(Buffer.concat([Buffer.from([0x80 | below(0x80)]), randomBytes(512)]), e) }],
    ['an RS256 key with n\'s first byte zero', { key: rsaKey(Buffer.concat([Buffer.from([0]), n]), e) }],
    ['an RS256 key with e even', { key: rsaKey(n, Buffer.from(pick([[0x01, 0x00, 0x00], [0x02], [0x01, 0x00, 0x02]]))) }],
    ['an RS256 key with e of 1', { key: rsaKey(n, Buffer.from([0x01])) }],
    ['a key of crv 2', { key: coseKey(pk.x, pk.y, { over: { '-1': 2 } }) }],
    ['a key with a sixth member', { key: coseKey(pk.x, pk.y, { extra: [pick([[2, randomBytes(8)], [4, [2]], [-4, randomBytes(32)]])] }) }],
    ['a key off the curve', { key: coseKey(pk.x, off) }],
    ['extensions with ED clear', { extensions: cbor(new Map([['credProtect', 2]])), ED: false }],
    ['ED set and no extensions', { ED: true }],
    ['a byte after the key', { after: Buffer.from([pick([0x00, 0xf6, 0xa0])]) }],
  ]
}

/// Adding (spec/PASSKEYS.md, "How it is checked"): `_passkeyAdd`'s link;
/// its page, loaded twice alike, held member by member, the navigation
/// refused as the authorization page's is, its other methods `404`, and a
/// missing token, a token of no link, and the first link's after a second,
/// each the error page. Then through the second link `passkey-register`
/// refused for each thing wrong (`registrationFaults`), the link still
/// holding, and with the authorization page's `Referer`; then taken, with a
/// byte order mark sometimes, and listed; the link then ended. More with
/// BE and BS set and clear, extensions with ED set, a credential ID of 1023
/// bytes taken and of 1024 refused, transports kept as given, each listed
/// and in `excludeCredentials`; another account's user handle its own, and
/// its passkey of a credential ID the first has, refused; `sign-in` with
/// the passkey page's `Referer` refused. And an account of 20 passkeys:
/// two registrations through one link at once, one taken; `_passkeyAdd`
/// then refused (spec/PASSKEYS.md, "_passkeyAdd", "The passkey page",
/// "passkey-register", "The relying party").
export async function passkeyAdding() {
  if (!able()) return
  const two = await twoAccounts()
  if (!two) return
  const [who, other] = two
  const first = await addLink(who)
  if (!first) return
  const b1 = new Browser()
  const p1 = await checkPage(b1, first, 'a new link')
  const again = p1 && (await checkPage(b1, first, 'loaded again'))
  if (!again) return
  if (again.challenge !== p1.challenge) await broke(CITE.page, 'passkey page loaded again', { account: who.label }, `the same challenge, ${p1.challenge}: loading keeps nothing and ends nothing`, again.challenge)
  // The navigation refused as the authorization page's is; other methods
  // `404` (spec/PASSKEYS.md, "The passkey page"; spec/OAUTH.md, "The
  // authorization page").
  const navs = [
    ['no Sec-Fetch-Mode: navigate', { 'sec-fetch-mode': pick([undefined, 'cors', 'no-cors', 'same-origin']) }],
    ['no Sec-Fetch-Dest: document', { 'sec-fetch-dest': pick([undefined, 'empty', 'iframe']) }],
    ['a Sec-Fetch-Site of no kind', { 'sec-fetch-site': pick([undefined, 'elsewhere']) }],
    ['another Origin', { origin: pick(['https://example.com', otherPort()]) }],
  ]
  for (const [what, headers] of navs) {
    const r = await loadPage(new Browser(), first.url, headers)
    if (!errorPage(r)) await broke(CITE.page, `passkey page with ${what}`, { headers }, { status: 400, __errorData: { error: 'invalid_request' } }, { status: r.status, data: r.data })
  }
  const method = pick(['POST', 'PUT', 'DELETE'])
  const posted = await new Browser().request(first.url, { method, headers: { 'content-type': 'application/json' }, body: method === 'POST' ? '{}' : undefined })
  if (posted.status !== 404) await broke(CITE.page, `${method} /oauth/passkey`, {}, 404, posted.status)
  for (const [what, url] of [['no token', `${origin()}/oauth/passkey`], ['a token of no link', `${origin()}/oauth/passkey?token=${b64u(randomBytes(32))}`], ['an empty token', `${origin()}/oauth/passkey?token=`]]) {
    const r = await loadPage(new Browser(), url)
    if (!errorPage(r)) await broke(CITE.page, `passkey page with ${what}`, { url: url.replace(/token=.*/, 'token=…') }, { status: 400, __errorData: { error: 'invalid_request' } }, { status: r.status, data: r.data })
  }
  await linkHolds(first, 'loaded with its navigation refused', CITE.page)
  const second = await addLink(who)
  if (!second) return
  await linkEnded(first, 'ended by a newer one')
  const b2 = new Browser()
  const p2 = await checkPage(b2, second, 'the second link')
  if (!p2) return
  count('passkeys: the page', true)

  // Each thing wrong, through the second link: refused, nothing added, the
  // link still holding.
  const pk = newPasskey({ rpId: rpId(), be: chance(0.5) })
  for (const [what, f] of registrationFaults(pk)) {
    const reg = registration(pk, { challenge: p2.challenge, origin: origin() }, f)
    const r = await registerOn(b2, second, reg.json)
    if (!apiRefused(r, 'invalid_request')) await broke(CITE.register, `passkey-register with ${what}`, { account: who.label }, { status: 400, error: 'invalid_request', error_description: '<any>' }, { status: r.status, body: r.json })
  }
  // The authorization page's Referer, not the link's.
  const d = newDevice()
  if (!(await parOn(d))) return
  const wrongPage = await d.b.api(d.req.page, '/passkey-register', { credential: registration(pk, { challenge: p2.challenge, origin: origin() }).json }, { headers: d.headers })
  if (!apiRefused(wrongPage, 'invalid_request')) await broke(CITE.register, 'passkey-register with the authorization page\'s Referer', { account: who.label }, { status: 400, error: 'invalid_request', error_description: '<any>' }, { status: wrongPage.status, body: wrongPage.json })
  await checkList(who, 'after registrations refused', [], { cite: CITE.register })
  if (!(await checkPage(b2, second, 'after registrations refused', CITE.register))) return
  count('passkeys: registrations refused', false)

  // Taken, the link then ended.
  const bom = chance(0.5)
  const transports = pick([['internal', 'hybrid'], ['usb', 'nfc', 'usb', 'bogus'], [], ['smart-card', 'ble', 'internal'], ['cable']])
  const f = { bom, transports }
  const reg = registration(pk, { challenge: p2.challenge, origin: origin() }, f)
  const r = await registerOn(b2, second, reg.json)
  if (r.status !== 200 || !isDeepStrictEqual(r.json, {})) return broke(CITE.register, `passkey-register${bom ? ', its client data with a byte order mark' : ''}`, { account: who.label }, { status: 200, body: {} }, { status: r.status, body: r.json })
  added(who, pk, second, p2, r.at, f)
  await checkList(who, 'after a passkey is added', [pk], { cite: CITE.register })
  await linkEnded(second, 'that added a passkey')
  await checkList(who, 'after its link is used again', [pk], { cite: CITE.register })

  // More, each kind of BE and BS, extensions with ED set, a credential ID
  // of 1023 bytes, and the transports each kept.
  const more = [
    [{ be: false, bs: false }, {}],
    [{ be: true, bs: false }, { ED: true, extensions: cbor(new Map([['credProtect', 2]])) }],
    [{ be: true, bs: true, idLength: 1023 }, {}],
    [{ alg: -257, bits: 2048, be: chance(0.5) }, {}],
    [{ alg: -257, bits: 4096, be: chance(0.5) }, {}],
  ]
  for (const [opts, extra] of more) {
    const ts = pick([['internal'], ['hybrid', 'internal', 'hybrid'], [], ['nfc', 'nope', 'usb']])
    if (!(await addPasskey(who, { ...opts, f: { transports: ts, ...extra } }))) return
  }
  await checkList(who, 'with passkeys of each BE and BS', who.passkeys, { cite: CITE.register })
  const third = await addLink(who)
  if (!third || !(await checkPage(new Browser(), third, 'of an account with passkeys'))) return
  // A credential ID of 1024 bytes: refused (spec/PASSKEYS.md, "passkey-register").
  const b3 = new Browser()
  const p3 = await checkPage(b3, third, 'of an account with passkeys, again')
  if (!p3) return
  const long = newPasskey({ rpId: rpId(), idLength: 1024 })
  const lr = await registerOn(b3, third, registration(long, { challenge: p3.challenge, origin: origin() }).json)
  if (!apiRefused(lr, 'invalid_request')) await broke(CITE.register, 'passkey-register with a credential ID of 1024 bytes', { account: who.label }, { status: 400, error: 'invalid_request', error_description: '<any>' }, { status: lr.status, body: lr.json })
  count('passkeys: added, each kind', true)

  // Another account: a user handle of its own; a credential ID the first
  // account has, refused; and `sign-in` with the passkey page's `Referer`.
  const theirs = await addLink(other)
  const bo = new Browser()
  const po = theirs && (await checkPage(bo, theirs, 'of another account'))
  if (!po) return
  const copy = newPasskey({ rpId: rpId() })
  copy.id = Buffer.from(pk.id)
  const dup = await registerOn(bo, theirs, registration(copy, { challenge: po.challenge, origin: origin() }).json)
  if (!apiRefused(dup, 'invalid_request')) await broke(CITE.register, 'passkey-register of a credential ID another account has', { account: other.label }, { status: 400, error: 'invalid_request', error_description: '<any>' }, { status: dup.status, body: dup.json })
  const endpoint = pick([['/sign-in', { locale: 'en', identifier: other.did, password: other.acct.password }], ['/passkey-options', {}], ['/consent', { did: other.did }]])
  for (const [path, input] of [['/sign-in', { locale: 'en', identifier: other.did, password: other.acct.password }], endpoint]) {
    const res = await bo.api(theirs.url, path, input)
    if (!apiRefused(res, 'invalid_request')) await broke(CITE.register, `${path.slice(1)} with the passkey page's Referer`, { account: other.label }, { status: 400, error: 'invalid_request', error_description: '<any>' }, { status: res.status, body: res.json })
  }
  if (!(await addPasskey(other))) return
  await checkList(other, 'after its own passkey, not the first account\'s', other.passkeys, { gone: who.passkeys, cite: CITE.register })
  await checkList(who, 'after another account added its own', who.passkeys, { cite: CITE.register })
  count('passkeys: another account', true)

  await fullAccount()
}

/// An account of 19 passkeys, then a link, and two registrations through
/// it at once: one taken, the other `400 access_denied`, as the first ended
/// the link; 20 listed. `_passkeyAdd` then `400 InvalidRequest`, making no
/// link; one removed, and it makes one again (spec/PASSKEYS.md,
/// "_passkeyAdd", "passkey-register").
async function fullAccount() {
  const acct = await createAccount({ withPassword: true })
  if (!acct) return
  const who = whoOf(acct, { bare: true })
  for (let i = 0; i < MOST - 1; i++) if (!(await addPasskey(who, { name: `key ${i + 1}`, be: chance(0.5) }))) return
  const link = await addLink(who, 'the twentieth')
  const [ba, bb] = [new Browser(), new Browser()]
  const pa = link && (await checkPage(ba, link, 'at 19 passkeys'))
  const pb = pa && (await checkPage(bb, link, 'at 19 passkeys, in a second browser'))
  if (!pb) return
  const [ka, kb] = [newPasskey({ rpId: rpId() }), newPasskey({ rpId: rpId() })]
  const [ra, rb] = await Promise.all([registerOn(ba, link, registration(ka, { challenge: pa.challenge, origin: origin() }).json), registerOn(bb, link, registration(kb, { challenge: pb.challenge, origin: origin() }).json)])
  const taken = [ra, rb].filter((r) => r.status === 200 && isDeepStrictEqual(r.json, {}))
  const other = [ra, rb].find((r) => r !== taken[0])
  if (taken.length !== 1 || !apiRefused(other, 'access_denied')) return broke(CITE.register, 'two passkey-register through one link at once', { account: who.label, passkeys: 19 }, 'one 200 {}, the other 400 access_denied: a link adds one passkey', [ra, rb].map((r) => ({ status: r.status, body: r.json })))
  added(who, taken[0] === ra ? ka : kb, link, pa, taken[0].at)
  await checkList(who, 'at 20 passkeys', who.passkeys, { cite: CITE.register })
  const res = await call(ADD, { auth: password(who), body: JSON.stringify({ name: 'the twenty-first' }) })
  const got = refusal(res, INVALID_REQUEST)
  if (!isDeepStrictEqual(got, INVALID_REQUEST)) await broke(CITE.add, `${ADD} of an account that has 20 passkeys`, { account: who.label }, INVALID_REQUEST, res)
  await checkList(who, 'after the twenty-first was refused', who.passkeys, { cite: CITE.add })
  const gone = pick(who.passkeys)
  await removeOf(who, b64u(gone.id), 'one of 20')
  forget(who, gone)
  if (!(await addPasskey(who, { name: 'the twentieth again' }))) return
  await checkList(who, 'at 20 again', who.passkeys, { gone: [gone], cite: CITE.add })
  count('passkeys: 20 at most', true)
}

/// Signing in (spec/PASSKEYS.md, "How it is checked"): `passkey-options`'
/// options, a new challenge each call, and with no device cookies `400
/// invalid_request`. `passkey-sign-in` with `remember: true`: `{account}`,
/// as `sign-in` answers it, the page then listing it, `_passkeyList` its
/// `lastUsedAt`, `_oauthDevices` the device; `remember` left out there,
/// still signed in; with `remember: false`, and left out on a new device,
/// an `ephemeralToken` that `consent` takes, the account not listed; each
/// through to a code and a token, for each issuer. Accepted too: a
/// signature with `s` in the upper half, BS changed, extensions with ED
/// set, a byte order mark, and a passkey whose count is always zero, twice.
/// With the email factor on, signed in with no code and nothing mailed
/// (spec/PASSKEYS.md, "passkey-options", "passkey-sign-in", "Signing in").
export async function passkeySigningIn() {
  if (!able()) return
  const acct = await createAccount({ withPassword: true })
  if (!acct) return
  const who = whoOf(acct, { bare: true })
  const pk = await addPasskey(who, { be: true, bs: chance(0.5) })
  const zero = pk && (await addPasskey(who, { counting: false, be: chance(0.5) }))
  if (!zero) return

  // passkey-options: a new challenge each call; refused with no device
  // cookies, or with cookies the server did not set.
  const d = newDevice()
  if (!(await parOn(d))) return
  const c1 = await optionsOn(d)
  const c2 = c1 && (await optionsOn(d))
  if (!c2) return
  if (c1 === c2) await broke(CITE.options, 'passkey-options called twice', {}, 'a new challenge each call', [c1, c2])
  const bare = new Browser()
  bare.jar.set('csrf-token', randomBytes(12).toString('hex'))
  if (chance(0.5)) for (const [k, v] of d.b.jar) if (k !== 'csrf-token') bare.jar.set(k, `${v.slice(0, -2)}${v.endsWith('xx') ? 'yy' : 'xx'}`)
  const none = await bare.api(d.req.page, '/passkey-options', {})
  if (!apiRefused(none, 'invalid_request')) await broke(CITE.options, 'passkey-options with no device cookies, or ones the server did not set', {}, { status: 400, error: 'invalid_request', error_description: '<any>' }, { status: none.status, body: none.json })
  count('passkeys: options', true)

  // The page's options: a new challenge each load, which passkey-sign-in
  // takes from that device; a later load, or passkey-options, replaces it,
  // and the one replaced is refused (spec/PASSKEYS.md, "The page's
  // options").
  const pageCite = 'spec/PASSKEYS.md, "The page\'s options"'
  const p = newDevice()
  const first = (await parOn(p)) && p.challenge
  const second = first && (await parOn(p)) && p.challenge
  if (!second) return
  await signInRefused(who, zero, p, 'the challenge of a page loaded before the last', {}, { challenge: first, cite: pageCite })
  const loaded = (await parOn(p)) && p.challenge
  if (!loaded || !(await optionsOn(p))) return
  await signInRefused(who, zero, p, 'the challenge of a page, passkey-options called since', {}, { challenge: loaded, cite: pageCite })
  const taken = (await parOn(p)) && p.challenge
  if (!taken || !(await passkeySignIn(who, zero, p, { challenge: taken, remember: chance(0.5), what: 'with the challenge of the page it loaded', cite: pageCite }))) return
  count('passkeys: the page\'s options', true)

  // As sign-in answers the account (spec/PASSKEYS.md, "passkey-sign-in").
  const pw = await signInCall(origin(), { locale: 'en', identifier: who.did, password: acct.password })
  if (pw.status !== 200) return flowBroke('sign-in with the password', { account: who.label }, 200, { status: pw.status, body: pw.json })
  const remembered = await passkeySignIn(who, pk, d, { remember: true, what: 'remembered', f: chance(0.5) ? { high: true } : {} })
  if (!remembered) return
  if (!isDeepStrictEqual(remembered.account, pw.json.account)) await broke(CITE.signIn, 'passkey-sign-in\'s account', { account: who.label }, pw.json.account, remembered.account)
  const s1 = await approve(who, d, d.req)
  if (!s1) return
  await works(who, s1, 'a session of a passkey sign-in', CITE.signIn)
  if (!(await listedOn(d, who))) await broke(CITE.signIn, 'authorization page after passkey-sign-in with remember: true', { account: who.label }, 'listing the account', 'not listing it')
  await checkList(who, 'after a sign-in', [pk, zero], { cite: CITE.signIn })
  const devs = (await devicesOf(who)).filter((x) => x.userAgent === d.ua)
  if (devs.length !== 1 || !near(devs[0].signedInAt, pk.used)) await broke(CITE.signIn, '_oauthDevices after passkey-sign-in with remember: true', { account: who.label }, { userAgent: d.ua, signedInAt: `within a second of ${iso(pk.used)}` }, devs)
  // Left out on the device it is signed in on: still signed in; with an `s`
  // in the upper half sometimes, BS changed when BE is set.
  if (!(await parOn(d))) return
  const kept = await passkeySignIn(who, pk, d, { what: 'remember left out, signed in there', f: { high: chance(0.5), BS: !pk.bs } })
  if (!kept || !(await approve(who, d, d.req))) return
  await checkList(who, 'after BS changed', [pk, zero], { cite: CITE.signIn })
  count('passkeys: remembered', true)

  // Not remembered: an ephemeral token consent takes, the account not
  // listed, and no device.
  for (const remember of [false, undefined]) {
    const e = newDevice()
    if (!(await parOn(e))) return
    const f = pick([{}, { bom: true }, { ED: true, extensions: cbor(new Map([['credProtect', 1]])) }])
    const signed = await passkeySignIn(who, pick([pk, zero]), e, { remember, f, what: remember === false ? 'remember: false' : 'remember left out, on a new device' })
    if (!signed) return
    const s = await approve(who, e, e.req, signed.ephemeralToken)
    if (!s) return
    await works(who, s, 'a session of a passkey sign-in not remembered', CITE.signIn)
    if (await listedOn(e, who)) await broke(CITE.signIn, `authorization page after passkey-sign-in with remember ${remember ?? 'left out'}`, { account: who.label }, 'not listing the account', 'listing it')
    if ((await devicesOf(who)).some((x) => x.userAgent === e.ua)) await broke(CITE.signIn, `_oauthDevices after passkey-sign-in with remember ${remember ?? 'left out'}`, { account: who.label }, `no device of ${e.ua}`, 'listed')
  }
  count('passkeys: not remembered', true)

  // A count of zero, twice, taken.
  for (const i of [1, 2]) {
    const z = newDevice()
    if (!(await parOn(z)) || !(await passkeySignIn(who, zero, z, { remember: chance(0.5), what: `a count of zero, the ${i === 1 ? 'first' : 'second'} time` }))) return
  }
  await checkList(who, 'after counts of zero', [pk, zero], { cite: CITE.signIn })

  // The MCP issuer's request, signed in on its page with the passkey
  // (spec/PASSKEYS.md, "passkey-sign-in"; spec/OAUTH-MCP.md).
  const m = newDevice()
  const mreq = await mcpPage(m.b)
  if (!mreq) return
  const signed = await passkeySignIn(who, pk, m, { req: mreq, remember: chance(0.5), what: 'on the MCP issuer\'s page' })
  if (!signed) return
  const c = await m.b.api(mreq.page, '/consent', { did: who.did }, { bearer: signed.ephemeralToken })
  if (c.status !== 200 || typeof c.json?.url !== 'string') return flowBroke('consent on the MCP issuer\'s page, after a passkey sign-in', { account: who.label }, { status: 200, url: '…' }, { status: c.status, body: c.json })
  if (!(await mcpRedeem(acct, m.b, mreq, c.json.url))) return
  count('passkeys: both issuers', true)

  // The email factor on: no code, nothing mailed.
  if (!(await setEmailFactor(acct, true))) return
  await checkMail('the emails before a passkey sign-in with the email factor on', { account: who.label })
  const ef = newDevice()
  const fsigned = (await parOn(ef)) && (await passkeySignIn(who, pk, ef, { remember: chance(0.5), what: 'with the email factor on' }))
  const sent = await checkMail('a passkey sign-in with the email factor on', { account: who.label })
  if (sent.server.length) await broke(CITE.signIn, 'emails after passkey-sign-in with the email factor on', { account: who.label }, 'none', sent.server)
  if (fsigned && !(await approve(who, ef, ef.req, fsigned.ephemeralToken))) return
  await setEmailFactor(acct, false)
  count('passkeys: the email factor', true)
}

/// The assertion faults of "How it is checked", each one thing wrong, for
/// `pk` of `who`, `theirs` another account's user handle: `[what, f]`.
function assertionFaults(pk, theirs) {
  const forms = [
    ['id other than rawId', (j) => ({ ...j, id: b64u(randomBytes(32)) })],
    ['rawId with padding', (j) => ({ ...j, id: `${j.id}=`, rawId: `${j.rawId}=` })],
    ['type other than public-key', (j) => ({ ...j, type: pick(['public-key ', 'webauthn', 'Public-Key']) })],
    ['no type', ({ type: _, ...j }) => j],
    ['no clientDataJSON', (j) => ({ ...j, response: { ...j.response, clientDataJSON: undefined } })],
    ['authenticatorData not a string', (j) => ({ ...j, response: { ...j.response, authenticatorData: [1, 2, 3] } })],
    ['no signature', (j) => ({ ...j, response: { ...j.response, signature: undefined } })],
    ['the signature in base64 with padding', (j) => ({ ...j, response: { ...j.response, signature: `${Buffer.from(j.response.signature, 'base64url').toString('base64')}=` } })],
    ['userHandle not a string', (j) => ({ ...j, response: { ...j.response, userHandle: 5 } })],
    ['a response that is not an object', (j) => ({ ...j, response: pick(['x', null]) })],
    ['a credential that is not an object', (j) => pick([JSON.stringify(j), null, [j]])],
  ]
  const [formName, formFn] = pick(forms)
  const faults = [
    [`the credential's form: ${formName}`, { form: formFn }],
    ['no userHandle', { userHandle: null }],
    ['another account\'s userHandle', { userHandle: theirs }],
    ['a credential ID of no passkey', { credentialId: randomBytes(pk.id.length) }],
    ['type webauthn.create', { type: 'webauthn.create' }],
    ['another challenge', { challenge: b64u(randomBytes(32)) }],
    ['another origin', { origin: pick(['https://example.com', otherPort()]) }],
    ['crossOrigin: true', { crossOrigin: true }],
    ['a topOrigin', { topOrigin: pick([origin(), 'https://example.com']) }],
    ['another rpIdHash', { rpIdHash: sha256(pick(['example.com', `${rpId()}.example.com`])) }],
    ['UP clear', { UP: false }],
    ['UV clear', { UV: false }],
    ['BE other than the passkey\'s', pk.be ? { BE: false, BS: false } : { BE: true }],
    ['AT set', { AT: true }],
    ['a signature by another key', { otherKey: otherKey(pk) }],
    ['a signature over other bytes', { signed: pick([(data, cd) => Buffer.concat([data, cd]), (data, cd) => Buffer.concat([sha256(cd), data]), (data) => data]) }],
    ['a signature not DER', { p1363: true }],
  ]
  return faults
}

/// Signing in refused (spec/PASSKEYS.md, "How it is checked"), each with
/// one thing wrong and no sign-in: no challenge; a challenge spent by a
/// sign-in and by a failure; another device's; then each assertion fault;
/// a count not greater than the last, and of zero after one that was not.
/// The passkey's last use and count are as before, the device lists no
/// account, and the passkey then signs in (spec/PASSKEYS.md,
/// "passkey-sign-in").
export async function passkeySignInRefused() {
  if (!able()) return
  const two = await twoAccounts()
  if (!two) return
  const [who, other] = two
  const pk = await addPasskey(who, { be: chance(0.5) })
  const theirs = pk && (await addPasskey(other))
  if (!theirs) return
  const d = newDevice()
  if (!(await parOn(d))) return
  // A challenge spent by a sign-in, on a device of its own.
  const s = newDevice()
  if (!(await parOn(s))) return
  const spent = await optionsOn(s)
  if (!spent) return
  const ok = await signInOn(s, assertion(pk, { challenge: spent, origin: origin() }).json, { remember: false })
  if (ok.status !== 200) return broke(CITE.signIn, 'passkey-sign-in', { account: who.label }, 200, { status: ok.status, body: ok.json })
  pk.stored = pk.count
  pk.used = ok.at
  await signInRefused(who, pk, s, 'a challenge already spent by a sign-in', {}, { challenge: spent })
  // A challenge spent by a failure.
  const failed = await optionsOn(d)
  if (!failed) return
  await signInRefused(who, pk, d, 'a failure first', { UV: false }, { challenge: failed })
  await signInRefused(who, pk, d, 'a challenge already spent by a failure', {}, { challenge: failed })
  // No challenge: the device's last one spent, and none given it since.
  await signInRefused(who, pk, d, 'no challenge', {}, { challenge: null })
  // Another device's challenge, the device holding one of its own or none.
  const e = newDevice()
  if (!(await parOn(e))) return
  const mine = await optionsOn(d)
  if (!mine) return
  if (chance(0.5) && !(await optionsOn(e))) return
  await signInRefused(who, pk, e, 'the challenge of another device', {}, { challenge: mine })
  for (const [what, f] of assertionFaults(pk, theirs.userHandle)) await signInRefused(who, pk, d, what, f)
  if (pk.stored > 1) await signInRefused(who, pk, d, 'a count not greater than the last', { count: pick([pk.stored, pk.stored - 1]) })
  else await signInRefused(who, pk, d, 'a count not greater than the last', { count: pk.stored })
  await signInRefused(who, pk, d, 'a count of zero after one that was not', { count: 0 })
  // An RS256 passkey: a signature by another key, and one a byte short,
  // refused; then it signs in (spec/PASSKEYS.md, "passkey-sign-in").
  const rs = await addPasskey(who, { alg: -257, bits: pick([2048, 4096]) })
  if (!rs) return
  await signInRefused(who, rs, d, 'an RS256 passkey\'s signature by another key', { otherKey: otherKey(rs) })
  await signInRefused(who, rs, d, 'an RS256 passkey\'s signature a byte short', { short: true })
  const r = newDevice()
  if (!(await parOn(r)) || !(await passkeySignIn(who, rs, r, { remember: chance(0.5), what: 'with an RS256 passkey' }))) return
  await checkList(who, 'after sign-ins refused', who.passkeys, { cite: CITE.signIn })
  if (await listedOn(d, who)) await broke(CITE.signIn, 'authorization page after passkey-sign-ins refused', { account: who.label }, 'not listing the account', 'listing it')
  if (await listedOn(e, who)) await broke(CITE.signIn, 'authorization page after passkey-sign-ins refused', { account: who.label }, 'not listing the account', 'listing it')
  if (!(await parOn(d)) || !(await passkeySignIn(who, pk, d, { remember: chance(0.5), what: 'after sign-ins refused' }))) return
  await checkList(who, 'after sign-ins refused, then one taken', who.passkeys, { cite: CITE.signIn })
  count('passkeys: sign-ins refused', false)
}

/// Removing (spec/PASSKEYS.md, "How it is checked"): an account with two
/// passkeys, one of them signed in with on a device, remembered, and
/// another account with one. `_passkeyRemove` of the first: `200 {}`, not
/// listed, its sign-in refused, the device it signed in on still signed in,
/// the other still signing in; of it again, of the other account's `id`,
/// and of an `id` no passkey has: `200 {}`, removing nothing
/// (spec/PASSKEYS.md, "_passkeyRemove").
export async function passkeyRemoving() {
  if (!able()) return
  const two = await twoAccounts()
  if (!two) return
  const [who, other] = two
  const a = await addPasskey(who)
  const b = a && (await addPasskey(who))
  const c = b && (await addPasskey(other))
  if (!c) return
  const d = newDevice()
  if (!(await parOn(d)) || !(await passkeySignIn(who, a, d, { remember: true, what: 'before it is removed' }))) return
  const [gone, kept] = chance(0.5) ? [a, b] : [b, a]
  await removeOf(who, b64u(gone.id), 'one of its passkeys')
  forget(who, gone)
  await checkList(who, 'after one is removed', [kept], { gone: [gone] })
  await passkeyRefused(who, gone, 'a credential ID of one removed', CITE.remove)
  const e = newDevice()
  if (!(await parOn(e)) || !(await passkeySignIn(who, kept, e, { remember: chance(0.5), what: 'the other passkey, after one was removed', cite: CITE.remove }))) return
  if (gone === a && !(await listedOn(d, who))) await broke(CITE.remove, 'authorization page on a device a removed passkey signed in on', { account: who.label }, 'listing the account: it stays signed in', 'not listing it')
  for (const [what, id] of [['one removed already', b64u(gone.id)], ['another account\'s passkey', b64u(c.id)], ['an id no passkey has', pick(['', 'no-such-passkey', b64u(randomBytes(32))])]]) await removeOf(who, id, what)
  await checkList(who, 'after removing ids not its own', [kept], { gone: [gone, c] })
  await checkList(other, 'after another account removed its id', [c])
  const o = newDevice()
  if (!(await parOn(o)) || !(await passkeySignIn(other, c, o, { remember: chance(0.5), what: 'whose id another account removed', cite: CITE.remove }))) return
  count('passkeys: removed', true)
}

/// The account's states (spec/PASSKEYS.md, "How it is checked"): a password
/// reset, on both sides alike, removing every passkey and ending the link,
/// a new link's user handle the same; a takedown, on both sides alike: its
/// passkeys listed, a sign-in refused, `Account was taken down`, then taken
/// again once lifted; a deactivation: signed in, as with its password, its
/// consent `access_denied` (spec/PASSKEYS.md, "The account's states",
/// "passkey-sign-in").
export async function passkeyStates() {
  if (!able()) return
  const acct = await createAccount({ withPassword: true })
  if (!acct) return
  const who = whoOf(acct, { bare: true })
  const p = await addPasskey(who)
  const q = p && (await addPasskey(who))
  const link = q && (await addLink(who))
  if (!link) return
  const userHandle = p.userHandle

  // A password reset, the account's own password again.
  await both('requestPasswordReset (passkeys)', 'com.atproto.server.requestPasswordReset', { body: { email: acct.email } })
  const sent = await checkMail('requestPasswordReset (passkeys)', { account: who.label })
  const token = (side) => sent[side.name].filter((m) => m.to === acct.email.toLowerCase() && m.kind === 'resetPassword').at(-1)?.token
  if (!token(cand) || !token(ref)) return broke(CITE.states, 'requestPasswordReset', { account: who.label }, 'a resetPassword email', sent.server)
  const [ra, rb] = await both('resetPassword (passkeys)', 'com.atproto.server.resetPassword', (side) => ({ body: { token: token(side), password: acct.password } }))
  if (ra.status !== 200 || rb.status !== 200) return
  await newSessions(who, 'after resetPassword')
  const removed = who.passkeys
  who.passkeys = []
  await checkList(who, 'after a password reset', [], { gone: removed, cite: CITE.states })
  await linkEnded(link, 'made before a password reset', CITE.states)
  await passkeyRefused(who, p, 'a passkey a password reset removed', CITE.states)
  const after = await addLink(who)
  const page = after && (await checkPage(new Browser(), after, 'after a password reset', CITE.states))
  if (!page) return
  if (page.userHandle !== userHandle) await broke(CITE.rp, 'passkey page\'s user.id after a password reset', { account: who.label }, `its user handle, the same whatever happens to the account: ${userHandle}`, page.userHandle)
  count('passkeys: a password reset', true)

  // A takedown: listed as they were, signed in again once lifted.
  const r = await addPasskey(who)
  if (!r) return
  await takedownBoth(who, true)
  await checkList(who, 'while taken down', [r], { cite: CITE.states })
  await passkeyRefused(who, r, 'its account taken down', CITE.states, { description: 'Account was taken down' })
  await takedownBoth(who, false)
  const t = newDevice()
  if (!(await parOn(t)) || !(await passkeySignIn(who, r, t, { remember: chance(0.5), what: 'once a takedown is lifted', cite: CITE.states }))) return
  count('passkeys: a takedown', true)

  // A deactivation: signed in, as with its password, its consent refused.
  await both('deactivateAccount (passkeys)', 'com.atproto.server.deactivateAccount', { token: acct, body: {} })
  const pw = await signInCall(origin(), { locale: 'en', identifier: who.did, password: acct.password })
  const dd = newDevice()
  const signed = (await parOn(dd)) && (await passkeySignIn(who, r, dd, { remember: chance(0.5), what: 'its account deactivated', cite: CITE.signIn }))
  if (signed) {
    if (pw.status !== 200 || signed.account?.deactivated !== true || !isDeepStrictEqual(signed.account, pw.json?.account)) await broke(CITE.signIn, 'passkey-sign-in\'s account, deactivated', { account: who.label }, { ...(pw.json?.account ?? {}), deactivated: true }, signed.account)
    const c = await dd.b.api(dd.req.page, '/consent', { did: who.did }, { headers: dd.headers, bearer: signed.ephemeralToken })
    const p2 = target(c.json?.url)?.params
    if (c.status !== 200 || p2?.code || p2?.error !== 'access_denied') await broke(CITE.signIn, 'consent after a passkey sign-in of a deactivated account', { account: who.label }, { status: 200, url: 'with error=access_denied' }, { status: c.status, body: c.json })
  }
  await both('activateAccount (passkeys)', 'com.atproto.server.activateAccount', { token: acct, method: 'POST' })
  for (const side of [ref, cand]) acct.handles[side.name].push(acct.handles[side.name].at(-1))
  count('passkeys: a deactivation', true)
}

/// Each `passkey_` tool, in every era, and each `pds passkey` command, with
/// the account's password session, an app password's, and none, answering
/// as its route does over XRPC; a name too long refused as there; with the
/// password session, a link made by each, its page answering and the one
/// before ended, and a passkey removed by each (spec/COMMANDS.md, "The
/// account's passkeys", "Auth", "Answers"; spec/PASSKEYS.md, "How it is
/// checked").
export async function passkeyCommands() {
  if (!able() || !COMMANDS) return
  const spec = 'spec/COMMANDS.md, "The account\'s passkeys"'
  const acct = await createAccount({ withPassword: true })
  if (!acct) return
  const who = whoOf(acct, { bare: true })
  const p = await addPasskey(who)
  const q = p && (await addPasskey(who))
  const app = q && (await appPasswordToken(acct))
  if (!app) return
  const [list, add, remove] = PASSKEY_ROUTES
  const ways = [
    ...[MCP_VERSION, ...MCP_LEGACY].map((era) => [`tool, ${era}`, (r, args, token) => viaRouteTool(r, args, token, era)]),
    ['command', (r, args, token) => viaRouteCommand(r, args, { token })],
  ]
  const named = (way, r) => (way === 'command' ? `pds passkey ${r.command}` : `tool ${r.tool}`)
  const overXrpc = (r, args, token) => call(r.route, { auth: token ? { authorization: bearer(token) } : {}, body: r.method === 'POST' ? JSON.stringify(args) : undefined })
  const shape = (a) => (a.status === 200 ? { status: 200, body: a.body } : { status: a.status, error: a.body?.error ?? null })
  const same = async (r, args, [whose, token]) => {
    const want = shape(await overXrpc(r, args, token))
    for (const [way, fn] of ways) {
      const got = shape(await fn(r, args, token))
      if (!isDeepStrictEqual(got, want)) await differ(named(way, r), { auth: whose, args, way }, want, got, spec)
    }
  }
  const auths = [['its password session', who.token], ['an app password\'s session', app], ['none', undefined]]
  for (const a of auths) await same(list, {}, a)
  for (const a of auths.slice(1)) {
    await same(add, { name: 'refused' }, a)
    await same(remove, { id: b64u(p.id) }, a)
  }
  await same(add, { name: 'x'.repeat(65) }, auths[0])
  await checkList(who, 'after its tools and commands refused', [p, q], { cite: spec })
  count('passkeys: tools and commands as the routes', true)

  // With its password session: a link by a tool and by a command, each
  // ending the one before; one passkey removed by each.
  const own = who.token
  const [tool, cmd] = [pick(ways.slice(0, -1)), ways.at(-1)]
  let before = await addLink(who)
  for (const [way, fn] of [tool, cmd]) {
    const name = newName()
    const t0 = Date.now()
    const got = await fn(add, { name }, own)
    const at = [t0, Date.now()]
    if (got.status !== 200 || !linkShaped(got.body, at)) return differ(named(way, add), { auth: 'its password session', way }, { status: 200, body: { url: `${origin()}/oauth/passkey?token=<32 random bytes, base64url>`, expiresAt: '900 seconds on' } }, got, spec)
    const link = { url: got.body.url, token: linkToken(got.body.url), expiresAt: got.body.expiresAt, name, who }
    if (!(await checkPage(new Browser(), link, `made by ${named(way, add)}`, spec))) return
    if (before) await linkEnded(before, `ended by ${named(way, add)}`, spec)
    before = link
  }
  for (const [[way, fn], pk] of [[tool, p], [cmd, q]]) {
    const got = shape(await fn(remove, { id: b64u(pk.id) }, own))
    if (!isDeepStrictEqual(got, { status: 200, body: {} })) await differ(named(way, remove), { auth: 'its password session', way }, { status: 200, body: {} }, got, spec)
    forget(who, pk)
  }
  await checkList(who, 'after its tool and command removed both', [], { gone: [p, q], cite: spec })
  const listed = shape(await pick(ways)[1](list, {}, own))
  if (!isDeepStrictEqual(listed, { status: 200, body: { passkeys: [] } })) await differ(named('tool', list), { auth: 'its password session' }, { status: 200, body: { passkeys: [] } }, listed, spec)
  count('passkeys: tools and commands adding and removing', true)
}

// ------------------------------------------------------------- restarts

/// What `passkeysBeforeCrash` made, for `passkeysAfterCrash`.
let beforeRestart = null

/// Before the server is killed, at some crashes of a run with
/// --crash-every (not --store's), on an active account with a password and
/// fewer than 18 passkeys: one added and signed in with, remembered on a
/// device; another added and removed; a link made; and a challenge given
/// to another device (spec/PASSKEYS.md, "Durability").
export async function passkeysBeforeCrash() {
  beforeRestart = null
  if (!able() || STORE || !chance(0.4)) return
  const some = accounts.filter((a) => a.password)
  if (!some.length) return
  const acct = pick(some)
  const now = await xrpcHttp(cand, 'com.atproto.server.getSession', { token: acct })
  if (now.status !== 200 || now.body?.active === false) return
  const who = whoOf(acct)
  const listed = await call(LIST, { auth: password(who) })
  if (listed.status !== 200 || !Array.isArray(listed.body?.passkeys) || listed.body.passkeys.length > MOST - 3) return
  who.others = listed.body.passkeys.map((x) => x.id)
  const kept = await addPasskey(who)
  const gone = kept && (await addPasskey(who))
  const d = newDevice()
  if (!gone || !(await parOn(d)) || !(await passkeySignIn(who, kept, d, { remember: true, f: kept.be ? { BS: !kept.bs } : {}, what: 'before a restart', cite: CITE.durability }))) return
  await removeOf(who, b64u(gone.id), 'a passkey, before a restart', CITE.durability)
  forget(who, gone)
  const link = await addLink(who)
  const e = newDevice()
  const challenge = link && (await parOn(e)) && (await optionsOn(e))
  if (!challenge) return
  beforeRestart = { who, kept, gone, d, link, e, challenge }
}

/// After the restart, what was made before it is as it was: the passkey
/// added listed and signing in, its count kept, so that an assertion of
/// that count is refused; the device it signed in on still signed in; the
/// one removed neither listed nor signing in; the link's page the error
/// page; the challenge refused (spec/PASSKEYS.md, "Durability").
export async function passkeysAfterCrash() {
  const s = beforeRestart
  beforeRestart = null
  if (!s) return
  const { who, kept, gone, d } = s
  await checkList(who, 'after a restart', [kept], { exact: false, gone: [gone], cite: CITE.durability })
  if (!(await listedOn(d, who))) await broke(CITE.durability, 'authorization page on a device a passkey signed in on before a restart', { account: who.label }, 'listing the account', 'not listing it')
  await passkeyRefused(who, kept, 'the count it signed with before a restart', CITE.durability, { f: { count: kept.stored } })
  await passkeyRefused(who, gone, 'a passkey removed before a restart', CITE.durability)
  await linkEnded(s.link, 'made before a restart', CITE.durability)
  // A new link's user handle, the one before the restart: the key it is
  // made with is kept (spec/PASSKEYS.md, "Durability", "The relying party").
  const fresh = await addLink(who)
  if (!fresh || !(await checkPage(new Browser(), fresh, 'after a restart', CITE.durability))) return
  await signInRefused(who, kept, s.e, 'a challenge given before a restart', {}, { challenge: s.challenge, cite: CITE.durability })
  const again = newDevice()
  if (!(await parOn(again)) || !(await passkeySignIn(who, kept, again, { remember: chance(0.5), what: 'after a restart', cite: CITE.durability }))) return
  await removeOf(who, b64u(kept.id), 'a passkey, after a restart', CITE.durability)
  forget(who, kept)
  count('passkeys: across a restart', true)
}