~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
755 lines · 42.2 KB Raw History
// OAuth's discoverable clients (spec/OAUTH-CLIENTS.md): https client IDs,
// whose documents and JWKS both sides fetch from the harness's client web
// (lib/clients.mjs); web, native and confidential clients; client
// authentication with private_key_jwt; and silent sign-in. The flows and
// what is compared are checks/oauth.mjs's.
//
// A public client's sessions join the account's OAuth sessions, which
// checks/oauth.mjs refreshes and revokes. A confidential client's need its
// assertion on every token request, so they are kept apart, in
// `acct.oauthConfidential`, each with the name of the client key it is
// bound to.

import { isDeepStrictEqual } from 'node:util'
import { below, chance, pick, rand } from '../lib/random.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { fail } from '../lib/plc.mjs'
import { count } from '../lib/report.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { HOSTS, ageReferenceCaches, fetchCount, serve } from '../lib/clients.mjs'
import { Browser, Dpop, b64u, fresh, newKey, pkce, signJwt } from '../lib/oauth.mjs'
import { can, issuer, pageApi } from '../lib/server.mjs'
import {
  RENEW_AFTER_MS, URN, approve, codeOf, codesOf, compare, consent, dpops, exchange, getSessionBoth, handleOf, holdToken, loadPage, oauthOf, par, redirectBoth, revokeOn, sides, signIn, token, tokenBody, view,
} from './oauth.mjs'

const H = `https://${HOSTS[0]}`
const H2 = `https://${HOSTS[1]}`
const ASSERTION_TYPE = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'
/// The private-use scheme of a native client on H: its host backwards.
const SCHEME = HOSTS[0].split('.').reverse().join('.')
const now = () => Math.floor(Date.now() / 1000)

let n = 0
/// A client ID no side has fetched yet.
const freshId = (name = 'c', host = H) => `${host}/${name}-${++n}.json`

/// A web client's document for `id`, with `over` set, or with `undefined`
/// taken out.
function baseDoc(id, over = {}) {
  const d = {
    client_id: id,
    client_name: 'Harness App',
    client_uri: H,
    application_type: 'web',
    redirect_uris: [`${H}/callback`],
    scope: 'atproto transition:generic',
    grant_types: ['authorization_code', 'refresh_token'],
    response_types: ['code'],
    token_endpoint_auth_method: 'none',
    dpop_bound_access_tokens: true,
  }
  for (const [k, v] of Object.entries(over)) {
    if (v === undefined) delete d[k]
    else d[k] = v
  }
  return d
}

// ------------------------------------------------------------ client keys

/// The confidential clients' keys: `k1` and `k2` both in their JWKS, and
/// `stray`, named `k1` too but in no JWKS. Each is a DPoP-style key from
/// lib/oauth.mjs with its `kid` and public JWK.
let K = null
async function keys() {
  if (K) return K
  const make = async (kid) => {
    const k = await newKey()
    return { ...k, kid, pub: { ...k.jwk, kid, alg: 'ES256', use: 'sig' } }
  }
  K = { k1: await make('k1'), k2: await make('k2'), stray: await make('k1') }
  return K
}

/// A client assertion for `clientId` to `side`, signed by `key`: `over` sets
/// or, with `undefined`, takes out claims; `header` header fields.
async function assertion(side, clientId, { key, over = {}, header = {} } = {}) {
  key ??= (await keys()).k1
  const claims = { iss: clientId, sub: clientId, aud: issuer(side), jti: fresh(), iat: now() }
  for (const [k, v] of Object.entries(over)) {
    if (v === undefined) delete claims[k]
    else claims[k] = typeof v === 'function' ? v(side) : v
  }
  const h = { alg: 'ES256', kid: key.kid, ...header }
  for (const [k, v] of Object.entries(header)) if (v === undefined) delete h[k]
  return signJwt(h, claims, key)
}

/// The parameters authenticating `clientId` to `side`.
const authOf = (clientId, opts) => async (side) => ({ client_assertion_type: ASSERTION_TYPE, client_assertion: await assertion(side, clientId, opts) })
const noAuth = async () => ({})

// ------------------------------------------------------- standing clients

/// The clients a run signs in with, each `{kind, id, confidential,
/// redirects, scope, refresh}`, their documents served once and never
/// changed.
let STANDING = null
export async function standing() {
  if (STANDING) return STANDING
  const { k1, k2 } = await keys()
  const scope = 'atproto transition:generic transition:email'
  const make = (kind, over, extra = {}) => {
    const id = freshId(kind)
    const d = baseDoc(id, { scope, ...over })
    serve(id, d)
    return { kind, id, confidential: d.token_endpoint_auth_method === 'private_key_jwt', redirects: d.redirect_uris, scope, refresh: d.grant_types.includes('refresh_token'), ...extra }
  }
  const jwksUri = `${H}/jwks-${++n}.json`
  serve(jwksUri, { keys: [k1.pub, k2.pub] })
  const conf = { token_endpoint_auth_method: 'private_key_jwt', token_endpoint_auth_signing_alg: 'ES256' }
  STANDING = {
    web: make('web', { redirect_uris: [`${H}/callback`, `${H}/cb2`] }),
    native: make('native', { application_type: 'native', client_uri: undefined, redirect_uris: [`${SCHEME}:/callback`, 'http://127.0.0.1/callback', `${H}/native`] }),
    noRefresh: make('norefresh', { grant_types: ['authorization_code'] }),
    conf: make('conf', { ...conf, jwks: { keys: [k1.pub, k2.pub] } }),
    confUri: make('confuri', { ...conf, jwks_uri: jwksUri }),
  }
  return STANDING
}

// ----------------------------------------------------------------- views

/// A PAR answer as compared, with how many times the side fetched each of
/// `urls` while answering it, if counted.
function parView(side, a) {
  const v = view(side, a, (b) => ({ request_uri: typeof b?.request_uri === 'string' && b.request_uri.startsWith(URN) ? '<request_uri>' : b?.request_uri, expires_in: '<expires_in>' }))
  if (a.fetched) v.fetched = a.fetched
  return v
}

/// `send(side)`, with how many times the side fetched each of `urls` while
/// it went.
async function counting(side, urls, send) {
  const before = urls.map((u) => fetchCount(side, u))
  const res = await send()
  return { ...res, fetched: urls.map((u, i) => fetchCount(side, u) - before[i]) }
}

const randomPort = (u) => {
  const x = new URL(u)
  x.port = String(1024 + below(60000))
  return x.href
}

/// A new authorization request of client `c` for `acct`, PAR'd on both
/// sides and compared (spec/OAUTH-CLIENTS.md, "Requests"): `prompt`,
/// `hint(side)` and `scope` as given or drawn, authenticated with the
/// client key `ckey` if `c` is confidential. Answers the request, as
/// checks/oauth.mjs's flows take it, or null.
export async function clientRequest(acct, c, { prompt, hint, scope, kind = `PAR (${c.kind} client)`, ckey = 'k1', auth } = {}) {
  const tokens = c.scope.split(' ')
  scope ??= tokens.filter((t) => t === 'atproto' || chance(0.6)).join(' ')
  let redirect = pick(c.redirects)
  if (redirect.startsWith('http://') && chance(0.25)) redirect = randomPort(redirect)
  const omit = c.redirects.length === 1 && chance(0.25)
  const mode = pick([undefined, undefined, 'query', 'fragment', 'form_post'])
  const key = await newKey()
  const dpop = dpops(key)
  const pk = pkce()
  const state = fresh(12)
  const p = (side) => ({
    client_id: c.id,
    response_type: 'code',
    ...(omit ? {} : { redirect_uri: redirect }),
    scope,
    state,
    code_challenge: pk.challenge,
    code_challenge_method: 'S256',
    ...(mode ? { response_mode: mode } : {}),
    ...(prompt ? { prompt } : {}),
    ...(hint ? { login_hint: hint(side) } : {}),
  })
  const K = await keys()
  auth ??= c.confidential ? authOf(c.id, { key: K[ckey] }) : noAuth
  const res = await compare(kind, { par: p(ref), confidential: c.confidential }, async (side) => par(side, dpop[side.name], { ...p(side), ...(await auth(side)) }), parView)
  for (const side of sides()) {
    const a = res[side.name]
    if (a.status === 201 && !(a.body.expires_in >= 299 && a.body.expires_in <= 300)) await fail(side, 'PAR expires_in (spec/OAUTH.md)', { par: p(ref) }, '299 to 300', a.body.expires_in)
  }
  if (res.reference.status !== 201) return null
  return { client: c, clientId: c.id, scope: scope.split(' '), redirect: omit ? c.redirects[0] : redirect, mode, state, pk, key, dpop, ckey, requestUri: { reference: res.reference.body.request_uri, server: res.server.body.request_uri } }
}

/// The page's answer was a redirect to the client (silent sign-in), not the
/// authorization page.
export const silent = (page) => !page.data.__authorizeData && !page.data.__errorData

/// Exchange the codes of `req`, authenticated as its client key if
/// confidential, and keep the session. Answers it, or null.
export async function exchangeAndKeep(acct, req, codes, kind) {
  const c = req.client
  const K = await keys()
  const t = await exchange(acct, req, codes, { kind, auth: c.confidential ? authOf(c.id, { key: K[req.ckey] }) : noAuth })
  if (t.reference.status !== 200) return null
  const s = {
    clientId: c.id,
    client: c,
    scope: t.reference.body.scope,
    key: req.key,
    dpop: req.dpop,
    tokens: Object.fromEntries(sides().map((side) => [side.name, { access: t[side.name].body.access_token, refresh: t[side.name].body.refresh_token }])),
    old: { reference: [], server: [] },
    code: codes,
    redirect: req.redirect,
    pk: req.pk,
    ckey: req.ckey,
    issued: Date.now(),
  }
  await getSessionBoth(s, `getSession after sign-in (${c.kind} client)`)
  if (!c.refresh) return s
  const list = c.confidential ? (acct.oauthConfidential ??= []) : oauthOf(acct).sessions
  list.push(s)
  if (list.length > 8) list.shift()
  return s
}

/// A full sign-in with client `c`, compared at each step, on the account's
/// device unless `browsers` are given. The page may send the browser back
/// at once (silent sign-in), on the reference's page API alone. With a
/// server's sign-in hook, the server signs in through it (checks/oauth.mjs,
/// `redirectBoth`). Answers the session, or null.
export async function clientLogin(acct, c, { browsers, remember, prompt, hint, scope, kind = `${c.kind} client` } = {}) {
  const st = oauthOf(acct)
  const own = !browsers
  browsers ??= st.browsers
  const req = await clientRequest(acct, c, { prompt, hint, scope })
  if (!req) return null
  let back = await loadPage(req, browsers, `authorization page (${kind})`)
  if (back.reference.status === 200 && back.reference.data.__authorizeData) {
    let bearer
    if (!(own && st.remembered && chance(0.5))) {
      remember ??= pick([true, true, false, undefined])
      const si = await signIn(acct, req, browsers, { remember, kind: `sign-in (${kind})` })
      if (si.reference.status !== 200) return null
      if (own && remember === true) st.remembered = true
      else if (own && remember === false) st.remembered = false
      if (si.reference.json.ephemeralToken) bearer = { reference: si.reference.json.ephemeralToken, server: si.server?.json?.ephemeralToken }
    }
    const narrow = chance(0.15) && can('narrowScope') ? req.scope.filter((t) => t === 'atproto' || chance(0.5)).join(' ') : undefined
    const decided = await consent(acct, req, browsers, { scope: narrow, bearer, kind: `consent (${kind})` })
    if (decided.reference.status !== 200 || !codesOf(decided)) return null
    back = await redirectBoth(acct, req, browsers, { reference: decided.reference.json.url, server: decided.server?.json?.url }, { kind: `redirect (${kind})` })
  } else if (!silent(back.reference) || !pageApi()) return null
  const codes = { reference: codeOf(back.reference, req.mode).code, server: codeOf(back.server, req.mode).code }
  if (!codes.reference) return null
  return exchangeAndKeep(acct, req, codes, `token: code (${kind})`)
}

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

/// A full sign-in with one of the run's https clients.
export async function oauthClientLogin(acct) {
  if (!handleOf(acct) || !acct.password) return
  const S = await standing()
  await clientLogin(acct, pick([S.web, S.web, S.native, S.noRefresh, S.conf, S.confUri]))
}

/// Documents with one thing wrong, or none (spec/OAUTH-CLIENTS.md, "Client
/// IDs", "The document"): `[name, how]`, where `how` has `over` (the web
/// document's fields), `id(n)` (a client ID, and where the document is
/// served, if at all), `answer(doc)` (the answer instead of the document),
/// `jwks` (a JWKS answer at the document's `jwks_uri`), `redirect` (the
/// request's), and `auth` (send an assertion).
const GOOD = `${H}/callback`
const conf = (over = {}) => ({ token_endpoint_auth_method: 'private_key_jwt', token_endpoint_auth_signing_alg: 'ES256', ...over })
const json = (body, status = 200, headers = { 'content-type': 'application/json' }) => ({ status, headers, body })
const two = (type, bad) => ({ over: { application_type: type, redirect_uris: [GOOD, bad] } })
const DOC_FAULTS = [
  ['none', {}],
  // the answer
  ...[204, 500].map((s) => [`status ${s}`, { answer: (d) => json(s === 204 ? '' : JSON.stringify(d), s) }]),
  ...[301, 302, 307].map((s) => [`status ${s}`, { answer: () => ({ status: s, headers: { location: `${H}/elsewhere.json` } }) }]),
  ['Content-Type text/plain', { answer: (d) => json(JSON.stringify(d), 200, { 'content-type': 'text/plain' }) }],
  ['no Content-Type', { answer: (d) => json(JSON.stringify(d), 200, {}) }],
  ['Content-Type with a charset', { answer: (d) => json(JSON.stringify(d), 200, { 'content-type': 'application/json; charset=utf-8' }) }],
  ['Content-Type in upper case', { answer: (d) => json(JSON.stringify(d), 200, { 'content-type': 'Application/JSON' }) }],
  ['Content-Type application/jrd+json', { answer: (d) => json(JSON.stringify(d), 200, { 'content-type': 'application/jrd+json' }) }],
  ['body not JSON', { answer: () => json('<html>') }],
  ['body an array', { answer: (d) => json(JSON.stringify([d])) }],
  ['body a string', { answer: () => json('"x"') }],
  ['body with more after the JSON', { answer: (d) => json(`${JSON.stringify(d)}x`) }],
  ['body over 512 KiB', { answer: (d) => json(JSON.stringify({ ...d, pad: 'x'.repeat(600 * 1024) })) }],
  ['body of 100 KiB', { answer: (d) => json(JSON.stringify({ ...d, pad: 'x'.repeat(100 * 1024) })) }],
  ['no document', { answer: () => json('not found', 404, { 'content-type': 'text/plain' }) }],
  // the client ID
  ...Object.entries({
    'path /': () => `${H}/`,
    'no path': () => H,
    'path ending in /': (i) => `${H}/dir-${i}/`,
    'a fragment': (i) => `${H}/f-${i}.json#x`,
    'a user and password': (i) => `https://u:p@${HOSTS[0]}/f-${i}.json`,
    'a port': (i) => `https://${HOSTS[0]}:8443/f-${i}.json`,
    'an IP address': (i) => `https://1.2.3.4/f-${i}.json`,
    '.test': (i) => `https://app.harness.test/f-${i}.json`,
    '.example': (i) => `https://app.harness.example/f-${i}.json`,
    '.invalid': (i) => `https://app.harness.invalid/f-${i}.json`,
    '.localhost': (i) => `https://app.harness.localhost/f-${i}.json`,
    '.local': (i) => `https://app.harness.local/f-${i}.json`,
    'one label': (i) => `https://harness/f-${i}.json`,
    'localhost': (i) => `https://localhost/f-${i}.json`,
    'HTTPS': (i) => `HTTPS://${HOSTS[0]}/f-${i}.json`,
    'a .. segment': (i) => `${H}/a/../f-${i}.json`,
    'http': (i) => `http://${HOSTS[0]}/f-${i}.json`,
  }).map(([name, id]) => [`client_id with ${name}`, { id: (i) => ({ id: id(i), at: null }) }]),
  ['client_id with a query the document names', { id: (i) => ({ id: `${H}/q-${i}.json?x=1`, at: `${H}/q-${i}.json` }) }],
  ['client_id with a query the document does not name', { id: (i) => ({ id: `${H}/q-${i}.json?x=1`, at: `${H}/q-${i}.json`, docId: `${H}/q-${i}.json` }) }],
  // the fields
  ...Object.entries({
    'no client_id': { client_id: undefined },
    'another client_id': { client_id: `${H}/other.json` },
    'an empty client_id': { client_id: '' },
    'dpop_bound_access_tokens false': { dpop_bound_access_tokens: false },
    'no dpop_bound_access_tokens': { dpop_bound_access_tokens: undefined },
    'dpop_bound_access_tokens "true"': { dpop_bound_access_tokens: 'true' },
    'no scope': { scope: undefined },
    'scope without atproto': { scope: 'transition:generic' },
    'a scope token twice': { scope: 'atproto atproto' },
    'a malformed scope': { scope: 'atproto  transition:generic' },
    'scope a number': { scope: 5 },
    'no authorization_code grant': { grant_types: ['refresh_token'] },
    'the implicit grant': { grant_types: ['authorization_code', 'implicit'] },
    'the password grant': { grant_types: ['authorization_code', 'password'] },
    'an unknown grant': { grant_types: ['authorization_code', 'bogus'] },
    'a grant twice': { grant_types: ['authorization_code', 'authorization_code'] },
    'no grants': { grant_types: [] },
    'no grant_types nor response_types': { grant_types: undefined, response_types: undefined },
    'response type token only': { response_types: ['token'] },
    'response types code and token': { response_types: ['code', 'token'] },
    'an unknown response type': { response_types: ['code', 'bogus'] },
    'no redirect_uris': { redirect_uris: undefined },
    'empty redirect_uris': { redirect_uris: [] },
    'a redirect URI a number': { redirect_uris: [GOOD, 5] },
    'application_type desktop': { application_type: 'desktop' },
    'no application_type': { application_type: undefined },
    'no token_endpoint_auth_method': { token_endpoint_auth_method: undefined },
    'client_secret_post': { token_endpoint_auth_method: 'client_secret_post' },
    'an unknown auth method': { token_endpoint_auth_method: 'bogus' },
    'none with a signing alg': { token_endpoint_auth_signing_alg: 'ES256' },
    'subject_type pairwise': { subject_type: 'pairwise' },
    'client_uri on another origin': { client_uri: H2 },
    'client_uri not a parent': { client_uri: `${H}/elsewhere` },
    'client_uri a parent': { client_uri: `${H}/` },
    'client_uri on a .test host': { client_uri: 'https://app.harness.test' },
    'no client_uri': { client_uri: undefined },
    'logo_uri http': { logo_uri: `http://${HOSTS[0]}/logo.png` },
    'logo_uri https': { logo_uri: `${H}/logo.png` },
    'tos_uri not a URL': { tos_uri: 'nope' },
    'policy_uri on another origin': { policy_uri: `${H2}/policy` },
    'client_name a number': { client_name: 5 },
    'contacts not emails': { contacts: ['nope'] },
    'contacts': { contacts: ['dev@pds-harness.net'] },
    'an unknown field': { unknown_field: { x: 1 } },
    'default_max_age': { default_max_age: 60 },
    'userinfo_signed_response_alg': { userinfo_signed_response_alg: 'ES256' },
    'id_token_signed_response_alg': { id_token_signed_response_alg: 'ES256' },
    'tls_client_certificate_bound_access_tokens true': { tls_client_certificate_bound_access_tokens: true },
    'tls_client_certificate_bound_access_tokens false': { tls_client_certificate_bound_access_tokens: false },
    'authorization_encrypted_response_enc': { authorization_encrypted_response_enc: 'A128CBC-HS256' },
    'authorization_details_types': { authorization_details_types: ['x'] },
    'empty authorization_details_types': { authorization_details_types: [] },
    'require_auth_time': { require_auth_time: true },
  }).map(([name, over]) => [name, { over }]),
  // redirect URIs
  ['web: http redirect URI', two('web', `http://${HOSTS[0]}/callback`)],
  ['web: http localhost redirect URI', two('web', 'http://localhost/callback')],
  ['web: redirect URI not a URL', two('web', 'nope')],
  ['web: https loopback redirect URI', two('web', 'https://127.0.0.1/callback')],
  ['web: loopback redirect URI', two('web', 'http://127.0.0.1/callback')],
  ['web: private-use redirect URI', two('web', `${SCHEME}:/callback`)],
  ['web: redirect URI on a .test host', two('web', 'https://app.harness.test/callback')],
  ['web: redirect URI on a .example host', two('web', 'https://app.harness.example/callback')],
  ['web: redirect URI on a .local host', two('web', 'https://app.harness.local/callback')],
  ['web: redirect URI on a one-label host', two('web', 'https://harness/callback')],
  ['web: redirect URI with a user', two('web', `https://u:p@${HOSTS[0]}/callback`)],
  ['web: redirect URI on an IP address', two('web', 'https://1.2.3.4/callback')],
  ['web: redirect URI on another origin', two('web', `${H2}/callback`)],
  ['web: redirect URI with a port', two('web', `https://${HOSTS[0]}:8443/callback`)],
  ['native: loopback redirect URI', two('native', 'http://127.0.0.1/callback')],
  ['native: [::1] redirect URI with a port', two('native', 'http://[::1]:8080/callback')],
  ['native: loopback redirect URI with a user', two('native', 'http://u:p@127.0.0.1/callback')],
  ['native: private-use redirect URI', two('native', `${SCHEME}:/callback`)],
  ['native: another private-use scheme', two('native', 'com.example.app:/callback')],
  ['native: private-use with //', two('native', `${SCHEME}://callback`)],
  ['native: private-use scheme without a dot', two('native', 'harnessapp:/callback')],
  ['native: private-use scheme of a local name', two('native', 'test.harness:/callback')],
  ['native: https redirect URI on its origin', two('native', `${H}/native`)],
  ['native: private-use redirect URI, requested', { over: { application_type: 'native', redirect_uris: [`${SCHEME}:/callback`] }, redirect: `${SCHEME}:/callback` }],
  // confidential clients
  ['private_key_jwt', { over: conf(), keys: true, auth: true }],
  ['private_key_jwt without keys', { over: conf(), auth: true }],
  ['private_key_jwt without a signing alg', { over: conf({ token_endpoint_auth_signing_alg: undefined }), keys: true, auth: true }],
  ['private_key_jwt with an unknown signing alg', { over: conf({ token_endpoint_auth_signing_alg: 'XX999' }), keys: true, auth: true }],
  ['private_key_jwt with empty jwks', { over: conf({ jwks: { keys: [] } }), auth: true }],
  ['private_key_jwt with only a private key', { over: conf(), keys: 'private', auth: true }],
  ['private_key_jwt with only a key without kid', { over: conf(), keys: 'no kid', auth: true }],
  ['private_key_jwt with only a malformed key', { over: conf({ jwks: { keys: [{ kty: 'nope', kid: 'k1' }] } }), auth: true }],
  ['private_key_jwt with jwks a string', { over: conf({ jwks: 'x' }), auth: true }],
  ['private_key_jwt with jwks and jwks_uri', { over: conf({ jwks_uri: `${H}/jwks-unused.json` }), keys: true, auth: true }],
  ['private_key_jwt with an http jwks_uri', { over: conf({ jwks_uri: `http://${HOSTS[0]}/jwks.json` }), auth: true }],
  ['private_key_jwt, native', { over: conf({ application_type: 'native' }), keys: true, auth: true }],
  ['jwks on a public client', { over: {}, keys: true }],
  ['private_key_jwt without an assertion', { over: conf(), keys: true }],
  ...Object.entries({
    'a JWKS': (k) => json(JSON.stringify({ keys: [k.k1.pub] })),
    'a JWKS without Content-Type': (k) => json(JSON.stringify({ keys: [k.k1.pub] }), 200, {}),
    'a JWKS as text/plain': (k) => json(JSON.stringify({ keys: [k.k1.pub] }), 200, { 'content-type': 'text/plain' }),
    'no JWKS': () => json('not found', 404, { 'content-type': 'text/plain' }),
    'a JWKS redirected': () => ({ status: 302, headers: { location: `${H}/jwks-elsewhere.json` } }),
    'a JWKS not JSON': () => json('x'),
    'a JWKS without keys': () => json('{}'),
    'a JWKS with no keys': () => json(JSON.stringify({ keys: [] })),
    'a JWKS with only the stray key': (k) => json(JSON.stringify({ keys: [k.stray.pub] })),
  }).map(([name, answer]) => [`jwks_uri: ${name}`, { over: conf(), jwks: answer, auth: true }]),
  ['jwks_uri on a public client, no JWKS', { over: {}, jwks: () => json('not found', 404, { 'content-type': 'text/plain' }) }],
]

/// A new client's document, served with one thing wrong or none, then PAR
/// on both sides, counting each side's fetches of it and of its JWKS; then
/// PAR again, the document as it was, or put right.
export async function oauthClientDocument() {
  const [name, how] = pick(DOC_FAULTS)
  const K = await keys()
  const i = ++n
  const { id, at = id, docId = id } = how.id ? how.id(i) : { id: `${H}/doc-${i}.json` }
  const jwksUrl = how.jwks ? `${H}/jwks-doc-${i}.json` : null
  const over = { ...(how.over ?? {}) }
  if (how.keys === true) over.jwks = { keys: [K.k1.pub, K.k2.pub] }
  if (how.keys === 'private') over.jwks = { keys: [{ ...K.k1.privateJwk, kid: 'k1' }] }
  if (how.keys === 'no kid') over.jwks = { keys: [K.k1.jwk] }
  if (jwksUrl) over.jwks_uri = jwksUrl
  const good = baseDoc(docId, over)
  if (at) serve(at, how.answer ? () => how.answer(good) : good)
  if (jwksUrl) serve(jwksUrl, () => how.jwks(K))
  const urls = [at, jwksUrl].filter(Boolean)
  const scope = 'atproto'
  const redirect = how.redirect ?? GOOD
  const parOnce = (kind) => {
    const pk = pkce()
    const state = fresh(12)
    return compare(kind, { client_id: id, document: name }, (side) => counting(side, urls, async () => {
      const dp = new Dpop(await newKey())
      const auth = how.auth ? await authOf(id, { key: K.k1 })(side) : {}
      return par(side, dp, { client_id: id, response_type: 'code', redirect_uri: redirect, scope, state, code_challenge: pk.challenge, code_challenge_method: 'S256', ...auth })
    }), parView)
  }
  const first = await parOnce(`PAR, client document: ${name}`)
  if (first.reference.status === 201) {
    if (chance(0.5)) await parOnce(`PAR again, client document: ${name} (kept)`)
    return
  }
  if (at && chance(0.4)) {
    // Put right: a refused document is not kept, so it is fetched again.
    const fixed = baseDoc(id, how.auth ? conf({ jwks: { keys: [K.k1.pub] } }) : {})
    serve(at, fixed)
    if (jwksUrl) serve(jwksUrl, { keys: [K.k1.pub] })
    await parOnce(`PAR, client document: ${name}, put right`)
  }
}

/// A document taken, then changed or gone: still the kept one on both
/// sides (spec/OAUTH-CLIENTS.md, "The document", "Keeping it"); then put
/// back.
export async function oauthClientCache() {
  const id = freshId('kept')
  const doc = baseDoc(id)
  serve(id, doc)
  const send = (kind, scope = 'atproto') => {
    const pk = pkce()
    const state = fresh(12)
    return compare(kind, { client_id: id }, (side) => counting(side, [id], async () => par(side, new Dpop(await newKey()), { client_id: id, response_type: 'code', redirect_uri: GOOD, scope, state, code_challenge: pk.challenge, code_challenge_method: 'S256' })), parView)
  }
  const first = await send('PAR (a document to keep)')
  if (first.reference.status !== 201) return
  const [name, changed, scope] = pick([
    ['gone', () => json('not found', 404, { 'content-type': 'text/plain' }), 'atproto'],
    ['refused now', baseDoc(id, { dpop_bound_access_tokens: false }), 'atproto'],
    ['a scope added', baseDoc(id, { scope: 'atproto transition:generic transition:email' }), 'atproto transition:email'],
    ['a redirect URI changed', baseDoc(id, { redirect_uris: [`${H}/new-callback`] }), 'atproto'],
  ])
  serve(id, changed)
  await send(`PAR, the kept document ${name}`, scope)
  serve(id, doc)
}

// ---------------------------------------------------- client authentication

/// Assertions with one thing wrong, or right (spec/OAUTH-CLIENTS.md,
/// "Client authentication"): `[name, (clientId) => side => params]`.
const ASSERTION_FAULTS = [
  ['none', () => async () => ({})],
  ['another type', (id) => async (side) => ({ client_assertion_type: 'urn:x', client_assertion: await assertion(side, id) })],
  ['no type', (id) => async (side) => ({ client_assertion: await assertion(side, id) })],
  ['not a JWT', () => async () => ({ client_assertion_type: ASSERTION_TYPE, client_assertion: 'abc' })],
  ['alg none', (id) => async (side) => ({ client_assertion_type: ASSERTION_TYPE, client_assertion: `${b64u(JSON.stringify({ alg: 'none', kid: 'k1' }))}.${b64u(JSON.stringify({ iss: id, sub: id, aud: issuer(side), jti: fresh(), iat: now() }))}.` })],
  ['a client_secret instead', () => async () => ({ client_secret: 'secret' })],
  ...Object.entries({
    'another iss': { over: { iss: `${H}/other.json` } },
    'no iss': { over: { iss: undefined } },
    'another sub': { over: { sub: `${H}/other.json` } },
    'no sub': { over: { sub: undefined } },
    'aud the token endpoint': { over: { aud: (side) => `${issuer(side)}/oauth/token` } },
    'aud with a trailing slash': { over: { aud: (side) => `${issuer(side)}/` } },
    'aud an array with the issuer': { over: { aud: (side) => ['https://elsewhere.pds-harness.net', issuer(side)] } },
    'no aud': { over: { aud: undefined } },
    'no jti': { over: { jti: undefined } },
    'no iat': { over: { iat: undefined } },
    'iat a string': { over: { iat: () => String(now()) } },
    'iat 120 s old': { over: { iat: () => now() - 120 } },
    'iat 30 s old': { over: { iat: () => now() - 30 } },
    'iat 30 s ahead': { over: { iat: () => now() + 30 } },
    'exp past': { over: { exp: () => now() - 10 } },
    'exp ahead': { over: { exp: () => now() + 30 } },
    'nbf ahead': { over: { nbf: () => now() + 30 } },
    'nbf past': { over: { nbf: () => now() - 30 } },
    'no kid': { header: { kid: undefined } },
    'an unknown kid': { header: { kid: 'k9' } },
    'kid k2, signed by k1': { header: { kid: 'k2' } },
    'alg ES384': { header: { alg: 'ES384' } },
    'typ dpop+jwt': { header: { typ: 'dpop+jwt' } },
    'signed by a key not the client\'s': { key: 'stray' },
    'signed by the client\'s other key': { key: 'k2' },
  }).map(([name, o]) => [name, (id) => async (side) => {
    const K = await keys()
    return { client_assertion_type: ASSERTION_TYPE, client_assertion: await assertion(side, id, { ...o, key: K[o.key ?? 'k1'] }) }
  }]),
]

/// A confidential client's PAR, code grant, refresh or revocation with an
/// assertion with one thing wrong (or reused), then the same as it should
/// be (spec/OAUTH-CLIENTS.md, "Client authentication", "Single-use values
/// and durability").
export async function oauthAssertionRefused(acct) {
  const S = await standing()
  const c = pick([S.conf, S.confUri])
  const r = rand()
  const where = r < 0.5 ? 'PAR' : r < 0.7 ? 'code' : r < 0.85 ? 'refresh' : 'revoke'
  const reuse = chance(0.12)
  const [name, make] = reuse ? ['jti reused', null] : pick(ASSERTION_FAULTS)
  // A reused assertion: each side's own, used once before this request.
  let once
  const fault = reuse ? async (side) => once[side.name] : make(c.id)
  const spend = async (kind) => {
    const a = authOf(c.id)
    once = { reference: await a(ref), server: await a(cand) }
    const pk = pkce()
    const st = fresh(12)
    await compare(kind, { client_id: c.id }, async (side) => par(side, new Dpop(await newKey()), { client_id: c.id, response_type: 'code', redirect_uri: GOOD, scope: 'atproto', state: st, code_challenge: pk.challenge, code_challenge_method: 'S256', ...once[side.name] }), parView)
  }
  if (where === 'PAR') {
    if (!handleOf(acct)) return
    if (reuse) await spend('PAR (an assertion to reuse)')
    await clientRequest(acct, c, { kind: `PAR, client assertion: ${name}`, auth: fault })
    if (chance(0.5)) await clientRequest(acct, c, { kind: `PAR, after an assertion refused (${name})` })
    return
  }
  if (where === 'code') {
    if (!handleOf(acct) || !acct.password) return
    const req = await clientRequest(acct, c, { kind: 'PAR (for another check)' })
    if (!req) return
    const codes = (await approve(acct, req))?.codes
    if (!codes) return
    if (reuse) await spend('PAR (an assertion to reuse)')
    await exchange(acct, req, codes, { kind: `token: code, client assertion: ${name}`, auth: fault })
    await exchangeAndKeep(acct, req, codes, `token: code after an assertion refused (${name})`)
    return
  }
  const ss = acct.oauthConfidential?.filter((s) => s.client === c) ?? []
  const s = ss.length ? pick(ss) : await clientLogin(acct, c)
  if (!s) return
  await renewConf(acct, s)
  if (reuse) await spend('PAR (an assertion to reuse)')
  if (where === 'refresh') {
    await refreshConf(acct, s, `client assertion: ${name}`, fault)
  } else {
    await compare(`revoke, client assertion: ${name}`, { revoke: name }, async (side) => revokeOn(side, s.dpop[side.name], { client_id: s.clientId, token: s.tokens[side.name].refresh, ...(await fault(side)) }), (side, a) => view(side, a, (b) => b))
  }
  await getSessionBoth(s, `getSession after a client assertion: ${name} (${where})`)
  await refreshConf(acct, s, `after a client assertion: ${name} (${where})`)
}

/// A refresh of a confidential session with `auth`'s parameters (the
/// session's own key if none), compared; the session's tokens move on if it
/// is answered.
async function refreshConf(acct, s, how, auth) {
  const K = await keys()
  auth ??= authOf(s.clientId, { key: K[s.ckey] })
  const body = (side) => ({ grant_type: 'refresh_token', client_id: s.clientId, refresh_token: s.tokens[side.name].refresh })
  const res = await compare(`token: refresh (${s.client.kind} client, ${how})`, { refresh: how }, async (side) => token(side, s.dpop[side.name], { ...body(side), ...(await auth(side)) }), (side, a) => view(side, a, tokenBody(side)))
  for (const side of sides()) await holdToken(side, acct, res[side.name], { refresh: how })
  if (res.reference.status !== 200) return res
  s.issued = Date.now()
  for (const side of sides()) {
    s.old[side.name].push({ ...s.tokens[side.name] })
    s.tokens[side.name] = { access: res[side.name].body.access_token, refresh: res[side.name].body.refresh_token }
  }
  if (s.old.reference.length > 4) for (const side of sides()) s.old[side.name].shift()
  return res
}

/// Refresh confidential session `s` with its key, compared, if its access
/// token is older than `RENEW_AFTER_MS`, as `pickSession` does a public
/// one's (spec/OAUTH.md, "How it is checked").
async function renewConf(acct, s) {
  if (Date.now() - (s.issued ?? 0) >= RENEW_AFTER_MS) await refreshConf(acct, s, 'a session near its expiry')
}

/// A confidential session refreshed or revoked with its key, the client's
/// other key, none, or a reused assertion; then getSession and a refresh
/// (spec/OAUTH-CLIENTS.md, "Client authentication").
export async function oauthConfidentialSession(acct) {
  const ss = acct.oauthConfidential ?? []
  if (!ss.length) return
  const s = chance(0.6) ? ss.at(-1) : pick(ss)
  await renewConf(acct, s)
  const K = await keys()
  const other = s.ckey === 'k1' ? 'k2' : 'k1'
  const replaced = s.old.reference.length > 0
  const how = pick(['its key', 'its key', 'the other key', 'no assertion', 'a reused assertion', ...(replaced ? ['a replaced refresh token'] : [])])
  const what = pick(['refresh', 'refresh', 'revoke access', 'revoke refresh'])
  let auth = how === 'the other key' ? authOf(s.clientId, { key: K[other] }) : how === 'no assertion' ? noAuth : authOf(s.clientId, { key: K[s.ckey] })
  if (how === 'a reused assertion') {
    const a = { reference: await auth(ref), server: await auth(cand) }
    await refreshConf(acct, s, 'an assertion to reuse', async (side) => a[side.name])
    auth = async (side) => a[side.name]
  }
  if (what === 'refresh') {
    if (how === 'a replaced refresh token' && s.old.reference.length) {
      const i = below(s.old.reference.length)
      await compare('token: refresh (confidential client, a replaced refresh token)', { refresh: 'replaced' }, async (side) => token(side, s.dpop[side.name], { grant_type: 'refresh_token', client_id: s.clientId, refresh_token: s.old[side.name][i].refresh, ...(await auth(side)) }), (side, a) => view(side, a, tokenBody(side)))
    } else await refreshConf(acct, s, how, auth)
  } else {
    const t = (side) => (what === 'revoke access' ? s.tokens[side.name].access : s.tokens[side.name].refresh)
    await compare(`revoke (confidential client, ${what}, ${how})`, { revoke: what, how }, async (side) => revokeOn(side, s.dpop[side.name], { client_id: s.clientId, token: t(side), ...(await auth(side)) }), (side, a) => view(side, a, (b) => b))
  }
  await getSessionBoth(s, `getSession (confidential client, after ${what} with ${how})`)
  if (chance(0.5)) await refreshConf(acct, s, `after ${what} with ${how}`)
}

// ------------------------------------------------------------ silent sign-in

/// A confidential client's request with a prompt and a login_hint drawn,
/// loaded on the account's device (or a new one); a code given at once is
/// exchanged (spec/OAUTH-CLIENTS.md, "Silent sign-in").
export async function oauthSilentSignIn(acct) {
  if (!handleOf(acct) || !acct.password) return
  const S = await standing()
  const c = pick([S.conf, S.confUri])
  const st = oauthOf(acct)
  // Approve the client on this device first, now and then.
  if (chance(st.remembered ? 0.2 : 0.6)) await clientLogin(acct, c, { remember: true, prompt: pick([undefined, 'consent']) })
  const prompt = pick(['none', 'none', 'none', undefined, undefined, 'login', 'consent', 'select_account', 'create'])
  const others = accounts.filter((a) => a !== acct && handleOf(a))
  const [hintName, hint] = pick([
    ['handle', () => handleOf(acct)],
    ['handle', () => handleOf(acct)],
    ['HANDLE', () => handleOf(acct).toUpperCase()],
    ['DID', (side) => didOf(side, acct)],
    ['another account', others.length ? () => handleOf(others[0]) : () => 'nobody.test'],
    ['none', null],
  ])
  const scope = pick(['atproto', 'atproto transition:generic', c.scope])
  const newDevice = chance(0.15)
  const browsers = newDevice ? { reference: new Browser(), server: new Browser() } : st.browsers
  const req = await clientRequest(acct, c, { prompt, hint: hint ?? undefined, scope, kind: `PAR (silent sign-in: prompt ${prompt ?? 'absent'}, hint ${hintName})` })
  if (!req) return
  const page = await loadPage(req, browsers, `silent sign-in: prompt ${prompt ?? 'absent'}, hint ${hintName}, scope ${scope}${newDevice ? ', a new device' : ''}`)
  if (!silent(page.reference)) return
  const codes = { reference: codeOf(page.reference, req.mode).code, server: codeOf(page.server, req.mode).code }
  if (codes.reference) await exchangeAndKeep(acct, req, codes, 'token: code of a silent sign-in')
}

// ------------------------------------------------------------ departures

/// The departures spec/OAUTH-CLIENTS.md lists (spec/OAUTH-CLIENTS.md,
/// "Where the reference departs from the specs"): the server held to the
/// spec alone.
export async function oauthClientDepartures() {
  const K = await keys()
  const id = freshId('dep')
  const jwksUrl = `${H}/jwks-dep-${n}.json`
  const [which, d, want, opts = {}] = pick([
    ['a document answered 201', () => json(JSON.stringify(baseDoc(id)), 201), 'invalid_client_metadata'],
    ['a document answered 203', () => json(JSON.stringify(baseDoc(id)), 203), 'invalid_client_metadata'],
    ['token_endpoint_auth_signing_alg none', baseDoc(id, conf({ token_endpoint_auth_signing_alg: 'none', jwks: { keys: [K.k1.pub] } })), 'invalid_client_metadata', { auth: true }],
    ['an http logo_uri on a loopback host', baseDoc(id, { logo_uri: 'http://127.0.0.1/logo.png' }), 'invalid_client_metadata'],
    ['an http tos_uri on a loopback host', baseDoc(id, { tos_uri: 'http://localhost/tos' }), 'invalid_client_metadata'],
    ['an http policy_uri on a loopback host', baseDoc(id, { policy_uri: 'http://[::1]/policy' }), 'invalid_client_metadata'],
    ['an http jwks_uri on a loopback host', baseDoc(id, conf({ jwks_uri: 'http://127.0.0.1/jwks.json' })), 'invalid_client_metadata', { auth: true }],
    ['a native client\'s https redirect URI on another origin', baseDoc(id, { application_type: 'native', redirect_uris: [`${SCHEME}:/callback`, `${H2}/callback`] }), 'invalid_redirect_uri', { redirect: `${SCHEME}:/callback` }],
    ['a JWKS answered 201', baseDoc(id, conf({ jwks_uri: jwksUrl })), 'invalid_client_metadata', { auth: true, jwks: () => json(JSON.stringify({ keys: [K.k1.pub] }), 201) }],
  ])
  serve(id, d)
  if (opts.jwks) serve(jwksUrl, opts.jwks)
  const pk = pkce()
  const p = { client_id: id, response_type: 'code', redirect_uri: opts.redirect ?? GOOD, scope: 'atproto', state: fresh(12), code_challenge: pk.challenge, code_challenge_method: 'S256', ...(opts.auth ? await authOf(id)(cand) : {}) }
  const got = view(cand, await par(cand, new Dpop(await newKey()), p))
  const g = { status: got.status, error: got.error ?? null }
  const w = { status: 400, error: want }
  if (!isDeepStrictEqual(g, w)) await fail(cand, `OAuth client departure "${which}" (spec/OAUTH-CLIENTS.md, held to the spec)`, p, w, g)
  count(`oauth client departure: ${which}`, true)
}

// ---------------------------------------------------------------- crashes

let pending = []

/// Before the server is killed: a request of a new client, on a new
/// device, signed in there or not, for consent after the restart.
export async function oauthClientsBeforeCrash() {
  pending = []
  const able = accounts.filter((a) => handleOf(a) && a.password)
  if (!able.length) return
  const acct = pick(able)
  const K = await keys()
  const kind = pick(['document gone', 'document refused', 'document not JSON', 'JWKS gone', 'redirect URIs changed', 'document gone, not signed in'])
  const id = freshId('pending')
  const jwksUrl = kind === 'JWKS gone' ? `${H}/jwks-pending-${n}.json` : null
  const d = baseDoc(id, jwksUrl ? conf({ jwks_uri: jwksUrl }) : {})
  serve(id, d)
  if (jwksUrl) serve(jwksUrl, { keys: [K.k1.pub] })
  const c = { kind: 'pending', id, confidential: Boolean(jwksUrl), redirects: d.redirect_uris, scope: d.scope, refresh: true }
  const req = await clientRequest(acct, c, { kind: 'PAR (a request to consent to after a crash)' })
  if (!req) return
  const browsers = { reference: new Browser(), server: new Browser() }
  await loadPage(req, browsers, 'authorization page (a request to consent to after a crash)')
  if (!kind.endsWith('not signed in')) {
    const si = await signIn(acct, req, browsers, { remember: true, identifier: 'handle', kind: 'sign-in (a request to consent to after a crash)' })
    if (si.reference.status !== 200) return
  }
  pending.push({ acct, req, browsers, kind, id, jwksUrl, d })
}

/// After the restart, which leaves the server keeping no document, and with
/// the reference's kept ones aged past 10 minutes: the client's document
/// broken, then consent and the page again, compared (spec/OAUTH-CLIENTS.md,
/// "Single-use values and durability", "At consent"; spec/OAUTH.md,
/// "Durability").
export async function oauthClientsAfterCrash() {
  if (!pending.length) return
  await ageReferenceCaches(11 * 60 * 1000)
  for (const { acct, req, browsers, kind, id, jwksUrl, d } of pending) {
    const gone = () => json('not found', 404, { 'content-type': 'text/plain' })
    if (kind === 'JWKS gone') serve(jwksUrl, gone)
    else if (kind === 'document refused') serve(id, { ...d, dpop_bound_access_tokens: false })
    else if (kind === 'document not JSON') serve(id, () => json('<html>'))
    else if (kind === 'redirect URIs changed') serve(id, { ...d, redirect_uris: [`${H}/new-callback`] })
    else serve(id, gone)
    const c = await consent(acct, req, browsers, { kind: `consent after a crash, the client's ${kind}` })
    await loadPage(req, browsers, `authorization page after consent, the client's ${kind}`)
    const codes = codesOf(c)
    if (codes) await exchangeAndKeep(acct, req, codes, `token: code after a crash, the client's ${kind}`)
  }
  pending = []
}