~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
461 lines · 24.2 KB Raw History
// Sessions: their tokens, refreshSession, deleteSession, and app passwords
// (spec/SESSIONS.md). Each is held to the reference, and every token either
// side answers is decoded and held to the claims the spec gives.

import { isDeepStrictEqual } from 'node:util'
import { COLLECTIONS, below, chance, goodRecord, pick, rand } from '../lib/random.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { fail } from '../lib/plc.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { normalize, shown, xrpc } from '../lib/xrpc.mjs'

const REFRESH = 'com.atproto.server.refreshSession'
const DELETE = 'com.atproto.server.deleteSession'
const GET = 'com.atproto.server.getSession'
const LOGIN = 'com.atproto.server.createSession'
const CREATE_AP = 'com.atproto.server.createAppPassword'
const LIST_AP = 'com.atproto.server.listAppPasswords'
const REVOKE_AP = 'com.atproto.server.revokeAppPassword'
const CREATE_RECORD = 'com.atproto.repo.createRecord'
/// A DID no server here holds.
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'

const FULL = 'com.atproto.access'
const APP = 'com.atproto.appPass'
const PRIVILEGED = 'com.atproto.appPassPrivileged'
const ACCESS_LIFE = 7200
const REFRESH_LIFE = 90 * 24 * 3600
const APP_PASSWORD = /^[a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4}-[a-z2-7]{4}$/
const DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/
/// Both sides, once `start` has set them.
const sides = () => [ref, cand]

/// Each account's sessions, oldest first: `{scope, app, sides}`, where `app`
/// names the app password it was made with, and `sides` holds, by side name,
/// its `access` and `refresh` tokens there. Ended and replaced sessions stay,
/// to be used again.
const pools = new Map()
/// Each account's app passwords by name, `{privileged, revoked, sides}`, with
/// `sides` holding each side's `password` and `createdAt`.
const passwordsByAccount = new Map()
/// Each side's refresh token ids, named by the order the harness first saw
/// them, so that the sessions refreshes answer can be compared.
const jtis = { reference: new Map(), server: new Map() }
const jtiName = (side, jti) => {
  const names = jtis[side.name]
  if (!names.has(jti)) names.set(jti, `<jti:${names.size + 1}>`)
  return names.get(jti)
}

const seconds = () => Date.now() / 1000

/// A JWT's header and payload, or null if it is not one.
function decode(token) {
  const parts = typeof token === 'string' ? token.split('.') : []
  if (parts.length !== 3) return null
  try {
    const [header, payload] = parts.slice(0, 2).map((p) => JSON.parse(Buffer.from(p, 'base64url').toString('utf8')))
    return header && payload && typeof header === 'object' && typeof payload === 'object' ? { header, payload } : null
  } catch {
    return null
  }
}

/// The session tokens `body` holds on `side`, held to spec/SESSIONS.md's
/// claims for `acct` and `scope` (spec/SESSIONS.md, "Tokens"). With
/// `window`, `[t0, t1]` in seconds, `iat` must be within a second of it.
/// Answers the refresh token's `jti`.
async function checkTokens(side, acct, body, scope, window, request) {
  const did = didOf(side, acct)
  const named = (d) => (d === did ? `<did:${acct.n}>` : d)
  let jti
  for (const [field, typ, wantScope, life] of [['accessJwt', 'at+jwt', scope, ACCESS_LIFE], ['refreshJwt', 'refresh+jwt', 'com.atproto.refresh', REFRESH_LIFE]]) {
    const jwt = decode(body?.[field])
    const what = `${field} (spec/SESSIONS.md)`
    if (!jwt) {
      await fail(side, what, request, 'a JWT', body?.[field])
      continue
    }
    const { iat, exp, sub, aud, jti: id, scope: s, ...rest } = jwt.payload
    const timely = Number.isInteger(iat) && (!window || (iat >= Math.floor(window[0]) - 1 && iat <= Math.ceil(window[1]) + 1))
    const got = {
      typ: jwt.header.typ,
      scope: s,
      sub: named(sub),
      aud,
      ...(field === 'refreshJwt' ? { jti: typeof id === 'string' && id ? '<jti>' : id } : id === undefined ? {} : { jti: id }),
      iat: timely ? '<iat>' : iat,
      // The reference reads the clock for `iat` and again for `exp`, so it
      // gives a second more when the two reads fall either side of one; the
      // server is held to the life exactly.
      life: !Number.isInteger(exp) || !Number.isInteger(iat) ? exp : side === ref && exp - iat === life + 1 ? life : exp - iat,
      ...rest,
    }
    const want = { typ, scope: wantScope, sub: `<did:${acct.n}>`, aud: 'did:web:localhost', ...(field === 'refreshJwt' ? { jti: '<jti>' } : {}), iat: '<iat>', life }
    if (!isDeepStrictEqual(got, want)) await fail(side, what, request, want, { ...got, ...(timely ? {} : { window }) })
    if (field === 'refreshJwt') jti = id
  }
  return jti
}

/// The same request to both sides, compared once `transform` has taken out,
/// of each side's normalized answer, what it checks itself. `request` is a
/// function of the side, or the same for both.
async function compare(kind, nsid, request, transform = (side, n) => n) {
  const on = (side) => (typeof request === 'function' ? request(side) : request)
  const t0 = seconds()
  const [a, b] = await Promise.all(sides().map((side) => xrpc(side, nsid, on(side))))
  const window = [t0, seconds()]
  const [na, nb] = [transform(ref, normalize(ref, a, nsid), a), transform(cand, normalize(cand, b, nsid), b)]
  if (!isDeepStrictEqual(na, nb)) await differ(nsid, shown(request), na, nb)
  count(kind, a.status < 400)
  return { a, b, window }
}

/// The account's sessions, with the one its token came from.
function sessionsOf(acct) {
  if (!pools.has(acct)) pools.set(acct, [])
  const pool = pools.get(acct)
  const { reference: r, server: s } = acct.sides
  if (r.refresh && s.refresh && !pool.some((x) => x.sides.reference.refresh === r.refresh)) {
    pool.push({ scope: FULL, app: null, sides: { reference: { access: r.token, refresh: r.refresh }, server: { access: s.token, refresh: s.refresh } }, seed: true })
  }
  return pool
}

/// A session of the account: the newest half the time. The tokens of a
/// session from createAccount or createSession are checked the first time,
/// all but `iat`'s time.
async function pickSession(acct, scopes) {
  const pool = sessionsOf(acct).filter((s) => !scopes || scopes.includes(s.scope))
  if (!pool.length) return null
  const s = chance(0.5) ? pool[pool.length - 1] : pick(pool)
  if (s.seed && !s.checked) {
    s.checked = true
    for (const side of sides()) {
      const { access: accessJwt, refresh: refreshJwt } = s.sides[side.name]
      const jti = await checkTokens(side, acct, { accessJwt, refreshJwt }, FULL, null, { tokens: `of <did:${acct.n}>'s createAccount or createSession` })
      jtiName(side, jti)
    }
  }
  return s
}

/// A new session both sides answered, `a` and `b`, of `scope`: its tokens are
/// checked on each side, its refresh token's id must name the same session on
/// both, and it joins the account's sessions.
async function newSession(acct, scope, app, a, b, window, request) {
  const ids = {}
  for (const [side, res] of [[ref, a], [cand, b]]) ids[side.name] = await checkTokens(side, acct, res.body, scope, window, request)
  const [na, nb] = [jtiName(ref, ids.reference), jtiName(cand, ids.server)]
  if (na !== nb) await differ('the session a refresh token names', request, na, nb, 'refresh token ids by the order first seen: a refresh must answer the same session on both sides (spec/SESSIONS.md)')
  const session = { scope, app, sides: { reference: { access: a.body.accessJwt, refresh: a.body.refreshJwt }, server: { access: b.body.accessJwt, refresh: b.body.refreshJwt } } }
  const pool = sessionsOf(acct)
  if (!pool.some((s) => s.sides.reference.refresh === session.sides.reference.refresh)) pool.push(session)
  if (pool.length > 12) {
    const old = pool.findIndex((x) => !x.seed)
    if (old >= 0) pool.splice(old, 1)
  }
  return session
}

/// refreshSession with a session's refresh token: new, replaced or ended.
/// Sometimes the account carries on with the new access token
/// (spec/SESSIONS.md, "refreshSession").
export async function refreshSession(acct) {
  const s = await pickSession(acct)
  if (!s) return
  await refreshWith(acct, s, 'refreshSession')
}

async function refreshWith(acct, s, kind) {
  const request = (side) => ({ token: s.sides[side.name].refresh, method: 'POST' })
  const { a, b, window } = await compare(kind, REFRESH, request)
  if (a.status !== 200) return
  const n = await newSession(acct, s.scope, s.app, a, b, window, shown(request))
  if (n.scope === FULL && chance(0.3)) {
    acct.sides.reference = { ...acct.sides.reference, token: n.sides.reference.access, refresh: n.sides.reference.refresh }
    acct.sides.server = { ...acct.sides.server, token: n.sides.server.access, refresh: n.sides.server.refresh }
  }
}

/// deleteSession with a session's refresh token; then sometimes its refresh
/// token again, or its access token, which still works (spec/SESSIONS.md,
/// "deleteSession").
export async function deleteSession(acct) {
  const s = await pickSession(acct)
  if (!s) return
  await compare('deleteSession', DELETE, (side) => ({ token: s.sides[side.name].refresh, method: 'POST' }))
  const r = rand()
  if (r < 0.4) await refreshWith(acct, s, 'refreshSession after deleteSession')
  else if (r < 0.7) await compare('getSession after deleteSession', GET, (side) => ({ token: s.sides[side.name].access }))
}

/// A token of the wrong kind, or changed after it was signed.
function tampered(token, change) {
  const parts = typeof token === 'string' ? token.split('.') : []
  const jwt = decode(token)
  if (!jwt) return `${token}x`
  if (change === 'none') return [Buffer.from(JSON.stringify({ ...jwt.header, alg: 'none' })).toString('base64url'), parts[1], ''].join('.')
  return [parts[0], Buffer.from(JSON.stringify({ ...jwt.payload, sub: change })).toString('base64url'), parts[2]].join('.')
}

/// The methods that take an access token, with input that is fine but for
/// the token.
const ACCESS_METHODS = (acct) => [
  [GET, () => ({})],
  [LIST_AP, () => ({})],
  [CREATE_AP, () => ({ body: { name: pick(['wrong-token', '']) } })],
  [REVOKE_AP, () => ({ body: { name: 'wrong-token' } })],
  [CREATE_RECORD, (side) => {
    const collection = pick(COLLECTIONS)
    return { body: { repo: didOf(side, acct), collection, record: goodRecord(collection) } }
  }],
]
const REFRESH_METHODS = [REFRESH, DELETE]

/// Tokens where they do not belong: a refresh token where an access token is
/// wanted, an access token where a refresh token is, one with its `sub`
/// changed or its `alg` made `none`, one never given out, none, and
/// `Authorization` headers of other schemes and shapes; and a session's
/// access token, whatever became of it, on getSession (spec/SESSIONS.md,
/// "Which token where").
export async function wrongTokens(acct) {
  const s = await pickSession(acct)
  if (!s) return
  const other = accounts.find((x) => x !== acct)
  const subOf = (side) => (other ? didOf(side, other) : NOBODY)
  const accessMethod = pick(ACCESS_METHODS(acct))
  const refreshMethod = pick(REFRESH_METHODS)
  const at = (method, token) => (side) => ({ ...(method[1] ? method[1](side) : {}), token: token(side), method: 'POST', ...(method[0] === GET || method[0] === LIST_AP ? { method: 'GET' } : {}) })
  const r = rand()
  const access = (side) => s.sides[side.name].access
  const refresh = (side) => s.sides[side.name].refresh
  if (r < 0.2) return void (await compare('a refresh token where an access token is wanted', accessMethod[0], at(accessMethod, refresh)))
  if (r < 0.35) return void (await compare('an access token where a refresh token is wanted', refreshMethod, at([refreshMethod], access)))
  if (r < 0.55) {
    const which = chance(0.5)
    const change = chance(0.5) ? 'none' : null
    const token = (side) => tampered(which ? access(side) : refresh(side), change ?? subOf(side))
    const method = which ? accessMethod : [refreshMethod]
    return void (await compare(`a token ${change ? 'with alg none' : 'with its sub changed'}`, method[0], at(method, token)))
  }
  if (r < 0.65) {
    const method = chance(0.5) ? accessMethod : [refreshMethod]
    const token = chance(0.5) ? 'never-given-out' : undefined
    return void (await compare(`${token ? 'a token never given out' : 'no token'}`, method[0], at(method, () => token)))
  }
  if (r < 0.8) return void (await headers(acct, s, accessMethod, refreshMethod))
  await compare('an access token, whatever became of its session', GET, (side) => ({ token: access(side) }))
}

/// `Authorization` headers that are not `Bearer <token>`: the scheme in
/// lower case, `Basic`, an unknown scheme, and three words. Over XRPC only
/// (spec/SESSIONS.md, "Which token where").
async function headers(acct, s, accessMethod, refreshMethod) {
  const toRefresh = chance(0.4)
  const [nsid, input] = toRefresh ? [refreshMethod, () => ({})] : accessMethod
  const token = (side) => s.sides[side.name][toRefresh ? 'refresh' : 'access']
  const variants = [
    ['Basic', () => `Basic ${Buffer.from('admin:password').toString('base64')}`],
    ['an unknown scheme', (side) => `Token ${token(side)}`],
    ['three words', (side) => `Bearer ${token(side)} x`],
    ['one word', () => 'Bearer'],
  ]
  // `bearer` in lower case is `Bearer`; with a refresh token or a write it
  // would change something, and listAppPasswords answers times that differ,
  // so it goes with an access token to getSession.
  if (nsid === GET) variants.push(['the scheme in lower case', (side) => `bearer ${token(side)}`])
  const [name, header] = pick(variants)
  const answers = []
  for (const side of sides()) {
    const { body } = input(side)
    const res = await fetch(`${side.url}/xrpc/${nsid}`, {
      method: nsid === GET || nsid === LIST_AP ? 'GET' : 'POST',
      headers: { authorization: header(side), ...(body ? { 'content-type': 'application/json' } : {}) },
      body: body ? JSON.stringify(body) : undefined,
    })
    const text = await res.text()
    let parsed = null
    try {
      parsed = text ? JSON.parse(text) : null
    } catch {
      parsed = { unparsed: text.slice(0, 200) }
    }
    answers.push(normalize(side, { status: res.status, body: parsed }, nsid))
  }
  if (!isDeepStrictEqual(answers[0], answers[1])) await differ(nsid, { authorization: name, token: toRefresh ? 'refresh' : 'access' }, answers[0], answers[1], 'an Authorization header that is not Bearer <token>')
  count(`Authorization: ${name}`, answers[0].status < 400)
}

let serial = 0
const ODD_NAMES = ['', ' one', 'ONE', 'one', '日本 🙂 name', 'x'.repeat(300), 'phone']

/// The account's app passwords, by name.
const passwordsOf = (acct) => {
  if (!passwordsByAccount.has(acct)) passwordsByAccount.set(acct, new Map())
  return passwordsByAccount.get(acct)
}

/// An app password's `createdAt` on `side`: a datetime within a second of
/// `window`, in seconds, or the one it was created with.
async function checkCreatedAt(side, createdAt, window, known, request) {
  const ok = typeof createdAt === 'string' && DATETIME.test(createdAt) && (known ? createdAt === known : Math.abs(Date.parse(createdAt) / 1000 - (window[0] + window[1]) / 2) <= (window[1] - window[0]) / 2 + 1)
  if (!ok) await fail(side, 'app password createdAt (spec/SESSIONS.md)', request, known ?? `a datetime within a second of the request, ${new Date(window[0] * 1000).toISOString()}`, createdAt)
}

/// createAppPassword: names new, odd, and the account's already; privileged
/// or not; sometimes with input the lexicon refuses; with a full session or
/// an app password's. Each password must be of the spec's form.
async function createAppPassword(acct, name = null) {
  const passwords = passwordsOf(acct)
  const s = chance(0.75) ? (await pickSession(acct, [FULL])) ?? (await pickSession(acct)) : await pickSession(acct)
  if (!s) return
  const r = rand()
  name ??= r < 0.5 ? `app-${++serial}` : r < 0.75 ? pick(ODD_NAMES) : pick([...passwords.keys(), 'app-0'])
  const privileged = pick([undefined, true, false])
  const bad = chance(0.08) ? pick([{}, { name: 5 }, { name, privileged: 'yes' }, { name: null }]) : null
  const body = bad ?? { name, ...(privileged === undefined ? {} : { privileged }) }
  const request = (side) => ({ body, token: s.sides[side.name].access })
  const { a, b, window } = await compare(`createAppPassword${bad ? ', bad input' : ''}${s.scope === FULL ? '' : ', app password session'}`, CREATE_AP, request, (side, n) =>
    n.status === 200 ? { ...n, body: { ...n.body, password: '<password>', createdAt: '<createdAt>' } } : n,
  )
  if (a.status !== 200) return
  const made = {}
  for (const [side, res] of [[ref, a], [cand, b]]) {
    if (!APP_PASSWORD.test(res.body.password ?? '')) await fail(side, 'app password (spec/SESSIONS.md)', shown(request), 'four groups of four of a-z and 2-7, joined by -', res.body.password)
    await checkCreatedAt(side, res.body.createdAt, window, null, shown(request))
    made[side.name] = { password: res.body.password, createdAt: res.body.createdAt }
  }
  passwords.set(body.name, { privileged: !!body.privileged, revoked: false, sides: made })
}

/// listAppPasswords with any of the account's sessions: each `createdAt` must
/// be the one it was created with, and is then taken out.
async function listAppPasswords(acct) {
  const s = await pickSession(acct)
  if (!s) return
  const passwords = passwordsOf(acct)
  const request = (side) => ({ token: s.sides[side.name].access })
  const { a, b } = await compare('listAppPasswords', LIST_AP, request, (side, n) =>
    n.status === 200 && Array.isArray(n.body?.passwords) ? { ...n, body: { ...n.body, passwords: n.body.passwords.map((p) => ({ ...p, createdAt: '<createdAt>' })) } } : n,
  )
  if (a.status !== 200) return
  for (const [side, res] of [[ref, a], [cand, b]]) for (const p of res.body.passwords) {
    const known = passwords.get(p.name)?.sides[side.name].createdAt
    if (known) await checkCreatedAt(side, p.createdAt, null, known, shown(request))
  }
}

/// revokeAppPassword of a name the account has, one it does not, or one
/// another account has, with any of its sessions.
async function revokeAppPassword(acct) {
  const s = await pickSession(acct)
  if (!s) return
  const passwords = passwordsOf(acct)
  const live = [...passwords].filter(([, p]) => !p.revoked).map(([n]) => n)
  const others = accounts.filter((x) => x !== acct).flatMap((x) => [...passwordsOf(x).keys()])
  const r = rand()
  const name = r < 0.7 && live.length ? pick(live) : r < 0.85 && others.length ? pick(others) : `app-none-${++serial}`
  const body = chance(0.05) ? pick([{}, { name: 5 }]) : { name }
  const { a } = await compare(`revokeAppPassword${s.scope === FULL ? '' : ', app password session'}`, REVOKE_AP, (side) => ({ body, token: s.sides[side.name].access }))
  if (a.status === 200 && passwords.has(body.name)) passwords.get(body.name).revoked = true
}

/// The account's app passwords to log in with, by name: all but one named
/// "", whose sessions the reference makes full sessions when they are
/// refreshed, a fault the server does not copy (spec/SESSIONS.md).
const loginPasswordsOf = (acct) => [...passwordsOf(acct)].filter(([name]) => name !== '')

/// createSession with an app password, live or revoked: by handle, email or
/// DID, the handle in upper case, the password in upper case or another
/// account's.
async function loginWithAppPassword(acct) {
  const passwords = loginPasswordsOf(acct)
  if (!passwords.length) return createAppPassword(acct)
  const [name, ap] = pick(passwords)
  const by = pick(['handle', 'email', 'did', 'HANDLE'])
  const fault = chance(0.15) ? pick(['upper case', 'another account\'s']) : null
  const others = accounts.filter((x) => x !== acct && loginPasswordsOf(x).length)
  const owner = fault === 'another account\'s' && others.length ? pick(others) : acct
  const [theirName, theirs] = owner !== acct ? pick(loginPasswordsOf(owner)) : [null, null]
  const password = (side) => (theirs ? theirs.sides[side.name].password : fault === 'upper case' ? ap.sides[side.name].password.toUpperCase() : ap.sides[side.name].password)
  const identifier = (side) => (by === 'did' ? didOf(side, acct) : by === 'email' ? acct.email : by === 'HANDLE' ? acct.handle.toUpperCase() : acct.handle)
  const request = (side) => ({ body: { identifier: identifier(side), password: password(side) } })
  const { a, b, window } = await compare(`createSession with an app password by ${by}${ap.revoked ? ', revoked' : ''}${fault ? `, ${fault}` : ''}`, LOGIN, request)
  if (a.status !== 200) return
  // Another account's app password logs in where the identifier names that
  // account too, as an email an account without a password keeps but does
  // not hold does: the session is that account's.
  const used = theirs ? [owner, theirName, theirs] : [acct, name, ap]
  const [whose] = accounts.filter((x) => didOf(ref, x) === a.body.did)
  if (whose !== used[0]) await differ(LOGIN, shown(request), `a session of <did:${used[0].n}>, whose app password it is`, `<did:${whose?.n}>`, 'the reference fails the check it is held to')
  await newSession(used[0], used[2].privileged ? PRIVILEGED : APP, used[1], a, b, window, shown(request))
}

/// App passwords: made, listed, revoked, and logged in with
/// (spec/SESSIONS.md, "App passwords").
export async function appPasswords(acct) {
  const r = rand()
  if (r < 0.35) await createAppPassword(acct)
  else if (r < 0.55) await listAppPasswords(acct)
  else if (r < 0.7) await revokeAppPassword(acct)
  else await loginWithAppPassword(acct)
}

/// Several refreshSessions at once with one token, which all succeed with
/// tokens of one session; or several createAppPasswords at once with one
/// name, of which one makes it (spec/SESSIONS.md, "refreshSession", "App
/// passwords").
export async function sessionRace(acct) {
  const n = 2 + below(4)
  if (chance(0.6)) {
    const s = await pickSession(acct)
    if (!s) return
    const t0 = seconds()
    const answers = await Promise.all(sides().map((side) => Promise.all(Array.from({ length: n }, () => xrpc(side, REFRESH, { token: s.sides[side.name].refresh, method: 'POST' })))))
    const window = [t0, seconds()]
    const request = { refreshes: n, at: 'once' }
    const [na, nb] = answers.map((rs, i) => rs.map((r) => normalize(sides()[i], r, REFRESH)))
    if (!isDeepStrictEqual(na, nb)) await differ(REFRESH, request, na, nb, 'refreshes at once with one token')
    count('refreshSession race', answers[0][0].status === 200)
    if (answers[0][0].status !== 200) return
    for (const [i, side] of sides().entries()) {
      const ids = new Set()
      for (const r of answers[i]) ids.add(await checkTokens(side, acct, r.body, s.scope, window, request))
      if (ids.size !== 1) await fail(side, 'sessions refreshes at once answer', request, 'one session', `${ids.size} sessions`)
    }
    return void (await newSession(acct, s.scope, s.app, answers[0][0], answers[1][0], window, request))
  }
  const s = await pickSession(acct, [FULL])
  if (!s) return
  const name = `race-${++serial}`
  const t0 = seconds()
  const answers = await Promise.all(sides().map((side) => Promise.all(Array.from({ length: n }, () => xrpc(side, CREATE_AP, { body: { name }, token: s.sides[side.name].access })))))
  const window = [t0, seconds()]
  const request = { createAppPassword: { name }, times: n, at: 'once' }
  const summary = (rs, side) => rs.map((r) => normalize(side, r, CREATE_AP)).map((x) => (x.status === 200 ? 'made' : `${x.status} ${x.error}`)).sort()
  const [sa, sb] = [summary(answers[0], ref), summary(answers[1], cand)]
  if (sa.filter((x) => x === 'made').length !== 1) await differ(CREATE_AP, request, 'one made', sa, 'the reference fails the check it is held to')
  if (!isDeepStrictEqual(sa, sb)) await differ(CREATE_AP, request, sa, sb, 'createAppPasswords at once with one name')
  count('createAppPassword race', true)
  const made = {}
  for (const [i, side] of sides().entries()) {
    const won = answers[i].find((r) => r.status === 200)
    await checkCreatedAt(side, won.body.createdAt, window, null, request)
    made[side.name] = { password: won.body.password, createdAt: won.body.createdAt }
  }
  passwordsOf(acct).set(name, { privileged: false, revoked: false, sides: made })
}

/// After a crash: each account's app passwords, and some of its sessions
/// refreshed, as on the reference, which was not killed (spec/SESSIONS.md,
/// "Durability").
export async function sessionsAfterCrash() {
  for (const acct of accounts) {
    if (passwordsOf(acct).size) await listAppPasswords(acct)
    const pool = sessionsOf(acct)
    for (let i = Math.min(3, pool.length); i > 0; i--) await refreshWith(acct, pick(pool), 'refreshSession after a crash')
  }
}