~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1031 lines · 62.9 KB Raw History
// Accounts moving between servers (spec/MIGRATION.md): to each side from a
// third PDS, the reference on the same PLC directory, and from each side to
// it; and the methods of a move by account state. A run of its own,
// `--moves`: its steps are a move in, a move out, the states and a did:web account, in
// turn, the same requests to both sides, compared, with both firehoses held
// to what each move puts on them.

import http from 'node:http'
import { isDeepStrictEqual } from 'node:util'
import { TestPds } from '@atproto/dev-env'
import { createServiceJwt } from '@atproto/xrpc-server'
import { Secp256k1Keypair, verifySignature } from '@atproto/crypto'
import { cborDecode, cborEncode, cidForCbor } from '@atproto/common'
import { MemoryBlockstore, Repo, WriteOpAction, blocksToCarFile, readCarWithRoot, verifyRepoCar } from '@atproto/repo'
import { MOVES_STEPS } from '../lib/args.mjs'
import { ADMIN_PASSWORD, MAX_REPO_IMPORT } from '../lib/env.mjs'
import { checkMail } from '../lib/mail.mjs'
import { resolveHere, serveHandle } from '../lib/handles.mjs'
import { checkDidDoc, plcLog } from '../lib/plc.mjs'
import { cand, handles, net, plcUrl, ref, wait } from '../lib/processes.mjs'
import { below, chance, pick } from '../lib/random.mjs'
import { count, differ, run } from '../lib/report.mjs'
import { own as ownRules } from '../lib/server.mjs'
import { normalize, strip } from '../lib/xrpc.mjs'
import { subscribe } from './firehose.mjs'

const S = 'com.atproto.server.'
const R = 'com.atproto.repo.'
const I = 'com.atproto.identity.'
const Y = 'com.atproto.sync.'
const A = 'com.atproto.admin.'
/// The collection the run's records are in.
const C = 'com.example.moved'
/// A DID no server here holds.
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
/// A signing key no account has.
const STRANGE_KEY = 'did:key:zQ3shZc2QzApp2oymGvQbzP8eKheVshBHbU4ZYjeXqwSKEn6N'
const basic = (user, password) => `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`
const bearer = (t) => `Bearer ${t}`
const b64 = (o) => Buffer.from(JSON.stringify(o)).toString('base64url')
const sides = () => [ref, cand]
const admin = (side) => (side === ref ? basic('admin', ADMIN_PASSWORD) : cand.admin)

/// The third PDS: `{name, url, pds, mails, did}`.
let old
/// What each side's DIDs and handles are named in what is compared, as
/// normalize's `[value, name]` pairs, longest first.
const names = { reference: [], server: [] }
const name = (side, value, label) => {
  names[side.name].push([value, label])
  names[side.name].sort((x, y) => y[0].length - x[0].length)
}
/// Each side's firehose since the run began.
const hoses = { reference: [], server: [] }

// ---- Requests -------------------------------------------------------------

/// A call to `side` (a side, or the third PDS): `auth` is the whole
/// `Authorization` header. A non-JSON answer that succeeds is `{status,
/// bytes}`.
async function send(side, nsid, { params, body, auth, method, type } = {}) {
  const url = new URL(`${side.url}/xrpc/${nsid}`)
  for (const [k, v] of Object.entries(params ?? {})) if (v !== undefined) url.searchParams.append(k, String(v))
  const headers = {}
  if (auth) headers.authorization = auth
  let payload
  if (body instanceof Uint8Array) {
    if (type !== null) headers['content-type'] = type ?? 'application/vnd.ipld.car'
    payload = body
  } else if (body !== undefined) {
    headers['content-type'] = 'application/json'
    payload = JSON.stringify(body)
  }
  try {
    const r = await fetch(url, { method: method ?? (body === undefined ? 'GET' : 'POST'), headers, body: payload })
    const ct = r.headers.get('content-type') ?? ''
    if (r.ok && !ct.startsWith('application/json')) {
      const bytes = new Uint8Array(await r.arrayBuffer())
      return bytes.length ? { status: r.status, bytes } : { status: r.status, body: null }
    }
    const text = await r.text()
    let parsed = null
    try {
      parsed = text ? JSON.parse(text) : null
    } catch {
      parsed = { unparsed: text.slice(0, 200) }
    }
    return { status: r.status, body: parsed }
  } catch (err) {
    return { status: 0, body: { error: `request failed: ${err.message}` } }
  }
}

/// Keys whose values differ between any two servers, by method, taken out
/// once held to what they must be.
const VOLATILE = {
  [`${Y}getLatestCommit`]: ['cid', 'rev'],
  [`${Y}getRepoStatus`]: ['rev'],
  [`${S}checkAccountStatus`]: ['repoCommit', 'repoRev'],
  [`${S}createAppPassword`]: ['password', 'createdAt'],
  [`${S}getServiceAuth`]: ['token'],
  [`${I}signPlcOperation`]: ['operation'],
}

/// An answer as compared: `normalize`'s, with the side's names, a CAR file
/// or blob by its status, and the volatile keys taken out.
function view(side, res, nsid) {
  if (res.bytes) return { status: res.status, body: '<bytes>' }
  const n = normalize(side, res, nsid, names[side.name])
  const drop = new Set(VOLATILE[nsid] ?? [])
  if (!n.body || typeof n.body !== 'object' || !drop.size) return n
  return { ...n, body: Object.fromEntries(Object.entries(n.body).map(([k, v]) => [k, drop.has(k) ? `<${k}>` : v])) }
}

/// A request as the report shows it: the reference's, with its names.
function shownReq(request) {
  const r = typeof request === 'function' ? request(ref) : request
  const auth = typeof r.auth === 'string' ? r.auth.replace(/^(\S+) (\S+\.\S+\.\S*)$/, '$1 <jwt>') : r.auth
  const body = r.body instanceof Uint8Array ? `<${r.body.length} bytes>` : r.body
  return JSON.parse(strip(ref, JSON.stringify({ ...r, auth, body }), names.reference))
}

/// The same request to both sides, compared. `request` is a function of
/// the side, or the same for both; `learn(side, res)`, if given, names
/// what the answers hold before they are compared. Answers both raw
/// answers.
async function same(kind, nsid, request, learn) {
  const on = (side) => (typeof request === 'function' ? request(side) : request)
  const [a, b] = await Promise.all(sides().map((side) => send(side, nsid, on(side))))
  if (learn) {
    learn(ref, a)
    learn(cand, b)
  }
  const [na, nb] = [view(ref, a, nsid), view(cand, b, nsid)]
  if (!isDeepStrictEqual(na, nb)) await differ(`${nsid} (${kind})`, shownReq(request), na, nb)
  count(`moves: ${kind}`, a.status < 400)
  return [a, b]
}

/// What fails a check held to both sides: the reference is held to it too.
const fail = (side, what, request, want, got) => differ(`the ${side.name}'s ${what}`, request, want, got, side === ref ? 'the reference fails the check it is held to' : undefined)

/// A call to the third PDS that must succeed, for the move of `side`'s
/// account: the reference's and the server's must both be taken.
async function must(side, what, nsid, request) {
  const res = await send(old, nsid, request)
  if (res.status !== 200) await fail(side, `${what}, taken by the reference it moves to`, { nsid, ...request, auth: request.auth && '<auth>', body: request.body instanceof Uint8Array ? `<${request.body.length} bytes>` : request.body }, 200, { status: res.status, body: res.body })
  count(`moves: ${what} at the reference it moves to`, res.status < 400)
  return res
}

// ---- CAR files ------------------------------------------------------------

const varint = (n) => {
  const out = []
  for (; n >= 0x80; n = Math.floor(n / 128)) out.push((n & 0x7f) | 0x80)
  out.push(n)
  return Buffer.from(out)
}

/// A CAR file of `roots` and `blocks`, `[cid, bytes]` pairs.
function carOf(roots, blocks) {
  const header = cborEncode({ version: 1, roots })
  const parts = [varint(header.length), header]
  for (const [cid, bytes] of blocks) parts.push(varint(cid.bytes.length + bytes.length), cid.bytes, bytes)
  return new Uint8Array(Buffer.concat(parts))
}

/// A CAR file's root, commit and blocks.
async function parse(car) {
  const { root, blocks } = await readCarWithRoot(car)
  const entries = []
  for (const { cid, bytes } of blocks.entries()) entries.push([cid, bytes])
  return { root, commit: cborDecode(blocks.get(root)), entries }
}

// ---- Firehoses ------------------------------------------------------------

/// The events of `did` each side has sent since they were last taken, as
/// compared: type, and `active`, `status` and whether there is a `handle`.
/// An event may reach a subscriber a while after the call that made it
/// answered: the reference polls for new events, backing off up to a
/// second when there are none. So this waits until each side has sent at
/// least `want[side]` events of the DID and nothing new for 400 ms, or 6
/// seconds.
async function eventsOf(did, want) {
  const mineOn = (side) => hoses[side.name].filter((e) => (e.body?.did ?? e.body?.repo) === did[side.name]).length
  let last = ''
  let quiet = 0
  for (let t = Date.now(); Date.now() - t < 6000; await wait(25)) {
    const n = sides().map(mineOn)
    const now = n.join(' ')
    if (now !== last) {
      last = now
      quiet = 0
    } else quiet += 25
    if (quiet >= 400 && sides().every((side, i) => n[i] >= want[side.name])) break
  }
  const out = {}
  for (const side of sides()) {
    const all = hoses[side.name]
    const mine = all.filter((e) => (e.body?.did ?? e.body?.repo) === did[side.name])
    // In place: the subscription keeps pushing to this array.
    const rest = all.filter((e) => !mine.includes(e))
    all.splice(0, all.length, ...rest)
    out[side.name] = mine.map(({ header, body }) => ({ t: header.t, ...(body.active !== undefined ? { active: body.active } : {}), ...(body.status ? { status: body.status } : {}), ...(body.handle !== undefined ? { handle: strip(side, body.handle, names[side.name]) } : {}), ...(body.rev ? { rev: body.rev } : {}) }))
  }
  return out
}

/// Each side's events of `did` since they were last taken must be `want`,
/// by type and fields, `rev` aside; the reference is held to it too, unless
/// `refWant` says otherwise ("Where the reference departs").
async function checkEvents(what, did, want, refWant = want) {
  const got = await eventsOf(did, { reference: refWant?.length ?? 0, server: want?.length ?? 0 })
  for (const side of sides()) {
    const w = side === ref ? refWant : want
    if (!w) continue
    const g = got[side.name].map(({ rev: _, ...e }) => e)
    if (!isDeepStrictEqual(g, w)) await fail(side, `firehose after ${what}`, { did: `<${what}>` }, w, g)
  }
  return got
}

// ---- Accounts -------------------------------------------------------------

let serial = 0

/// Records and blobs alike for both sides' accounts: `{records: [{rkey,
/// value}], blobs: [{bytes, type}], again}`, `again` whether a record
/// references the first blob a second time. Every draw is made here, once
/// for both sides: `fill` draws nothing.
function content() {
  const blobs = Array.from({ length: 1 + below(3) }, (_, i) => ({ bytes: new TextEncoder().encode(`spec-pds blob ${++serial} ${i}`), type: pick(['text/plain', 'application/octet-stream']) }))
  const records = Array.from({ length: 1 + below(3) }, (_, i) => ({ rkey: `r${i}`, value: { $type: C, text: `moved ${i}`, n: below(100) } }))
  return { records, blobs, again: blobs.length > 1 && chance(0.5) }
}

/// Put `content` in `did`'s repository on `at`, with `token`: its blobs
/// uploaded, and records referencing them. Answers each blob's ref.
async function fill(at, did, token, { records, blobs, again }) {
  const refs = []
  for (const b of blobs) refs.push((await send(at, `${R}uploadBlob`, { auth: bearer(token), body: b.bytes, type: b.type })).body?.blob)
  const writes = records.map((r) => ({ $type: `${R}applyWrites#create`, collection: C, rkey: r.rkey, value: r.value }))
  refs.forEach((blob, i) => writes.push({ $type: `${R}applyWrites#create`, collection: C, rkey: `b${i}`, value: { $type: C, blob, ...(i > 0 ? { also: [refs[0]] } : {}) } }))
  if (again) writes.push({ $type: `${R}applyWrites#create`, collection: C, rkey: 'again', value: { $type: C, blob: refs[0] } })
  const res = await send(at, `${R}applyWrites`, { auth: bearer(token), body: { repo: did, writes } })
  if (res.status !== 200) throw new Error(`filling ${did} on ${at.name}: ${JSON.stringify(res.body)}`)
  return refs
}

/// Make an account on both sides alike, with `content` if given: `{did,
/// token, password, handle}` by side name.
async function makeOnBoth(kind, body, data) {
  const did = {}
  const token = {}
  const n = ++serial
  await same(kind, `${S}createAccount`, { body }, (side, res) => {
    if (res.status !== 200) return
    did[side.name] = res.body.did
    token[side.name] = res.body.accessJwt
    name(side, res.body.did, `<did:m${n}>`)
  })
  if (!did.reference || !did.server) throw new Error(`${kind}: no account made`)
  if (data) for (const side of sides()) await fill(side, did[side.name], token[side.name], data)
  return { did, token, password: body.password, handle: body.handle, n }
}

/// An account's emailed token of `purpose` on each side, from the emails
/// both sent, compared (spec/EMAIL.md).
async function mailedTokens(what, request) {
  const sent = await checkMail(what, request)
  return { reference: sent.reference.at(-1)?.token, server: sent.server.at(-1)?.token }
}

/// An app password's session token for the account on each side.
async function appPasswordTokens(acct) {
  const out = {}
  for (const side of sides()) {
    const made = await send(side, `${S}createAppPassword`, { auth: bearer(acct.token[side.name]), body: { name: `app ${++serial}` } })
    const s = await send(side, `${S}createSession`, { body: { identifier: acct.did[side.name], password: made.body?.password } })
    out[side.name] = s.body?.accessJwt
  }
  return out
}

// ---- Moving in ------------------------------------------------------------

/// An account on the third PDS for each side, alike: `{did, token, handle,
/// key}` by side name, its records and blobs `data`.
async function oldAccounts(front, data) {
  const acct = { did: {}, token: {}, handle: {}, key: {}, refs: {} }
  for (const side of sides()) {
    const handle = `${front}${side === ref ? 'r' : 's'}.test`
    const res = await send(old, `${S}createAccount`, { body: { handle, email: `${front}-${side === ref ? 'r' : 's'}@old.example.com`, password: 'old-pass' } })
    if (res.status !== 200) throw new Error(`the third PDS made no account: ${JSON.stringify(res.body)}`)
    acct.did[side.name] = res.body.did
    acct.token[side.name] = res.body.accessJwt
    acct.handle[side.name] = handle
    acct.key[side.name] = await old.pds.ctx.actorStore.keypair(res.body.did)
    acct.refs[side.name] = await fill(old, res.body.did, res.body.accessJwt, data)
    await send(old, 'app.bsky.actor.putPreferences', { auth: bearer(res.body.accessJwt), body: { preferences: [{ $type: 'app.bsky.actor.defs#adultContentPref', enabled: false }] } })
  }
  return acct
}

/// The faults of createAccount's service token, and its other refusals of
/// a moving account (spec/MIGRATION.md), each a function of the side,
/// `(side) => request`, given the good token and body.
function createFaults(o, good, body, squat) {
  const exp = () => Math.floor(Date.now() / 1000) + 60
  // Drawn once, for both sides alike.
  const otherByDns = chance(0.5)
  const forge = async (side, claims, keypair) => bearer(await createServiceJwt({ iss: o.did[side.name], aud: sideDid, lxm: `${S}createAccount`, keypair: keypair ?? o.key[side.name], ...claims }))
  const crafted = (side, header, payload) => bearer(`${b64(header)}.${b64({ iss: o.did[side.name], aud: sideDid, exp: exp(), lxm: `${S}createAccount`, ...payload })}.c2ln`)
  return {
    'no token': async (side) => ({ body: body(side) }),
    'a token that is no JWT': async (side) => ({ auth: 'Bearer abc', body: body(side) }),
    'a token of four parts': async (side) => ({ auth: 'Bearer a.b.c.d', body: body(side) }),
    'a session token': async (side) => ({ auth: bearer(o.token[side.name]), body: body(side) }),
    'a header without alg': async (side) => ({ auth: crafted(side, { typ: 'JWT' }, {}), body: body(side) }),
    'a typ of dpop+jwt': async (side) => ({ auth: crafted(side, { alg: 'ES256K', typ: 'dpop+jwt' }, {}), body: body(side) }),
    'a typ of refresh+jwt': async (side) => ({ auth: crafted(side, { alg: 'ES256K', typ: 'refresh+jwt' }, {}), body: body(side) }),
    'no aud': async (side) => ({ auth: crafted(side, { alg: 'ES256K' }, { aud: undefined }), body: body(side) }),
    'an exp that is a string': async (side) => ({ auth: crafted(side, { alg: 'ES256K' }, { exp: String(exp()) }), body: body(side) }),
    'an exp passed': async (side) => ({ auth: await forge(side, { exp: Math.floor(Date.now() / 1000) - 10 }), body: body(side) }),
    'another lxm': async (side) => ({ auth: await forge(side, { lxm: `${R}createRecord` }), body: body(side) }),
    'no lxm': async (side) => ({ auth: await forge(side, { lxm: undefined }), body: body(side) }),
    'an iss that is no DID': async (side) => ({ auth: await forge(side, { iss: 'nope' }), body: body(side) }),
    'an iss no directory knows': async (side) => ({ auth: await forge(side, { iss: NOBODY }), body: { ...body(side), did: NOBODY } }),
    'a key not the DID\'s': async (side) => ({ auth: await forge(side, {}, await Secp256k1Keypair.create()), body: body(side) }),
    'another aud': async (side) => ({ auth: await forge(side, { aud: 'did:web:other.example.com' }), body: body(side) }),
    'an aud with a fragment': async (side) => ({ auth: await forge(side, { aud: `${sideDid}#atproto_pds` }), body: body(side) }),
    'the DPoP scheme': async (side) => ({ auth: `DPoP ${good[side.name]}`, body: body(side) }),
    'a did not the token\'s': async (side) => ({ auth: bearer(good[side.name]), body: { ...body(side), did: NOBODY } }),
    'a plcOp': async (side) => ({ auth: bearer(good[side.name]), body: { ...body(side), plcOp: {} } }),
    'an external handle that resolves to nothing': async (side) => ({ auth: bearer(good[side.name]), body: { ...body(side), handle: `gone${serial}.moved.example.com` } }),
    'an external handle of another DID': async (side) => {
      const h = `other${serial}${side === ref ? 'r' : 's'}.moved.example.com`
      serveHandle(h, otherByDns ? { dns: [`did=${NOBODY}`] } : { https: `${NOBODY}\n` })
      return { auth: bearer(good[side.name]), body: { ...body(side), handle: h } }
    },
    'a handle another account has': async (side) => ({ auth: bearer(good[side.name]), body: { ...body(side), handle: squat.handle } }),
    'an email another account has': async (side) => ({ auth: bearer(good[side.name]), body: { ...body(side), email: squat.email } }),
    'a handle of a disallowed top-level domain': async (side) => ({ auth: bearer(good[side.name]), body: { ...body(side), handle: `${serial}x.moved.example` } }),
  }
}

/// The server's DID, which is the reference's too (`did:web:localhost`).
let sideDid
/// An account on each side, its handle and email taken by none other.
let squatter
/// An account on each side made without a password.
let passwordless

/// A handle for the moving account on `side`: under the sides' domains,
/// or an external one served by DNS or HTTPS, each named alike.
function chooseHandle(front, did) {
  const kind = pick(['domain', 'dns', 'https', 'dns ambiguous, https'])
  const handle = {}
  for (const side of sides()) {
    if (kind === 'domain') {
      handle[side.name] = `${front}.test`
      continue
    }
    const h = `${front}${side === ref ? 'r' : 's'}.moved.example.com`
    handle[side.name] = h
    const d = did[side.name]
    serveHandle(h, kind === 'dns' ? { dns: ['v=other', `did=${d}`] } : kind === 'https' ? { https: `${d}\n` } : { dns: [`did=${d}`, `did=${NOBODY}`], https: `  ${d}  \nmore` })
    name(side, h, `<handle:${front}>`)
  }
  return { kind, handle }
}

/// A move in from the third PDS, every step to both sides alike
/// (spec/MIGRATION.md, "The move", "Moving in").
async function moveIn() {
  const front = `in${run.step}`
  const data = content()
  const o = await oldAccounts(front, data)
  for (const side of sides()) {
    name(side, o.did[side.name], `<mover:${front}>`)
    name(side, o.handle[side.name], `<old-handle:${front}>`)
  }
  const good = {}
  for (const side of sides()) good[side.name] = (await send(old, `${S}getServiceAuth`, { auth: bearer(o.token[side.name]), params: { aud: sideDid, lxm: `${S}createAccount` } })).body.token
  const email = `${front}@moved.example.com`
  const body = (side) => ({ handle: `${front}.test`, email, password: 'moved-pass', did: o.did[side.name] })

  // createAccount refused, for each fault drawn, then made
  // (spec/MIGRATION.md, "createAccount with a DID").
  const faults = createFaults(o, good, body, squatter)
  // The external handles that do not resolve to the DID are always sent:
  // nothing else of the run holds the server to resolving them.
  const always = new Set(['an external handle that resolves to nothing', 'an external handle of another DID'])
  for (const [what, make] of Object.entries(faults)) {
    if (!always.has(what) && !chance(0.4)) continue
    const req = { reference: await make(ref), server: await make(cand) }
    await same(`createAccount with a DID: ${what}`, `${S}createAccount`, (side) => req[side.name])
  }
  const { kind, handle } = chooseHandle(front, o.did)
  const tok = {}
  const [a, b] = await same(`createAccount with a DID, handle ${kind}`, `${S}createAccount`, (side) => ({ auth: bearer(good[side.name]), body: { ...body(side), handle: handle[side.name] } }), (side, res) => {
    tok[side.name] = res.body?.accessJwt
  })
  for (const [side, res] of [[ref, a], [cand, b]]) if (res.status === 200) await checkDidDoc(side, o.did[side.name], res.body.didDoc, 'createAccount with a DID: didDoc', { did: '<mover>' })
  if (a.status !== 200) return
  if (chance(0.3)) await same('createAccount with a DID here already', `${S}createAccount`, (side) => ({ auth: bearer(good[side.name]), body: { ...body(side), handle: `${front}x.test`, email: `${front}x@moved.example.com` } }))
  const acct = { did: o.did, token: tok }
  const own = (side) => bearer(tok[side.name])
  await same('getSession of an account moving in', `${S}getSession`, (side) => ({ auth: own(side) }))
  await same('checkAccountStatus of an account moving in', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
  await same('describeRepo of an account moving in', `${R}describeRepo`, (side) => ({ params: { repo: o.did[side.name] } }))
  await same('getRepoStatus of an account moving in', `${Y}getRepoStatus`, (side) => ({ params: { did: o.did[side.name] } }))
  await checkEvents('createAccount with a DID', o.did, [])
  const firstRev = {}
  for (const side of sides()) firstRev[side.name] = (await send(side, `${S}checkAccountStatus`, { auth: own(side) })).body?.repoRev

  // importRepo (spec/MIGRATION.md, "importRepo").
  const car = {}
  for (const side of sides()) car[side.name] = (await send(old, `${Y}getRepo`, { params: { did: o.did[side.name] } })).bytes
  const appPw = chance(0.5) ? await appPasswordTokens(acct) : null
  const importFaults = {
    'no token': (side) => ({ body: car[side.name] }),
    'an app password\'s token': appPw && ((side) => ({ auth: bearer(appPw[side.name]), body: car[side.name] })),
    'a JSON Content-Type': (side) => ({ auth: own(side), body: car[side.name], type: 'application/json' }),
    'no Content-Type': (side) => ({ auth: own(side), body: car[side.name], type: null }),
    'a body that is no CAR': (side) => ({ auth: own(side), body: new Uint8Array([1, 2, 3]) }),
    'an empty body': (side) => ({ auth: own(side), body: new Uint8Array() }),
    'a body too large': (side) => ({ auth: own(side), body: new Uint8Array(MAX_REPO_IMPORT + 1) }),
  }
  for (const [what, make] of Object.entries(importFaults)) if (make && chance(0.5)) await same(`importRepo: ${what}`, `${R}importRepo`, make)
  const parsed = {}
  for (const side of sides()) parsed[side.name] = await parse(car[side.name])
  if (chance(0.5)) {
    const two = {}
    for (const side of sides()) {
      const p = parsed[side.name]
      two[side.name] = carOf([p.root, p.commit.data], p.entries)
    }
    await same('importRepo: two roots', `${R}importRepo`, (side) => ({ auth: own(side), body: two[side.name] }))
  }
  if (chance(0.4)) {
    const rootless = {}
    for (const side of sides()) {
      const p = parsed[side.name]
      rootless[side.name] = carOf([p.commit.data], p.entries)
    }
    await same('importRepo: a root that is no commit', `${R}importRepo`, (side) => ({ auth: own(side), body: rootless[side.name] }))
  }
  if (ownRules()) await importDepartures(o, parsed, tok)
  await same('importRepo', `${R}importRepo`, (side) => ({ auth: own(side), body: car[side.name] }))
  if (chance(0.3)) await same('importRepo again', `${R}importRepo`, (side) => ({ auth: own(side), body: car[side.name] }))
  await same('getLatestCommit after importRepo', `${Y}getLatestCommit`, (side) => ({ auth: own(side), params: { did: o.did[side.name] } }))
  await same('checkAccountStatus after importRepo', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
  await checkEvents('importRepo of an account deactivated', o.did, [])
  await same('getRecommendedDidCredentials of an account moving in', `${I}getRecommendedDidCredentials`, (side) => ({ auth: own(side) }))
  const newKey = {}
  for (const side of sides()) newKey[side.name] = (await send(side, `${I}getRecommendedDidCredentials`, { auth: own(side) })).body?.verificationMethods?.atproto
  if (ownRules()) await checkImported(o.did, parsed.server.commit.data, firstRev.server, newKey.server, tok.server)

  // The blobs.
  await missingBlobs(o, tok, data, appPw)

  // Preferences.
  const prefs = {}
  for (const side of sides()) prefs[side.name] = (await send(old, 'app.bsky.actor.getPreferences', { auth: bearer(o.token[side.name]) })).body
  await same('putPreferences of an account moving in', 'app.bsky.actor.putPreferences', (side) => ({ auth: own(side), body: prefs[side.name] }))
  await same('getPreferences of an account moving in', 'app.bsky.actor.getPreferences', (side) => ({ auth: own(side) }))

  // The operation: signed by the third PDS, submitted here.
  const creds = {}
  for (const side of sides()) creds[side.name] = (await send(side, `${I}getRecommendedDidCredentials`, { auth: own(side) })).body
  const op = {}
  for (const side of sides()) {
    await must(side, 'requestPlcOperationSignature', `${I}requestPlcOperationSignature`, { auth: bearer(o.token[side.name]), method: 'POST' })
    const mailed = old.mails.splice(0).find((m) => m.to === `${front}-${side === ref ? 'r' : 's'}@old.example.com`)
    op[side.name] = (await must(side, 'signPlcOperation', `${I}signPlcOperation`, { auth: bearer(o.token[side.name]), body: { token: mailed?.token, ...creds[side.name] } })).body?.operation
  }
  await submitFaults(o, op, own)
  const before = {}
  for (const side of sides()) before[side.name] = (await plcLog(o.did[side.name])).body
  await same('submitPlcOperation', `${I}submitPlcOperation`, (side) => ({ auth: own(side), body: { operation: op[side.name] } }))
  for (const side of sides()) {
    const log = await plcLog(o.did[side.name])
    if (!isDeepStrictEqual(log.body, [...before[side.name], op[side.name]])) await fail(side, 'PLC log after submitPlcOperation', { operation: '<op>' }, 'the operations before, and the one submitted', log.body)
  }
  if (chance(0.3)) await same('submitPlcOperation again', `${I}submitPlcOperation`, (side) => ({ auth: own(side), body: { operation: op[side.name] } }))
  await checkEvents('submitPlcOperation', o.did, [{ t: '#identity' }])
  await same('checkAccountStatus after submitPlcOperation', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))

  // Activated here, deactivated there.
  await same('activateAccount of an account moved in', `${S}activateAccount`, (side) => ({ auth: own(side), method: 'POST' }))
  for (const side of sides()) await send(old, `${S}deactivateAccount`, { auth: bearer(o.token[side.name]), body: {} })
  await checkEvents('activateAccount of an account moved in', o.did, [{ t: '#account', active: true }, { t: '#identity', handle: strip(ref, handle.reference, names.reference) }, { t: '#sync' }])
  await net.pds.ctx.idResolver.did.resolve(o.did.reference, true)
  await same('getSession of an account moved in', `${S}getSession`, (side) => ({ auth: own(side) }))
  await same('describeRepo of an account moved in', `${R}describeRepo`, (side) => ({ params: { repo: o.did[side.name] } }))
  await same('resolveHandle of an account moved in', `${I}resolveHandle`, (side) => ({ params: { handle: handle[side.name] } }))
  await same('a write of an account moved in', `${R}createRecord`, (side) => ({ auth: own(side), body: { repo: o.did[side.name], collection: C, rkey: 'after', record: { $type: C, text: 'after the move' } } }))
  await checkEvents('a write of an account moved in', o.did, [{ t: '#commit' }])
  for (const side of sides()) await verifyAgainstDoc(side, o.did[side.name], 'getRepo of an account moved in, after a write')
  if (chance(0.5)) await externalHandles(front, o.did, own)
  if (chance(0.5)) {
    const again = {}
    for (const side of sides()) again[side.name] = (await send(side, `${Y}getRepo`, { params: { did: o.did[side.name] } })).bytes
    await same('importRepo of an account active', `${R}importRepo`, (side) => ({ auth: own(side), body: again[side.name] }))
    await checkEvents('importRepo of an account active', o.did, ownRules() ? [{ t: '#sync' }] : null, [])
  }
}

/// What the server refuses of importRepo where the reference takes it
/// ("Where the reference departs"): sent to the server alone.
async function importDepartures(o, parsed, tok) {
  const p = parsed.server
  const recordCid = p.entries.find(([cid, bytes]) => !cid.equals(p.root) && !cid.equals(p.commit.data) && !('e' in (cborDecode(bytes) ?? {})))?.[0]
  const cases = {
    'a commit of another DID': () => carOf([parsed.reference.root], parsed.reference.entries),
    'a record missing': recordCid && (() => carOf([p.root], p.entries.filter(([c]) => !c.equals(recordCid)))),
    'the tree\'s root missing': () => carOf([p.root], p.entries.filter(([c]) => !c.equals(p.commit.data))),
  }
  for (const [what, make] of Object.entries(cases)) {
    if (!make || !chance(0.6)) continue
    const res = await send(cand, `${R}importRepo`, { auth: bearer(tok.server), body: make() })
    count(`moves: importRepo: ${what}`, res.status < 400)
    if (res.status !== 400 || res.body?.error !== 'InvalidRequest') await fail(cand, `importRepo of ${what} (spec/MIGRATION.md, "Where the reference departs")`, { did: '<mover>' }, { status: 400, error: 'InvalidRequest' }, { status: res.status, error: res.body?.error })
  }
}

/// The server's head after an import: a new commit of the tree imported,
/// `data` its root, a `rev` later than `firstRev`, signed with the
/// account's new key `key` ("Where the reference departs").
async function checkImported(did, data, firstRev, key, token) {
  const res = await send(cand, `${Y}getRepo`, { auth: bearer(token), params: { did: did.server } })
  if (!res.bytes) return fail(cand, 'getRepo after importRepo', { did: '<mover>' }, 'a CAR file', res)
  const { commit } = await parse(res.bytes)
  if (!commit.data?.equals?.(data)) await fail(cand, 'head after importRepo', { did: '<mover>' }, { data: data.toString() }, { data: String(commit.data) })
  if (!(typeof commit.rev === 'string' && commit.rev > firstRev)) await fail(cand, 'head after importRepo', { did: '<mover>' }, `a rev later than ${firstRev}`, { rev: commit.rev })
  try {
    await verifyRepoCar(res.bytes, did.server, key)
  } catch (err) {
    await fail(cand, 'head after importRepo', { did: '<mover>' }, `a repository verified against the account's new key, ${key}`, String(err.message ?? err))
  }
}

/// A side's whole repository must verify against the key its DID document
/// names now.
async function verifyAgainstDoc(side, did, what) {
  const doc = (await fetch(`${plcUrl}/${did}/data`).then((r) => r.json())) ?? {}
  const key = doc.verificationMethods?.atproto
  const res = await send(side, `${Y}getRepo`, { params: { did } })
  try {
    if (!res.bytes) throw new Error(`getRepo answered ${res.status} ${JSON.stringify(res.body)}`)
    await verifyRepoCar(res.bytes, did, key)
  } catch (err) {
    await fail(side, what, { did: '<mover>' }, `a repository verified against ${key}`, String(err.message ?? err))
  }
}

// ---- A did:web account --------------------------------------------------

/// A `did:web` the harness is the owner of, one for each side: a host of
/// its own on this machine, `localhost:<port>`, serving the document
/// `serve` last gave it, or `404` after `unserve`. Answers `{did, key,
/// serve, unserve, doc}`.
async function webDid(front, side) {
  let doc = null
  const web = http.createServer((req, res) => {
    if (req.url !== '/.well-known/did.json' || !doc) return res.writeHead(404, { 'content-type': 'text/plain' }).end('not found')
    res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(doc))
  })
  await new Promise((ok) => web.listen(0, '127.0.0.1', ok))
  web.unref()
  const did = `did:web:localhost%3A${web.address().port}`
  const key = await Secp256k1Keypair.create({ exportable: true })
  name(side, did, `<web:${front}>`)
  const w = {
    did,
    key,
    get doc() {
      return doc
    },
    /// Serve a document naming `handle`, the signing key `signing` and
    /// the endpoint `pds`, as atproto/did.md lays one out.
    async serve({ handle, signing, pds }) {
      doc = {
        '@context': ['https://www.w3.org/ns/did/v1', 'https://w3id.org/security/multikey/v1'],
        id: did,
        alsoKnownAs: [`at://${handle}`],
        verificationMethod: [{ id: `${did}#atproto`, type: 'Multikey', controller: did, publicKeyMultibase: signing.replace(/^did:key:/, '') }],
        service: [{ id: '#atproto_pds', type: 'AtprotoPersonalDataServer', serviceEndpoint: pds }],
      }
      // The reference keeps the documents it resolved: have it read this one.
      if (side === ref) await net.pds.ctx.idResolver.did.resolve(did, true).catch(() => {})
    },
    async unserve() {
      doc = null
      if (side === ref) await net.pds.ctx.idResolver.did.resolve(did, true).catch(() => {})
    },
  }
  return w
}

/// A repository of `did`, with `records`, signed with `key`, as a CAR file:
/// the account's own, which it brings to a server for the first time.
async function ownRepo(did, key, records) {
  const storage = new MemoryBlockstore()
  const writes = records.map((r) => ({ action: WriteOpAction.Create, collection: C, rkey: r.rkey, record: r.value }))
  const repo = await Repo.create(storage, did, key, writes)
  return blocksToCarFile(repo.cid, storage.blocks)
}

/// A `did:web` account made on each side by its owner, the harness, with a
/// service token it signs itself, then moved in whole: its repository
/// imported, its document pointed at the side, activated, written to, its
/// handle changed (spec/MIGRATION.md, "A `did:web` account").
async function webAccount() {
  const front = `web${run.step}`
  const data = content()
  const w = { reference: await webDid(front, ref), server: await webDid(front, cand) }
  for (const side of sides()) await w[side.name].serve({ handle: `${front}.test`, signing: w[side.name].key.did(), pds: 'https://old.example.com' })
  const did = { reference: w.reference.did, server: w.server.did }
  const token = (side, claims = {}, keypair) => createServiceJwt({ iss: did[side.name], aud: sideDid, lxm: `${S}createAccount`, keypair: keypair ?? w[side.name].key, ...claims })
  const body = (side) => ({ did: did[side.name], handle: `${front}.test`, email: `${front}@web.example.com`, password: 'web-pass' })

  // Refused, then made.
  if (chance(0.5)) await same('createAccount of a did:web: no token', `${S}createAccount`, (side) => ({ body: body(side) }))
  if (chance(0.5)) {
    const other = await Secp256k1Keypair.create()
    const req = {}
    for (const side of sides()) req[side.name] = { auth: bearer(await token(side, {}, other)), body: body(side) }
    await same('createAccount of a did:web: a key not its document\'s', `${S}createAccount`, (side) => req[side.name])
  }
  if (chance(0.5)) {
    for (const side of sides()) await w[side.name].unserve()
    const req = {}
    for (const side of sides()) req[side.name] = { auth: bearer(await token(side)), body: body(side) }
    await same('createAccount of a did:web: its document not found', `${S}createAccount`, (side) => req[side.name])
    for (const side of sides()) await w[side.name].serve({ handle: `${front}.test`, signing: w[side.name].key.did(), pds: 'https://old.example.com' })
  }
  const req = {}
  for (const side of sides()) req[side.name] = { auth: bearer(await token(side)), body: body(side) }
  const tok = {}
  const [a, b] = await same('createAccount of a did:web', `${S}createAccount`, (side) => req[side.name], (side, res) => {
    tok[side.name] = res.body?.accessJwt
  })
  for (const [side, res] of [[ref, a], [cand, b]]) if (res.status === 200 && !isDeepStrictEqual(res.body.didDoc, w[side.name].doc)) await fail(side, 'createAccount of a did:web: didDoc', { did: '<web>' }, w[side.name].doc, res.body.didDoc)
  if (a.status !== 200) return
  const own = (side) => bearer(tok[side.name])
  await checkEvents('createAccount of a did:web', did, [])
  await same('getSession of a did:web moving in', `${S}getSession`, (side) => ({ auth: own(side) }))
  await same('checkAccountStatus of a did:web moving in', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
  await same('describeRepo of a did:web moving in', `${R}describeRepo`, (side) => ({ params: { repo: did[side.name] } }))

  // Its own repository, signed by its owner.
  const car = {}
  for (const side of sides()) car[side.name] = await ownRepo(did[side.name], w[side.name].key, data.records)
  await same('importRepo of a did:web\'s own repository', `${R}importRepo`, (side) => ({ auth: own(side), body: car[side.name] }))
  await same('checkAccountStatus after importRepo of a did:web', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
  await checkEvents('importRepo of a did:web', did, [])

  // No PLC method applies.
  await same('getRecommendedDidCredentials of a did:web', `${I}getRecommendedDidCredentials`, (side) => ({ auth: own(side) }))
  const creds = {}
  for (const side of sides()) creds[side.name] = (await send(side, `${I}getRecommendedDidCredentials`, { auth: own(side) })).body
  await same('requestPlcOperationSignature of a did:web', `${I}requestPlcOperationSignature`, (side) => ({ auth: own(side), method: 'POST' }))
  const mailed = await mailedTokens('requestPlcOperationSignature of a did:web', { did: '<web>' })
  await same('signPlcOperation of a did:web', `${I}signPlcOperation`, (side) => ({ auth: own(side), body: { token: mailed[side.name] } }))
  if (ownRules()) {
    const op = { type: 'plc_operation', ...creds.server, prev: null, sig: 'c2ln' }
    const res = await send(cand, `${I}submitPlcOperation`, { auth: own(cand), body: { operation: op } })
    count('moves: submitPlcOperation of a did:web', res.status < 400)
    if (res.status !== 400 || res.body?.error !== 'InvalidRequest') await fail(cand, 'submitPlcOperation of a did:web (spec/MIGRATION.md, "Where the reference departs")', { did: '<web>' }, { status: 400, error: 'InvalidRequest' }, { status: res.status, error: res.body?.error })
  }

  // Its document pointed here, by its owner; then activated.
  await same('activateAccount of a did:web whose document names its old server', `${S}activateAccount`, (side) => ({ auth: own(side), method: 'POST' }))
  for (const side of sides()) await w[side.name].serve({ handle: `${front}.test`, signing: creds[side.name].verificationMethods.atproto, pds: side.publicUrl })
  await same('checkAccountStatus of a did:web pointed here', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
  await same('activateAccount of a did:web', `${S}activateAccount`, (side) => ({ auth: own(side), method: 'POST' }))
  await checkEvents('activateAccount of a did:web', did, [{ t: '#account', active: true }, { t: '#identity', handle: `${front}.test` }, { t: '#sync' }])
  await same('describeRepo of a did:web moved in', `${R}describeRepo`, (side) => ({ params: { repo: did[side.name] } }))
  await same('a write of a did:web moved in', `${R}createRecord`, (side) => ({ auth: own(side), body: { repo: did[side.name], collection: C, rkey: 'after', record: { $type: C, text: 'after the move' } } }))
  await checkEvents('a write of a did:web', did, [{ t: '#commit' }])
  for (const side of sides()) await verifyAgainstKey(side, did[side.name], creds[side.name].verificationMethods.atproto, 'getRepo of a did:web moved in')

  // Its handle, changed in its document first.
  const next = `${front}x.test`
  await same('updateHandle of a did:web to a handle its document does not name', `${I}updateHandle`, (side) => ({ auth: own(side), body: { handle: next } }))
  await checkEvents('updateHandle of a did:web refused', did, [])
  for (const side of sides()) await w[side.name].serve({ handle: next, signing: creds[side.name].verificationMethods.atproto, pds: side.publicUrl })
  await same('updateHandle of a did:web', `${I}updateHandle`, (side) => ({ auth: own(side), body: { handle: next } }))
  await checkEvents('updateHandle of a did:web', did, [{ t: '#identity', handle: next }])
  await same('describeRepo of a did:web by its new handle', `${R}describeRepo`, (side) => ({ params: { repo: next } }))
  await same('resolveHandle of a did:web\'s handle', `${I}resolveHandle`, (side) => ({ params: { handle: next } }))
  for (const side of sides()) {
    const log = await plcLog(did[side.name])
    if (log.status === 200) await fail(side, 'the PLC directory after a did:web\'s moves', { did: '<web>' }, 'no operations: a did:web is no directory\'s', log.body)
  }

  // Its document gone.
  if (chance(0.5)) {
    for (const side of sides()) await w[side.name].unserve()
    await same('describeRepo of a did:web whose document is gone', `${R}describeRepo`, (side) => ({ params: { repo: did[side.name] } }))
    await same('checkAccountStatus of a did:web whose document is gone', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
    await same('activateAccount of a did:web whose document is gone', `${S}activateAccount`, (side) => ({ auth: own(side), method: 'POST' }))
  }
}

/// A side's whole repository must verify against `key`.
async function verifyAgainstKey(side, did, key, what) {
  const res = await send(side, `${Y}getRepo`, { params: { did } })
  try {
    if (!res.bytes) throw new Error(`getRepo answered ${res.status} ${JSON.stringify(res.body)}`)
    await verifyRepoCar(res.bytes, did, key)
  } catch (err) {
    await fail(side, what, { did: '<web>' }, `a repository verified against ${key}`, String(err.message ?? err))
  }
}

/// listMissingBlobs, held to the records that reference each blob, then
/// each blob uploaded, in a random order (spec/MIGRATION.md,
/// "listMissingBlobs").
async function missingBlobs(o, tok, data, appPw) {
  const own = (side) => bearer(tok[side.name])
  const referencing = new Map()
  for (const side of sides()) {
    const recs = (await send(side, `${Y}getRepo`, { auth: own(side), params: { did: o.did[side.name] } })).bytes
    const { entries } = await parse(recs)
    for (const [cid, bytes] of entries) {
      const v = cborDecode(bytes)
      if (v?.$type !== C) continue
      for (const b of [v.blob, ...(v.also ?? [])]) if (b?.ref) referencing.set(`${side.name} ${b.ref.toString()}`, (referencing.get(`${side.name} ${b.ref.toString()}`) ?? 0) + 1)
      void cid
    }
  }
  // A blob several records reference is listed with any one of them.
  const list = async (kind, params, auth = own) => {
    const [a, b] = await Promise.all(sides().map((side) => send(side, `${R}listMissingBlobs`, { params, auth: auth(side) })))
    const shape = (side, res) => {
      const v = view(side, res, `${R}listMissingBlobs`)
      if (res.status !== 200 || !Array.isArray(res.body?.blobs)) return v
      res.body.blobs.forEach((x, i) => {
        const many = (referencing.get(`${side.name} ${x.cid}`) ?? 0) > 1
        const isRecord = typeof x.recordUri === 'string' && x.recordUri.startsWith(`at://${o.did[side.name]}/${C}/`)
        if (!isRecord) return
        if (many) v.body.blobs[i].recordUri = '<a record referencing it>'
      })
      return v
    }
    const [na, nb] = [shape(ref, a), shape(cand, b)]
    if (!isDeepStrictEqual(na, nb)) await differ(`listMissingBlobs (${kind})`, { params }, na, nb)
    count(`moves: listMissingBlobs ${kind}`, a.status < 400)
    return [a, b]
  }
  if (chance(0.5)) await same('listMissingBlobs: no token', `${R}listMissingBlobs`, {})
  if (chance(0.5)) await list('limit 0', { limit: 0 })
  if (chance(0.5)) await list('limit 1001', { limit: 1001 })
  if (appPw) await list('an app password\'s token', {}, (side) => bearer(appPw[side.name]))
  if (chance(0.5)) await list('a cursor past every CID', { cursor: 'zzz' })
  await list('all', {})
  // Paged by one.
  const cursor = { reference: undefined, server: undefined }
  for (let i = 0; i <= data.blobs.length; i++) {
    const [a, b] = await Promise.all(sides().map((side) => send(side, `${R}listMissingBlobs`, { params: { limit: 1, cursor: cursor[side.name] }, auth: own(side) })))
    const [na, nb] = [view(ref, a, `${R}listMissingBlobs`), view(cand, b, `${R}listMissingBlobs`)]
    for (const v of [na, nb]) for (const x of v.body?.blobs ?? []) x.recordUri = '<a record>'
    if (!isDeepStrictEqual(na, nb)) await differ('listMissingBlobs (paged by one)', { limit: 1, cursor: '<cursor>' }, na, nb)
    count('moves: listMissingBlobs paged', a.status < 400)
    cursor.reference = a.body?.cursor
    cursor.server = b.body?.cursor
    if (!a.body?.cursor) break
  }
  // Uploaded, one by one.
  const order = [...data.blobs]
  for (let i = order.length - 1; i > 0; i--) {
    const j = below(i + 1)
    ;[order[i], order[j]] = [order[j], order[i]]
  }
  for (const blob of order) {
    await same('uploadBlob of a missing blob', `${R}uploadBlob`, (side) => ({ auth: own(side), body: blob.bytes, type: blob.type }))
    await list('after an upload', {})
    if (chance(0.5)) await same('checkAccountStatus after an upload', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
  }
}

/// submitPlcOperation refused: with no token, an operation not of the
/// form, each fault of its checks, and one the directory refuses; each
/// leaving the directory's log as it was (spec/MIGRATION.md,
/// "submitPlcOperation").
async function submitFaults(o, op, own) {
  const atproto = (side) => op[side.name].services?.atproto_pds ?? {}
  const faults = {
    'no token': (side) => ({ body: { operation: op[side.name] } }),
    'no operation': (side) => ({ auth: own(side), body: {} }),
    'an operation that is no object': (side) => ({ auth: own(side), body: { operation: null } }),
    'an operation not of the form': (side) => ({ auth: own(side), body: { operation: { type: 'plc_operation' } } }),
    'a tombstone': (side) => ({ auth: own(side), body: { operation: { type: 'plc_tombstone', prev: op[side.name].prev, sig: op[side.name].sig } } }),
    'rotation keys without the server\'s': (side) => ({ auth: own(side), body: { operation: { ...op[side.name], rotationKeys: op[side.name].rotationKeys.filter((k) => k !== side.rotationKey) } } }),
    'a service of another type': (side) => ({ auth: own(side), body: { operation: { ...op[side.name], services: { atproto_pds: { ...atproto(side), type: 'Other' } } } } }),
    'another endpoint': (side) => ({ auth: own(side), body: { operation: { ...op[side.name], services: { atproto_pds: { ...atproto(side), endpoint: 'https://pds.example.com' } } } } }),
    'another signing key': (side) => ({ auth: own(side), body: { operation: { ...op[side.name], verificationMethods: { ...op[side.name].verificationMethods, atproto: STRANGE_KEY } } } }),
    'another handle': (side) => ({ auth: own(side), body: { operation: { ...op[side.name], alsoKnownAs: ['at://nobody.example.com'] } } }),
    'a signature the directory refuses': (side) => ({ auth: own(side), body: { operation: { ...op[side.name], sig: `${op[side.name].sig.slice(0, -4)}AAAA` } } }),
  }
  for (const [what, make] of Object.entries(faults)) {
    if (!chance(0.5)) continue
    const before = {}
    for (const side of sides()) before[side.name] = (await plcLog(o.did[side.name])).body
    await same(`submitPlcOperation: ${what}`, `${I}submitPlcOperation`, make)
    for (const side of sides()) {
      const log = await plcLog(o.did[side.name])
      if (!isDeepStrictEqual(log.body, before[side.name])) await fail(side, `PLC log after submitPlcOperation refused (${what})`, { operation: '<op>' }, 'the operations before, and no more', log.body)
    }
  }
}

/// updateHandle to external handles: one resolving to another DID,
/// refused, and one resolving to the account's, by DNS or HTTPS
/// (spec/IDENTITY.md, "Resolving a handle").
async function externalHandles(front, did, own) {
  const other = {}
  const mine = {}
  const byDns = chance(0.5)
  for (const side of sides()) {
    const s = side === ref ? 'r' : 's'
    other[side.name] = `${front}other${s}.handles.example.org`
    mine[side.name] = `${front}${s}.handles.example.org`
    serveHandle(other[side.name], { dns: [`did=${NOBODY}`] })
    serveHandle(mine[side.name], byDns ? { dns: [`did=${did[side.name]}`] } : { https: did[side.name] })
    name(side, other[side.name], `<other-handle:${front}>`)
    name(side, mine[side.name], `<new-handle:${front}>`)
  }
  await same('updateHandle to an external handle of another DID', `${I}updateHandle`, (side) => ({ auth: own(side), body: { handle: other[side.name] } }))
  await same('updateHandle to an external handle', `${I}updateHandle`, (side) => ({ auth: own(side), body: { handle: mine[side.name] } }))
  await net.pds.ctx.idResolver.did.resolve(did.reference, true)
  await same('getSession after updateHandle to an external handle', `${S}getSession`, (side) => ({ auth: own(side) }))
  await same('describeRepo after updateHandle to an external handle', `${R}describeRepo`, (side) => ({ params: { repo: mine[side.name] } }))
  await checkEvents('updateHandle to an external handle', did, [{ t: '#identity', handle: strip(ref, mine.reference, names.reference) }])
}

// ---- Moving out -----------------------------------------------------------

/// A move out to the third PDS, each side's account taken there
/// (spec/MIGRATION.md, "The move", "Moving out").
async function moveOut() {
  const front = `out${run.step}`
  const data = content()
  const acct = await makeOnBoth('createAccount of an account to move out', { handle: `${front}.test`, email: `${front}@here.example.com`, password: 'out-pass' }, data)
  const own = (side) => bearer(acct.token[side.name])
  // The third PDS: the account made there with each side's service token.
  await same('getServiceAuth for createAccount elsewhere', `${S}getServiceAuth`, (side) => ({ auth: own(side), params: { aud: old.did, lxm: `${S}createAccount` } }))
  const tokOld = {}
  for (const side of sides()) {
    const t = (await send(side, `${S}getServiceAuth`, { auth: own(side), params: { aud: old.did, lxm: `${S}createAccount` } })).body?.token
    const res = await must(side, 'createAccount with the side\'s service token', `${S}createAccount`, { auth: bearer(t), body: { handle: `${front}${side === ref ? 'r' : 's'}.test`, email: `${front}-${side === ref ? 'r' : 's'}@there.example.com`, password: 'there-pass', did: acct.did[side.name] } })
    tokOld[side.name] = res.body?.accessJwt
    name(side, `${front}${side === ref ? 'r' : 's'}.test`, `<there-handle:${front}>`)
  }
  const creds = {}
  for (const side of sides()) creds[side.name] = (await send(old, `${I}getRecommendedDidCredentials`, { auth: bearer(tokOld[side.name]) })).body

  // requestPlcOperationSignature (spec/MIGRATION.md,
  // "requestPlcOperationSignature").
  const appPw = chance(0.5) ? await appPasswordTokens(acct) : null
  if (chance(0.5)) await same('requestPlcOperationSignature: no token', `${I}requestPlcOperationSignature`, { method: 'POST' })
  if (appPw) await same('requestPlcOperationSignature: an app password\'s token', `${I}requestPlcOperationSignature`, (side) => ({ auth: bearer(appPw[side.name]), method: 'POST' }))
  if (chance(0.5)) await same('requestPlcOperationSignature: a body', `${I}requestPlcOperationSignature`, (side) => ({ auth: own(side), body: {} }))
  if (chance(0.5)) await same('requestPlcOperationSignature: no email', `${I}requestPlcOperationSignature`, (side) => ({ auth: bearer(passwordless.token[side.name]), method: 'POST' }))
  await same('requestPlcOperationSignature', `${I}requestPlcOperationSignature`, (side) => ({ auth: own(side), method: 'POST' }))
  const token = await mailedTokens('requestPlcOperationSignature', { did: '<did>' })

  // signPlcOperation (spec/MIGRATION.md, "signPlcOperation").
  const fields = {}
  for (const k of ['rotationKeys', 'alsoKnownAs', 'verificationMethods', 'services']) if (chance(0.75)) fields[k] = true
  const input = (side) => Object.fromEntries(Object.keys(fields).map((k) => [k, creds[side.name][k]]))
  const signFaults = {
    'no token': (side) => ({ body: { token: token[side.name] } }),
    'no token field': (side) => ({ auth: own(side), body: input(side) }),
    'an empty token': (side) => ({ auth: own(side), body: { token: '', ...input(side) } }),
    'a wrong token': (side) => ({ auth: own(side), body: { token: 'AAAAA-AAAAA', ...input(side) } }),
    'rotationKeys not a list': (side) => ({ auth: own(side), body: { token: token[side.name], rotationKeys: 'x' } }),
    'services not an object': (side) => ({ auth: own(side), body: { token: token[side.name], services: 5 } }),
    'an app password\'s token': appPw && ((side) => ({ auth: bearer(appPw[side.name]), body: { token: token[side.name] } })),
  }
  for (const [what, make] of Object.entries(signFaults)) if (make && chance(0.5)) await same(`signPlcOperation: ${what}`, `${I}signPlcOperation`, make)
  const before = {}
  for (const side of sides()) before[side.name] = (await plcLog(acct.did[side.name])).body
  const lower = chance(0.5)
  const [a, b] = await same(`signPlcOperation with ${Object.keys(fields).join(', ') || 'no fields'}`, `${I}signPlcOperation`, (side) => ({ auth: own(side), body: { token: lower ? token[side.name]?.toLowerCase() : token[side.name], ...input(side) } }))
  const op = { reference: a.body?.operation, server: b.body?.operation }
  for (const side of sides()) await checkSigned(side, before[side.name], input(side), op[side.name])
  // The KEM key, which the `latest` reference has not, is taken out once
  // checkSigned has held each operation to its fields (spec/PDS.md).
  const shape = (side) => {
    const { sig: _s, prev: _p, ...rest } = op[side.name] ?? {}
    if (rest.verificationMethods && typeof rest.verificationMethods === 'object') {
      const { atproto_kem: _k, ...vm } = rest.verificationMethods
      rest.verificationMethods = vm
    }
    return JSON.parse(strip(side, JSON.stringify(rest), names[side.name]))
  }
  if (!isDeepStrictEqual(shape(ref), shape(cand))) await differ('signPlcOperation\'s operation', { fields: Object.keys(fields) }, shape(ref), shape(cand))
  if (chance(0.5)) await same('signPlcOperation with its token again', `${I}signPlcOperation`, (side) => ({ auth: own(side), body: { token: token[side.name], ...input(side) } }))
  const unchanged = {}
  for (const side of sides()) unchanged[side.name] = (await plcLog(acct.did[side.name])).body
  for (const side of sides()) if (!isDeepStrictEqual(unchanged[side.name], before[side.name])) await fail(side, 'PLC log after signPlcOperation', { did: '<did>' }, 'the operations before: signing sends nothing', unchanged[side.name])

  // The third PDS takes it all, when every field was given; else the
  // operation keeps this side as its server, which the third PDS refuses.
  if (Object.keys(fields).length < 4) return
  for (const side of sides()) {
    const car = (await send(side, `${Y}getRepo`, { params: { did: acct.did[side.name] } })).bytes
    await must(side, 'importRepo of the side\'s getRepo', `${R}importRepo`, { auth: bearer(tokOld[side.name]), body: car })
    const missing = (await send(old, `${R}listMissingBlobs`, { auth: bearer(tokOld[side.name]) })).body?.blobs ?? []
    for (const m of missing) {
      const blob = await send(side, `${Y}getBlob`, { params: { did: acct.did[side.name], cid: m.cid } })
      await must(side, 'uploadBlob of the side\'s getBlob', `${R}uploadBlob`, { auth: bearer(tokOld[side.name]), body: blob.bytes ?? new Uint8Array(), type: 'application/octet-stream' })
    }
    await must(side, 'submitPlcOperation of the side\'s operation', `${I}submitPlcOperation`, { auth: bearer(tokOld[side.name]), body: { operation: op[side.name] } })
    await must(side, 'activateAccount', `${S}activateAccount`, { auth: bearer(tokOld[side.name]), method: 'POST' })
  }
  await same('deactivateAccount of an account moved out', `${S}deactivateAccount`, (side) => ({ auth: own(side), body: {} }))
  await net.pds.ctx.idResolver.did.resolve(acct.did.reference, true)
  await same('getRepoStatus of an account moved out', `${Y}getRepoStatus`, (side) => ({ params: { did: acct.did[side.name] } }))
  await same('describeRepo of an account moved out', `${R}describeRepo`, (side) => ({ params: { repo: acct.did[side.name] } }))
  await same('checkAccountStatus of an account moved out', `${S}checkAccountStatus`, (side) => ({ auth: own(side) }))
  await same('getRepo of an account moved out, with its token', `${Y}getRepo`, (side) => ({ auth: own(side), params: { did: acct.did[side.name] } }))
}

/// A side's signed operation: the update of the DID's last operation in
/// `before`, its fields `input`'s where given, `prev` the last one's CID,
/// signed with the side's rotation key.
async function checkSigned(side, before, input, op) {
  const req = { did: '<did>', fields: Object.keys(input) }
  if (!op || typeof op !== 'object') return fail(side, 'signPlcOperation\'s operation', req, 'an operation', op)
  const last = before.at(-1)
  const { sig: _, ...prev } = last
  const { sig, ...unsigned } = op
  const want = { ...prev, ...input, prev: (await cidForCbor(last)).toString() }
  if (!isDeepStrictEqual(unsigned, want)) return fail(side, 'signPlcOperation\'s operation', req, want, unsigned)
  let ok = false
  try {
    ok = typeof sig === 'string' && (await verifySignature(side.rotationKey, cborEncode(unsigned), Buffer.from(sig, 'base64url')))
  } catch {}
  if (!ok) await fail(side, 'signPlcOperation\'s operation', req, `a signature by the side's rotation key, ${side.rotationKey}`, { sig })
}

// ---- States ---------------------------------------------------------------

/// The five methods of a move, for an account deactivated, taken down and
/// deleted, with its password session's token, and taken down, its
/// `com.atproto.takendown` session's too (spec/MIGRATION.md, "What each
/// state does").
async function states() {
  for (const state of ['deactivated', 'takendown', 'deleted']) {
    const front = `st${run.step}${state.slice(0, 3)}`
    const acct = await makeOnBoth(`createAccount of an account ${state}`, { handle: `${front}.test`, email: `${front}@here.example.com`, password: 'state-pass' }, content())
    const own = (side) => bearer(acct.token[side.name])
    const car = {}
    for (const side of sides()) car[side.name] = (await send(side, `${Y}getRepo`, { params: { did: acct.did[side.name] } })).bytes
    // A well-formed operation, signed before the change, for the deleted.
    await same(`requestPlcOperationSignature before ${state}`, `${I}requestPlcOperationSignature`, (side) => ({ auth: own(side), method: 'POST' }))
    const early = await mailedTokens(`requestPlcOperationSignature before ${state}`, { did: '<did>' })
    const creds = {}
    for (const side of sides()) creds[side.name] = (await send(side, `${I}getRecommendedDidCredentials`, { auth: own(side) })).body
    const [sa, sb] = await same(`signPlcOperation before ${state}`, `${I}signPlcOperation`, (side) => ({ auth: own(side), body: { token: early[side.name], ...creds[side.name] } }))
    const op = { reference: sa.body?.operation, server: sb.body?.operation }
    if (state === 'deactivated') await same('deactivateAccount', `${S}deactivateAccount`, (side) => ({ auth: own(side), body: {} }))
    if (state === 'takendown') await same('takedown', `${A}updateSubjectStatus`, (side) => ({ auth: admin(side), body: { subject: { $type: `${A}defs#repoRef`, did: acct.did[side.name] }, takedown: { applied: true, ref: 'migration' } } }))
    if (state === 'deleted') {
      await same('requestAccountDelete', `${S}requestAccountDelete`, (side) => ({ auth: own(side), method: 'POST' }))
      const del = await mailedTokens('requestAccountDelete', { did: '<did>' })
      await same('deleteAccount', `${S}deleteAccount`, (side) => ({ body: { did: acct.did[side.name], password: 'state-pass', token: del[side.name] } }))
    }
    const tokens = [['its password session\'s token', own]]
    if (state === 'takendown') {
      const td = {}
      for (const side of sides()) td[side.name] = (await send(side, `${S}createSession`, { body: { identifier: acct.did[side.name], password: 'state-pass', allowTakendown: true } })).body?.accessJwt
      tokens.push(['its com.atproto.takendown token', (side) => bearer(td[side.name])])
    }
    for (const [whose, auth] of tokens) {
      const k = `${state}, ${whose}`
      await same(`importRepo, ${k}`, `${R}importRepo`, (side) => ({ auth: auth(side), body: car[side.name] }))
      await same(`listMissingBlobs, ${k}`, `${R}listMissingBlobs`, (side) => ({ auth: auth(side) }))
      await same(`requestPlcOperationSignature, ${k}`, `${I}requestPlcOperationSignature`, (side) => ({ auth: auth(side), method: 'POST' }))
      const t = await mailedTokens(`requestPlcOperationSignature, ${k}`, { did: '<did>' })
      await same(`signPlcOperation, ${k}`, `${I}signPlcOperation`, (side) => ({ auth: auth(side), body: { token: t[side.name] ?? 'AAAAA-AAAAA' } }))
      await same(`submitPlcOperation not of the form, ${k}`, `${I}submitPlcOperation`, (side) => ({ auth: auth(side), body: { operation: {} } }))
      if (state === 'deleted' && op.reference && op.server) await same(`submitPlcOperation, ${k}`, `${I}submitPlcOperation`, (side) => ({ auth: auth(side), body: { operation: op[side.name] } }))
    }
  }
}

// ---- The run --------------------------------------------------------------

/// Start the third PDS, on the same directory, resolving handles through
/// the harness, its emails caught.
async function startOld() {
  const pds = await TestPds.create({ didPlcUrl: plcUrl, hostname: 'localhost', inviteRequired: false })
  resolveHere(pds.ctx.idResolver.handle, handles, pds.ctx.cfg.identity.serviceHandleDomains)
  const mails = []
  const sendTemplate = pds.ctx.mailer.sendTemplate.bind(pds.ctx.mailer)
  pds.ctx.mailer.sendTemplate = (kind, params, opts) => {
    mails.push({ to: opts.to, kind, token: params.token })
    return sendTemplate(kind, params, opts)
  }
  return { name: 'the reference it moves to', url: pds.url, pds, mails, did: pds.ctx.cfg.service.did }
}

/// Moves in and out, and the states, in turn, `--steps` of them.
export async function movesRun() {
  old = await startOld()
  for (const side of sides()) {
    const sub = subscribe(side, undefined, hoses[side.name])
    await new Promise((ok) => (sub.ws.onopen = ok))
  }
  const [d] = await same('describeServer', `${S}describeServer`, {})
  sideDid = d.body?.did
  squatter = await makeOnBoth('createAccount of an account in the way', { handle: 'squat.test', email: 'squat@here.example.com', password: 'squat-pass' })
  squatter.email = 'squat@here.example.com'
  passwordless = await makeOnBoth('createAccount without a password', { handle: 'nopass.test', email: 'nopass@here.example.com' })
  const kinds = [moveIn, moveOut, states, webAccount]
  for (run.step = 1; run.step <= MOVES_STEPS; run.step++) {
    const step = kinds[(run.step - 1) % kinds.length]
    process.stderr.write(`\rmove step ${run.step}/${MOVES_STEPS}: ${step.name}   `)
    await step()
  }
  await old.pds.close().catch(() => {})
  console.error(`\nall ${MOVES_STEPS} move steps agree`)
}