~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
525 lines · 29.9 KB Raw History
// Email (spec/EMAIL.md): confirming an account's email, changing it,
// resetting the password by it, and the sign-in code it gets; and the
// emails each side sends for them, compared by address and kind, each
// token held to the form the spec gives. Each is held to the reference, and
// each side's own tokens are given back to it.

import { isDeepStrictEqual } from 'node:util'
import { below, chance, pick, rand } from '../lib/random.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { checkMail } from '../lib/mail.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { both, normalize, shown, xrpc, xrpcHttp } from '../lib/xrpc.mjs'
import { EDGE_BAD_EMAILS, EMOJI, edgeEmail, freshFront, mixCase } from './accounts.mjs'
import { Browser, wwwError } from '../lib/oauth.mjs'
import { CLIENTS, approved, getSessionOn, handleOf, loadPage, login as oauthLogin, newRequest, oauthOf, pageUrl, signIn, token as tokenEndpoint } from './oauth.mjs'
import { smtp } from '../lib/server.mjs'

const REQUEST_CONFIRM = 'com.atproto.server.requestEmailConfirmation'
const CONFIRM = 'com.atproto.server.confirmEmail'
const REQUEST_UPDATE = 'com.atproto.server.requestEmailUpdate'
const UPDATE = 'com.atproto.server.updateEmail'
const REQUEST_RESET = 'com.atproto.server.requestPasswordReset'
const RESET = 'com.atproto.server.resetPassword'
const LOGIN = 'com.atproto.server.createSession'
const GET = 'com.atproto.server.getSession'
const REFRESH = 'com.atproto.server.refreshSession'
const CREATE_AP = 'com.atproto.server.createAppPassword'

/// Each kind of email, and its token's purpose.
const PURPOSE = { confirmEmail: 'confirm_email', updateEmail: 'update_email', resetPassword: 'reset_password', signInAuthFactor: 'auth_factor' }
/// Tokens of the form that no side made.
const NEVER = ['AAAAA-AAAAA', '22222-22222', 'ZZZZZ-77777']

/// Each account's tokens, by purpose, as each side mailed them, oldest
/// first: `{reference: [...], server: [...]}`, alike in length, as both
/// sides mail alike. Kept to give back later, maybe after a crash, when
/// each must still do as it would have (spec/EMAIL.md, "Durability").
const mailed = new Map()
function tokensOf(acct, purpose) {
  if (!mailed.has(acct)) mailed.set(acct, {})
  const byPurpose = mailed.get(acct)
  byPurpose[purpose] ??= { reference: [], server: [] }
  return byPurpose[purpose]
}

/// Keep the tokens `sent` carried (checkMail's answer), each for the
/// account with a password whose email it went to.
function keep(sent) {
  sent.reference.forEach((m, i) => {
    const acct = accounts.find((a) => a.password && a.email === m.to)
    const purpose = PURPOSE[m.kind]
    if (!acct || !purpose) return
    const t = tokensOf(acct, purpose)
    t.reference.push(m.token)
    t.server.push(sent.server[i].token)
  })
}

/// One request to both, compared, then the emails each sent for it. With
/// `http`, it goes over XRPC on both sides, never through a tool or
/// command: a call by GET, or with a body where none is taken, is HTTP's.
async function call(kind, nsid, request, http = false) {
  const answers = http ? await bothHttp(kind, nsid, request) : await both(kind, nsid, request)
  keep(await checkMail(kind, shown(request)))
  return answers
}

async function bothHttp(kind, nsid, request) {
  const on = (side) => (typeof request === 'function' ? request(side) : request)
  const [a, b] = await Promise.all([xrpcHttp(ref, nsid, on(ref)), xrpcHttp(cand, nsid, on(cand))])
  const [na, nb] = [normalize(ref, a, nsid), normalize(cand, b, nsid)]
  if (!isDeepStrictEqual(na, nb)) await differ(nsid, shown(request), na, nb)
  count(kind, a.status < 400)
  return [a, b]
}

/// The emails sent since the last step of this page, by other steps:
/// compared too, so that no other method sends one where the reference
/// does not (spec/EMAIL.md, "The mailer").
async function strays() {
  keep(await checkMail('the emails sent since the last email step', {}))
}

const tokenOn = (side, t) => (typeof t === 'function' ? t(side) : t)

/// A token to give back for `acct`'s `purpose`, as `[how, token of the
/// side]`: its current one, an earlier one, the current one in lower case,
/// its current one of another purpose, one never made, or `""`
/// (spec/EMAIL.md, "Tokens").
function pickToken(acct, purpose) {
  const t = tokensOf(acct, purpose)
  const n = t.reference.length
  const r = rand()
  if (n && r < 0.45) return ['the current', (side) => t[side.name][n - 1]]
  if (n > 1 && r < 0.6) {
    const i = below(n - 1)
    return ['an earlier', (side) => t[side.name][i]]
  }
  if (n && r < 0.7) return ['the current, in lower case,', (side) => t[side.name][n - 1].toLowerCase()]
  const others = Object.values(PURPOSE).filter((p) => p !== purpose && tokensOf(acct, p).reference.length)
  if (others.length && r < 0.8) {
    const o = tokensOf(acct, pick(others))
    const i = o.reference.length - 1
    return ["another purpose's", (side) => o[side.name][i]]
  }
  if (r < 0.93) {
    const v = pick(NEVER)
    return ['a never made', () => v]
  }
  return ['an empty', () => '']
}

/// The access token to call with: the account's, none, its refresh token,
/// or one never given out.
function authOf(acct) {
  const r = rand()
  if (r < 0.8) return ['', acct]
  if (r < 0.87) return [', no token', undefined]
  if (r < 0.94) return [', a refresh token', (side) => acct.sides[side.name].refresh]
  return [', a token never given out', 'never-given-out']
}

/// A procedure with no input, sometimes called by GET or with a body.
function noInput() {
  const r = rand()
  return r < 0.05 ? [', by GET', { method: 'GET' }] : r < 0.1 ? [', with a body', { body: {} }] : ['', { method: 'POST' }]
}

/// The emails accounts without a password were made with, that no account
/// with a password has: no account keeps them.
const freeEmails = () => accounts.filter((a) => !a.password && !accounts.some((b) => b.password && b.email === a.email)).map((a) => a.email)

/// requestEmailConfirmation with the account's token, none, or a wrong one
/// (spec/EMAIL.md, "requestEmailConfirmation").
export async function requestEmailConfirmation(acct) {
  await strays()
  const [how, token] = authOf(acct)
  const [odd, shape] = noInput()
  await call(`requestEmailConfirmation${how}${odd}`, REQUEST_CONFIRM, (side) => ({ ...shape, token: tokenOn(side, token) }), odd !== '')
}

/// confirmEmail with the account's email, in mixed case, another's, or one
/// no account has; and a token picked as pickToken says. Then getSession
/// (spec/EMAIL.md, "confirmEmail", "The account's email").
export async function confirmEmail(acct) {
  await strays()
  const others = accounts.filter((a) => a !== acct)
  const r = rand()
  const [which, email] = r < 0.75 ? ["the account's email", chance(0.5) ? mixCase(acct.email) : acct.email] : r < 0.9 && others.length ? ["another account's email", pick(others).email] : ['an email no account has', `${freshFront()}@example.com`]
  const [how, token] = pickToken(acct, 'confirm_email')
  const bad = chance(0.05) ? pick([{}, { email }, { token: 'x' }, { email, token: 5 }]) : null
  const [a] = await call(bad ? 'confirmEmail, bad input' : `confirmEmail with ${which}, ${how} token`, CONFIRM, (side) => ({ token: acct, body: bad ?? { email, token: token(side) } }))
  if (a.status === 200) await both('getSession after confirmEmail', GET, { token: acct })
}

/// requestEmailUpdate with the account's token, none, or a wrong one
/// (spec/EMAIL.md, "requestEmailUpdate").
export async function requestEmailUpdate(acct) {
  await strays()
  const [how, token] = authOf(acct)
  const [odd, shape] = noInput()
  await call(`requestEmailUpdate${how}${odd}`, REQUEST_UPDATE, (side) => ({ ...shape, token: tokenOn(side, token) }), odd !== '')
}

/// updateEmail to a new address, the same, another account's, one only an
/// account without a password had, or no address; with no token or one
/// picked as pickToken says; sometimes with `emailAuthFactor: false`, or
/// `true` and a new address. Then getSession, and createSession by the
/// new email (spec/EMAIL.md, "updateEmail", "The account's email").
export async function updateEmail(acct) {
  await strays()
  const others = accounts.filter((a) => a !== acct && a.password)
  const free = freeEmails()
  const r = rand()
  let [which, email] = ['a new address', `${freshFront()}@example.com`]
  if (r < 0.15) [which, email] = ['a new address at the edge', edgeEmail(freshFront())]
  else if (r < 0.35) [which, email] = ['the same address', acct.email]
  else if (r < 0.5 && others.length) [which, email] = ["another account's address", pick(others).email]
  else if (r < 0.6 && free.length) [which, email] = ['an address only an account without a password had', pick(free)]
  else if (r < 0.7) [which, email] = ['no address', pick(['not-an-email', ...EDGE_BAD_EMAILS])]
  if (chance(0.3)) email = mixCase(email)
  const f = rand()
  const factor = f < 0.1 ? false : f < 0.15 ? true : undefined
  // Turning the factor on, with the account's own address, is emailFactor's.
  if (factor === true) [which, email] = ['a new address', `${freshFront()}@example.com`]
  const [how, token] = chance(0.35) ? ['no', null] : pickToken(acct, 'update_email')
  const bad = chance(0.05) ? pick([{}, { email: 5 }, { email, emailAuthFactor: 'yes' }, { email, token: 5 }]) : null
  const extra = factor === undefined ? '' : `, emailAuthFactor ${factor}`
  const [a, b] = await call(bad ? 'updateEmail, bad input' : `updateEmail to ${which}, ${how} token${extra}`, UPDATE, (side) => ({
    token: acct,
    body: bad ?? { email, ...(token ? { token: token(side) } : {}), ...(factor === undefined ? {} : { emailAuthFactor: factor }) },
  }))
  if (bad || a.status !== 200 || b.status !== 200) return
  // With the factor off, `false` and the account's own address changes nothing.
  if (acct.password && !(factor === false && email.toLowerCase() === acct.email)) acct.email = email.toLowerCase()
  await both('getSession after updateEmail', GET, { token: acct })
  if (acct.password) await both('createSession by the email after updateEmail', LOGIN, { body: { identifier: chance(0.5) ? mixCase(acct.email) : acct.email, password: acct.password } })
}

/// Each account's app password for these steps, made once, with a session
/// of it: `{privileged, sides}`, each side's `password` and `access` token.
const appSessions = new Map()
async function appSession(acct) {
  if (appSessions.has(acct)) return appSessions.get(acct)
  const privileged = chance(0.5)
  const request = { token: acct, body: { name: `email-${acct.n}`, privileged } }
  const [a, b] = await Promise.all([xrpc(ref, CREATE_AP, request), xrpc(cand, CREATE_AP, request)])
  // The password and createdAt differ; their form is SESSIONS.md's, checked there.
  const masked = (side, res) => {
    const n = normalize(side, res, CREATE_AP)
    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(CREATE_AP, shown(request), na, nb)
  count('createAppPassword for the email steps', a.status < 400)
  if (a.status !== 200 || b.status !== 200) return null
  const sides = { reference: { password: a.body.password }, server: { password: b.body.password } }
  const [c, d] = await both('createSession with the email steps\' app password', LOGIN, (side) => ({ body: { identifier: acct.handle, password: sides[side.name].password } }))
  if (c.status !== 200 || d.status !== 200) return null
  sides.reference.access = c.body.accessJwt
  sides.server.access = d.body.accessJwt
  const s = { privileged, sides }
  appSessions.set(acct, s)
  return s
}

/// createSession for `acct` by handle, email or DID, with `password`, and
/// `extra` (or what it gives for the side) in its input.
function login(acct, extra = {}, password = acct.password) {
  const by = pick(['handle', 'email', 'did'])
  return (side) => ({ body: { identifier: by === 'did' ? didOf(side, acct) : acct[by], password: tokenOn(side, password), ...tokenOn(side, extra) } })
}

/// The email factor, in one step: turned on, for an account confirmed or
/// not (confirmed first, mostly); createSession without the code, with
/// wrong codes, with an app password, and with the code, once and again;
/// then turned off, without a token, with a wrong one, and with the one
/// mailed. It is off again when the step ends (spec/EMAIL.md, "The
/// account's email", "updateEmail", "The email factor and createSession").
export async function emailFactor(acct) {
  await strays()
  const turnOn = (kind) => call(kind, UPDATE, { token: acct, body: { email: chance(0.3) ? mixCase(acct.email) : acct.email, emailAuthFactor: true, ...(chance(0.3) ? { token: pick(NEVER) } : {}) } })
  if (!acct.password) return void (await turnOn('updateEmail turning the email factor on, no password'))
  const [s] = await both('getSession before the email factor', GET, { token: acct })
  if (!s.body?.emailConfirmed) {
    if (chance(0.3)) return void (await turnOn('updateEmail turning the email factor on, email unconfirmed'))
    await call('requestEmailConfirmation for the email factor', REQUEST_CONFIRM, { method: 'POST', token: acct })
    const t = tokensOf(acct, 'confirm_email')
    const i = t.reference.length - 1
    await call('confirmEmail for the email factor', CONFIRM, (side) => ({ token: acct, body: { email: acct.email, token: t[side.name][i] } }))
  }
  const [a, b] = await turnOn('updateEmail turning the email factor on')
  if (a.status !== 200 || b.status !== 200) return
  await both('getSession with the email factor on', GET, { token: acct })
  for (let i = 0, n = 1 + below(2); i < n; i++) await call('createSession with the email factor on, no code', LOGIN, login(acct))
  const codes = tokensOf(acct, 'auth_factor')
  const cur = codes.reference.length - 1
  for (let k = 0, n = below(3); k < n; k++) {
    const r = rand()
    if (r < 0.25 && cur > 0) {
      const i = below(cur)
      await call('createSession with the email factor on, a code replaced since', LOGIN, login(acct, (side) => ({ authFactorToken: codes[side.name][i] })))
    } else if (r < 0.45) {
      await call('createSession with the email factor on, a code never made', LOGIN, login(acct, { authFactorToken: pick(NEVER) }))
    } else if (r < 0.6 && tokensOf(acct, 'confirm_email').reference.length) {
      const t = tokensOf(acct, 'confirm_email')
      const i = t.reference.length - 1
      await call("createSession with the email factor on, another purpose's token", LOGIN, login(acct, (side) => ({ authFactorToken: t[side.name][i] })))
    } else if (r < 0.8) {
      await call('createSession with the email factor on, a wrong password and the code', LOGIN, login(acct, (side) => ({ authFactorToken: codes[side.name][cur] }), `${acct.password}x`))
    } else {
      const app = await appSession(acct)
      if (app) await call('createSession with the email factor on, an app password, no code', LOGIN, login(acct, {}, (side) => app.sides[side.name].password))
    }
  }
  const lower = chance(0.3)
  const code = (side) => ({ authFactorToken: lower ? codes[side.name][cur].toLowerCase() : codes[side.name][cur] })
  await call(`createSession with the email factor on, the code${lower ? ' in lower case' : ''}`, LOGIN, login(acct, code))
  if (chance(0.5)) await call('createSession with the email factor on, the code again', LOGIN, login(acct, code))
  await oauthSignInFactor(acct)
  const email = acct.email
  await call('updateEmail turning the email factor off, no token', UPDATE, { token: acct, body: { email, emailAuthFactor: false } })
  if (chance(0.3)) await call('updateEmail turning the email factor off, a wrong token', UPDATE, { token: acct, body: { email, emailAuthFactor: false, token: pick(NEVER) } })
  const u = tokensOf(acct, 'update_email')
  const j = u.reference.length - 1
  await call('updateEmail turning the email factor off, the token', UPDATE, (side) => ({ token: acct, body: { email, emailAuthFactor: false, token: u[side.name][j] } }))
  await both('getSession with the email factor off', GET, { token: acct })
}

/// The email factor turned on (`true`) or off for `acct` on both sides,
/// its email confirmed first if it is not, each call compared with the
/// emails it sent, for checks/pages.mjs. Answers whether it changed on
/// both sides.
export async function setEmailFactor(acct, on) {
  await strays()
  if (on) {
    const [s] = await both('getSession before the email factor (pages)', GET, { token: acct })
    if (!s.body?.emailConfirmed) {
      await call('requestEmailConfirmation for the email factor (pages)', REQUEST_CONFIRM, { method: 'POST', token: acct })
      const t = tokensOf(acct, 'confirm_email')
      const i = t.reference.length - 1
      await call('confirmEmail for the email factor (pages)', CONFIRM, (side) => ({ token: acct, body: { email: acct.email, token: t[side.name][i] } }))
    }
    const [a, b] = await call('updateEmail turning the email factor on (pages)', UPDATE, { token: acct, body: { email: acct.email, emailAuthFactor: true } })
    return a.status === 200 && b.status === 200
  }
  await call('requestEmailUpdate turning the email factor off (pages)', REQUEST_UPDATE, { method: 'POST', token: acct })
  const u = tokensOf(acct, 'update_email')
  const j = u.reference.length - 1
  const [a, b] = await call('updateEmail turning the email factor off (pages)', UPDATE, (side) => ({ token: acct, body: { email: acct.email, emailAuthFactor: false, token: u[side.name][j] } }))
  return a.status === 200 && b.status === 200
}

/// The emails both sides sent since they were last taken, compared, their
/// tokens kept; answers each side's sign-in codes for `acct`, oldest first.
export async function signInCodes(acct, what) {
  keep(await checkMail(what, { pages: what }))
  return tokensOf(acct, 'auth_factor')
}

/// OAuth's sign-in with the email factor on (spec/OAUTH.md, "The API"): on
/// a new device, without a code, which mails one; with a code never made;
/// with the code mailed; then, on that device, now remembered, a sign-in of
/// another request without a code; and on another new device, without a
/// code again. Each compared, with the emails.
async function oauthSignInFactor(acct) {
  if (!handleOf(acct)) return
  const browsers = { reference: new Browser(), server: new Browser() }
  const fresh = async (b, kind) => {
    const req = await newRequest(acct, { client: CLIENTS[1], kind: `PAR (${kind})` })
    if (!req) return null
    await loadPage(req, b, `authorization page (${kind})`)
    return req
  }
  const signInWith = async (req, b, kind, extra) => {
    const r = await signIn(acct, req, b, { identifier: 'handle', remember: true, kind, extra })
    keep(await checkMail(kind, { signIn: kind }))
    return r
  }
  const req = await fresh(browsers, 'email factor on')
  if (!req) return
  await signInWith(req, browsers, 'OAuth sign-in with the email factor on, no code')
  const codes = tokensOf(acct, 'auth_factor')
  const cur = codes.reference.length - 1
  await signInWith(req, browsers, 'OAuth sign-in with the email factor on, a code never made', () => ({ emailOtp: pick(NEVER) }))
  if (cur >= 0) await signInWith(req, browsers, 'OAuth sign-in with the email factor on, the code', (side) => ({ emailOtp: codes[side.name][cur] }))
  const again = await fresh(browsers, 'email factor on, the device remembered')
  if (again) await signInWith(again, browsers, 'OAuth sign-in with the email factor on, on a device it signed in on, no code')
  const other = { reference: new Browser(), server: new Browser() }
  const elsewhere = await fresh(other, 'email factor on, another device')
  if (elsewhere) await signInWith(elsewhere, other, 'OAuth sign-in with the email factor on, on another device, no code')
}

/// requestPasswordReset by the account's email, one no account has, one only
/// an account without a password had, or no address; then, mostly,
/// resetPassword with a token picked as pickToken says, or another
/// account's, and a new password, one of 256 UTF-16 units, one over, or
/// `""` (then set again). After a reset: createSession with the old and new
/// password, and refreshSession with a session from before (spec/EMAIL.md,
/// "requestPasswordReset", "resetPassword").
export async function passwordReset(acct) {
  await strays()
  const free = freeEmails()
  const r = rand()
  let [which, email] = ['an email no account has', `${freshFront()}@example.com`]
  if (acct.password && r < 0.7) [which, email] = ["the account's email", chance(0.5) ? mixCase(acct.email) : acct.email]
  else if (r < 0.8 && free.length) [which, email] = ['an email only an account without a password had', pick(free)]
  else if (r < 0.9) [which, email] = ['no address', pick(['not-an-email', ''])]
  const bad = chance(0.04) ? pick([{}, { email: 5 }]) : null
  const auth = chance(0.1) ? 'never-given-out' : undefined
  await call(bad ? 'requestPasswordReset, bad input' : `requestPasswordReset by ${which}${auth ? ', a token never given out' : ''}`, REQUEST_RESET, { token: auth, body: bad ?? { email } })
  if (chance(0.25)) return

  const owners = accounts.filter((a) => a !== acct && a.password && tokensOf(a, 'reset_password').reference.length)
  let owner = acct
  let how, token
  if (owners.length && chance(0.1)) {
    owner = pick(owners)
    const t = tokensOf(owner, 'reset_password')
    const i = t.reference.length - 1
    ;[how, token] = ["another account's", (side) => t[side.name][i]]
  } else [how, token] = pickToken(acct, 'reset_password')
  const p = rand()
  const [pw, password] = p < 0.6 ? ['a new password', `pw-${freshFront()}`] : p < 0.7 ? ['a password of 256 UTF-16 units', EMOJI.repeat(128)] : p < 0.85 ? ['a password too long', pick(['p'.repeat(257), EMOJI.repeat(129)])] : ['the empty password', '']
  const before = { password: owner.password, refresh: { reference: owner.sides.reference.refresh, server: owner.sides.server.refresh } }
  const pending = await beforeReset(owner)
  const auth2 = chance(0.1) ? 'never-given-out' : undefined
  const [a, b] = await call(`resetPassword with ${how} token, ${pw}`, RESET, (side) => ({ token: auth2, body: { token: token(side), password } }))
  if (a.status !== 200 || b.status !== 200) return
  let now = password
  if (password === '') {
    await both('createSession with the empty password, after resetPassword', LOGIN, { body: { identifier: owner.handle, password: '' } })
    await call('requestPasswordReset, to set a password again', REQUEST_RESET, { body: { email: owner.email } })
    const t = tokensOf(owner, 'reset_password')
    const i = t.reference.length - 1
    now = `pw-${freshFront()}`
    const [c, d] = await call('resetPassword, setting a password again', RESET, (side) => ({ body: { token: t[side.name][i], password: now } }))
    if (c.status !== 200 || d.status !== 200) return afterReset(owner, pending)
  }
  owner.password = now
  await both('createSession with the old password, after resetPassword', LOGIN, { body: { identifier: owner.handle, password: before.password } })
  await both('createSession with the new password, after resetPassword', LOGIN, login(owner))
  await both('refreshSession with a session from before resetPassword', REFRESH, (side) => ({ method: 'POST', token: before.refresh[side.name] }))
  await afterReset(owner, pending)
}

/// Before a resetPassword, sometimes: an OAuth session of the account, if
/// it has none, and a request approved for it, whose code is not exchanged.
/// Answers the approved request, or null.
async function beforeReset(owner) {
  if (!owner.password || !handleOf(owner) || !chance(0.5)) return null
  if (!oauthOf(owner).sessions.length) await oauthLogin(owner, { reject: false, narrow: false })
  return approved(owner)
}

/// After a resetPassword, held to spec/EMAIL.md on the server alone, as
/// the reference keeps them all: each OAuth session of the account ended,
/// `getSession` `401 invalid_token` and a refresh `400 invalid_grant`; the
/// code of the request approved before refused, `400 invalid_grant`; and
/// the account on the page of no device it signed in on (spec/EMAIL.md,
/// "resetPassword", "What the reference does that the server does not
/// copy"). The harness then drops those sessions and devices on both sides.
async function afterReset(owner, pending) {
  const st = oauthOf(owner)
  const held = async (what, want, got) => {
    if (!isDeepStrictEqual(want, got)) await differ(`the server's ${what}, after resetPassword (spec/EMAIL.md: the reference keeps it)`, { account: `<did:${owner.n}>` }, want, got)
    count(`email: ${what} after resetPassword, on the server alone`, false)
  }
  for (const s of [...st.sessions, ...(st.imagesOnly ? [st.imagesOnly] : []), ...(owner.oauthConfidential ?? [])]) {
    const g = await getSessionOn(cand, s.dpop.server, s.tokens.server.access)
    await held('getSession with an OAuth session from before', { status: 401, www: 'invalid_token' }, { status: g.status, www: wwwError(g.headers?.['www-authenticate']) })
    if (s.client?.confidential) continue
    const r = await tokenEndpoint(cand, s.dpop.server, { grant_type: 'refresh_token', client_id: s.clientId, refresh_token: s.tokens.server.refresh })
    await held('a refresh of an OAuth session from before', { status: 400, error: 'invalid_grant' }, { status: r.status, error: r.body?.error ?? null })
  }
  if (pending) {
    const r = await tokenEndpoint(cand, pending.req.dpop.server, { grant_type: 'authorization_code', client_id: pending.req.clientId, redirect_uri: pending.req.redirect, code: pending.codes.server, code_verifier: pending.req.pk.verifier })
    await held('the code of a request approved before', { status: 400, error: 'invalid_grant' }, { status: r.status, error: r.body?.error ?? null })
  }
  for (const browsers of [st.browsers, ...(pending ? [pending.browsers] : [])]) {
    const req = await newRequest(owner, { client: CLIENTS[1], kind: 'PAR (after resetPassword)' })
    if (!req) break
    const page = await browsers.server.navigate(pageUrl(cand, req.clientId, req.requestUri.server))
    const listed = (page.data.__sessions ?? []).some((x) => x.account?.did === didOf(cand, owner))
    await held('the page on a device it signed in on', { listed: false }, { listed })
  }
  st.sessions.length = 0
  st.imagesOnly = null
  owner.oauthConfidential = []
  st.browsers = { reference: new Browser(), server: new Browser() }
  st.remembered = false
}

/// The four methods of this page that take a token, with a session of an
/// app password, privileged or not: two take it, two do not (spec/EMAIL.md,
/// "requestEmailConfirmation", "confirmEmail", "requestEmailUpdate",
/// "updateEmail").
export async function appPasswordEmail(acct) {
  await strays()
  const s = await appSession(acct)
  if (!s) return
  const kind = s.privileged ? 'a privileged app password' : 'an app password'
  const token = (side) => s.sides[side.name].access
  const r = below(4)
  if (r === 0) await call(`requestEmailConfirmation with ${kind}`, REQUEST_CONFIRM, (side) => ({ method: 'POST', token: token(side) }))
  else if (r === 1) {
    const [how, t] = pickToken(acct, 'confirm_email')
    await call(`confirmEmail with ${kind}, ${how} token`, CONFIRM, (side) => ({ token: token(side), body: { email: acct.email, token: t(side) } }))
  } else if (r === 2) await call(`requestEmailUpdate with ${kind}`, REQUEST_UPDATE, (side) => ({ method: 'POST', token: token(side) }))
  else {
    const email = `${freshFront()}@example.com`
    await call(`updateEmail with ${kind}`, UPDATE, (side) => ({ token: token(side), body: { email } }))
  }
}

/// An email the SMTP server refuses: requestEmailConfirmation or
/// requestPasswordReset for the account, with the server's SMTP server
/// refusing each message for that one call. The reference sends its email;
/// the server, which keeps the token before sending, answers `500
/// InternalServerError`, held to the spec on the server alone, and its
/// development sink records the email as the reference's mailer does. Then
/// the token it could not send, given back, works as the reference's:
/// confirmEmail, then getSession; or resetPassword with a new password,
/// then createSession with the old and the new, as `passwordReset` after
/// a reset (spec/EMAIL.md, "SMTP").
export async function smtpRefused(acct) {
  const sink = smtp()
  if (!sink || !acct.password) return
  await strays()
  const reset = chance(0.4)
  const [kind, nsid, request] = reset
    ? ['requestPasswordReset, the SMTP server refusing its email', REQUEST_RESET, { body: { email: acct.email } }]
    : ['requestEmailConfirmation, the SMTP server refusing its email', REQUEST_CONFIRM, { method: 'POST', token: acct }]
  sink.refusing = true
  let a, b
  try {
    ;[a, b] = await Promise.all([xrpcHttp(ref, nsid, request), xrpcHttp(cand, nsid, request)])
  } finally {
    sink.refusing = false
  }
  const [na, nb] = [normalize(ref, a, nsid), normalize(cand, b, nsid)]
  const want = na.status === 200 ? { status: 500, error: 'InternalServerError' } : na
  if (!isDeepStrictEqual(nb, want)) await differ(`${nsid}, the SMTP server refusing its email`, shown(request), want, nb, na.status === 200 ? 'held to spec/EMAIL.md ("SMTP") on the server alone: the reference sent its email' : undefined)
  count(kind, false)
  const sent = await checkMail(kind, shown(request))
  keep(sent)
  if (na.status !== 200 || !sent.server.length) return
  if (!reset) {
    const t = tokensOf(acct, 'confirm_email')
    const i = t.reference.length - 1
    const [c, d] = await call('confirmEmail with the token of an email the SMTP server refused', CONFIRM, (side) => ({ token: acct, body: { email: acct.email, token: t[side.name][i] } }))
    if (c.status === 200 && d.status === 200) await both('getSession after confirmEmail', GET, { token: acct })
    return
  }
  const t = tokensOf(acct, 'reset_password')
  const i = t.reference.length - 1
  const [old, password] = [acct.password, `pw-${freshFront()}`]
  const [c, d] = await call('resetPassword with the token of an email the SMTP server refused', RESET, (side) => ({ body: { token: t[side.name][i], password } }))
  if (c.status !== 200 || d.status !== 200) return
  acct.password = password
  await both('createSession with the old password, after resetPassword', LOGIN, { body: { identifier: acct.handle, password: old } })
  await both('createSession with the new password, after resetPassword', LOGIN, login(acct))
  await afterReset(acct, null)
}