~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
1065 lines · 88.3 KB Raw History
// The spaces' policies and lifecycle (spec/SPACES-POLICIES.md), with the
// server as a space's authority and host beside the alpha's. On each side an
// authority account (the server's on the server, the reference's on the alpha
// PDS) owns the spaces; peers on a second alpha PDS, the same accounts for both
// sides, are their members and writers. Each request goes to both sides alike,
// with the space's URI on the side's own authority, and the answers must be
// equal with each authority's DID named alike. Where the page says what the
// answer is, each side is held to it too, the reference included, which checks
// the check.
//
// The stages go in order, each on what the one before needs: 1. the methods
// here alone; 2. publishing, read with the space repo's listRecords and
// listRepoOps; 3. the writer set, which needs repo update notifications; 4.
// reads, which need authorizeSpaceSync; 5. takedown and deactivation, compared
// only once the server can put an account in either state (the reference is
// held to them regardless). Every draw comes from the run's `rand`.

import { createServer } from 'node:http'
import { once } from 'node:events'
import { isDeepStrictEqual } from 'node:util'
import * as plc from '@did-plc/lib'
import { Secp256k1Keypair, verifySignature } from '@atproto/crypto'
import * as S from './lib/spec.mjs'

const T = 'com.example.group'
const MEMBER = 'com.atproto.memberspace.member'
const POLICY = 'com.atproto.space.policy'
const PERSONAL = { $type: 'com.atproto.personalspace.policy' }
const MS = (fields = {}) => ({ $type: 'com.atproto.memberspace.policy', ...fields })
const MG = (managingApp, fields = {}) => ({ $type: 'com.atproto.managedspace.policy', managingApp, ...fields })
/// A memberspace policy as the page says it is stored.
const msStored = ({ publicRead = false, publicWrite = false, publishPolicy = false, publishMembers = false, allowedApps } = {}) => ({ $type: 'com.atproto.memberspace.policy', publicRead, publicWrite, publishPolicy, publishMembers, ...(allowedApps ? { allowedApps } : {}) })
const STAR = 'application/vnd.dasl.star'
const isStar = (type) => (type ?? '').split(';')[0].trim().toLowerCase() === STAR
const mgStored = (managingApp, publishPolicy = false) => ({ $type: 'com.atproto.managedspace.policy', managingApp, publishPolicy })
const TID = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/
const EMPTY = { status: 200, empty: true }
const sleep = (ms) => new Promise((ok) => setTimeout(ok, ms))
/// A member's record key: the first `%3A` of the DID as `:`.
const rkeyOf = (did) => did.replace('%3A', ':')

export async function checkPolicies(h) {
  const { ref, cand, peer, plcUrl, refPds, rand, front, accounts, normalize, differ, fail, count, createAccount, env } = h
  const sides = [ref, cand]
  const pick = (xs) => xs[Math.floor(rand() * xs.length)]
  const skey = (p) => `${p}${Math.floor(rand() * 1e6)}`

  // ---- requests ------------------------------------------------------------------

  async function call(base, nsid, { params, body, raw, ctype, token, auth } = {}) {
    const url = new URL(`${base}/xrpc/${nsid}`)
    for (const [k, v] of Object.entries(params ?? {})) url.searchParams.set(k, v)
    const headers = {}
    if (auth) headers.authorization = auth
    else if (token) headers.authorization = `Bearer ${token}`
    let send
    // An archive goes as the lexicon's encoding, or as `ctype`; `ctype: null` sends none.
    if (raw !== undefined) { send = raw; if (ctype !== null) headers['content-type'] = ctype ?? STAR } else if (body !== undefined) { send = JSON.stringify(body); headers['content-type'] = 'application/json' }
    const res = await fetch(url, { method: send === undefined ? 'GET' : 'POST', headers, body: send })
    const buf = Buffer.from(await res.arrayBuffer())
    const type = res.headers.get('content-type')
    let parsed = null
    if (buf.length && !isStar(type)) try { parsed = JSON.parse(buf.toString('utf8')) } catch { parsed = { unparsed: buf.toString('utf8').slice(0, 200) } }
    return { status: res.status, type, buf, body: parsed }
  }
  /// What a side answered, as compared: an error as its status and name; a
  /// method that answers nothing as `EMPTY` (it must have no body and no
  /// Content-Type); otherwise its JSON, normalized.
  function shape(side, res) {
    if (res.status >= 400) return normalize(side, res)
    if (res.status === 200 && !res.buf.length && !res.type) return EMPTY
    if (res.status === 200 && !res.buf.length) return { status: 200, empty: true, type: res.type }
    if (isStar(res.type)) return { status: res.status, archive: true }
    return normalize(side, res)
  }
  const describe = (side, req) => JSON.parse(alias(side, JSON.stringify(req, (k, v) => (k === 'token' ? '<token>' : Buffer.isBuffer(v) || v?.type === 'Buffer' ? `<${(v.data ?? v).length} bytes>` : v))))
  function alias(side, s) {
    for (const a of accounts) if (a.sides[side.name].did) s = s.split(a.sides[side.name].did).join(`<did:${a.n}>`)
    return s
  }

  /// The same request to both sides, `make(side)` its arguments. Each side's
  /// answer must be `want` when given (an object to equal, or a function
  /// answering what is wrong), and the two must agree, as `view` shows them.
  async function both(kind, nsid, make, want, view = (g) => g) {
    const res = await Promise.all(sides.map((side) => call(side.url, nsid, make(side))))
    const got = sides.map((side, i) => shape(side, res[i]))
    for (const [i, side] of sides.entries()) {
      const wrong = want === undefined ? null : typeof want === 'function' ? want(got[i], res[i], side) : isDeepStrictEqual(got[i], want) ? null : want
      if (wrong) await fail(side, `${kind}: ${nsid}`, describe(side, make(side)), typeof wrong === 'string' ? wrong : JSON.parse(alias(side, JSON.stringify(wrong))), got[i])
    }
    const [a, b] = got.map(view)
    if (!isDeepStrictEqual(a, b)) await differ(`${kind}: ${nsid}`, describe(cand, make(cand)), a, b)
    count(kind)
    return res
  }
  const err = (error, status = 400) => ({ status, error })

  // ---- the accounts ----------------------------------------------------------------

  const peerHost = peer.url
  const peerDomain = (await (await fetch(`${peerHost}/xrpc/com.atproto.server.describeServer`)).json()).availableUserDomains[0]
  async function peerAccount() {
    const f = front()
    const r = await call(peerHost, 'com.atproto.server.createAccount', { body: { handle: `${f}${peerDomain}`, email: `${f}@example.com`, password: `pw-${f}` } })
    if (r.status !== 200) await differ('a peer account on the second alpha PDS', { handle: `${f}${peerDomain}` }, 'an account', r.body, 'the harness could not make a peer')
    return { did: r.body.did, token: r.body.accessJwt, handle: r.body.handle }
  }
  const [bob, carol, dave, eve] = [await peerAccount(), await peerAccount(), await peerAccount(), await peerAccount()]
  const A = await createAccount()
  const auth = (side) => A.sides[side.name]
  const tok = (side) => auth(side).token
  const sp = (side, key, type = T) => `at://${auth(side).did}/space/${type}/${key}`

  const create = (kind, key, policy, want = (g) => (g.status === 200 ? null : 'the space created')) => both(kind, 'com.atproto.space.createSpace', (side) => ({ token: tok(side), body: { spaceType: T, skey: key, policy } }), want)
  const getSpace = (kind, key, policy) => both(kind, 'com.atproto.space.getSpace', (side) => ({ token: tok(side), params: { space: sp(side, key) } }), (g, _, side) => (isDeepStrictEqual(g, normalize(side, { status: 200, body: { space: sp(side, key), policy } })) ? null : { space: sp(side, key), policy }))
  const update = (kind, key, policy, want = EMPTY) => both(kind, 'com.atproto.space.updateSpace', (side) => ({ token: tok(side), body: { space: sp(side, key), policy } }), want)
  /// putMembers of `list`, each [did, read, write].
  const putMembers = (kind, key, list, want = EMPTY) => both(kind, 'com.atproto.memberspace.putMembers', (side) => ({ token: tok(side), body: { space: sp(side, key), members: list.map(([did, read, write]) => ({ did, read, write })) } }), want)
  const removeMembers = (kind, key, dids, want = EMPTY) => both(kind, 'com.atproto.memberspace.removeMembers', (side) => ({ token: tok(side), body: { space: sp(side, key), dids } }), want)
  const removeWriter = (kind, key, did, want = EMPTY) => both(kind, 'com.atproto.space.removeWriter', (side) => ({ token: tok(side), body: { space: sp(side, key), repo: typeof did === 'function' ? did(side) : did } }), want)
  const deleteSpace = (kind, key, want = EMPTY) => both(kind, 'com.atproto.space.deleteSpace', (side) => ({ token: tok(side), body: { space: sp(side, key) } }), want)
  /// listMembers, which must answer `list` and its cursor, or the error `list` is.
  const members = (kind, key, list, params = {}) => both(kind, 'com.atproto.memberspace.listMembers', (side) => ({ token: tok(side), params: { space: sp(side, key), ...params } }), list.error ? list : { status: 200, body: { members: list, ...(list.length ? { cursor: list.at(-1).did } : {}) } })
  /// `xs` cut into batches of 1 to `most`, their sizes drawn.
  const batches = (xs, most = 3) => { const out = []; for (let i = 0; i < xs.length;) { const n = 1 + Math.floor(rand() * most); out.push(xs.slice(i, i + n)); i += n } return out }

  // ---- space meta archives ---------------------------------------------------------

  const asJson = (v) => JSON.parse(JSON.stringify(v, (k, x) => (x instanceof Uint8Array || x?.type === 'Buffer' ? { $hex: Buffer.from(x.data ?? x).toString('hex') } : x)))
  /// Read an archive exportSpaceMeta answered as the page says it must be,
  /// holding the side to every rule; answers its contents
  /// (spec/SPACES-POLICIES.md, "Space meta archives", "exportSpaceMeta").
  async function readArchive(side, res, space, request) {
    const bad = (why) => fail(side, `exportSpaceMeta archive (${why})`, request, 'an archive as SPACES-POLICIES.md writes it', { status: res.status, type: res.type, hex: res.buf.toString('hex').slice(0, 400), body: res.body })
    if (res.status !== 200 || res.type !== STAR) return bad('status and Content-Type')
    let star
    try { star = S.readStar(res.buf, S.REPO_LIMITS) } catch (e) { return bad(e.message) }
    if (!isDeepStrictEqual(asJson(star.meta), { $type: 'atproto-space-meta', ver: 1, space })) return bad(`metadata ${JSON.stringify(asJson(star.meta))}`)
    const out = { policy: null, members: [], writers: {} }
    let section = -1, prev = null
    for (const [i, { key, value }] of star.pairs.entries()) {
      const k = key.toString('utf8')
      const sec = k === 'policy' ? 0 : k.startsWith('writer/') ? 2 : 1
      if (i === 0 && sec !== 0) return bad('the first pair is not policy')
      if (sec < section) return bad(`section out of order at ${k}`)
      if (sec === section && Buffer.compare(prev, key) >= 0) return bad(`key out of order at ${k}`)
      section = sec; prev = key
      let v
      try { v = S.decode(value) } catch (e) { return bad(`value of ${k}: ${e.message}`) }
      if (!S.encode(v).equals(value)) return bad(`value of ${k} is not canonical DRISL`)
      if (sec === 0) out.policy = asJson(v)
      else if (sec === 1) {
        if (!k.startsWith(`${MEMBER}/`) || !isDeepStrictEqual(Object.keys(v).sort(), ['$type', 'read', 'write']) || v.$type !== MEMBER || typeof v.read !== 'boolean' || typeof v.write !== 'boolean') return bad(`policy state ${k}`)
        out.members.push([k, asJson(v)])
      } else {
        if (!isDeepStrictEqual(Object.keys(v).sort(), ['data', 'repoRev', 'spaceRev']) || !TID.test(v.repoRev) || !TID.test(v.spaceRev) || !(v.data instanceof Uint8Array) || v.data.length !== 32) return bad(`writer ${k}`)
        out.writers[k.slice('writer/'.length)] = { repoRev: v.repoRev, spaceRev: v.spaceRev, data: Buffer.from(v.data).toString('hex') }
      }
    }
    if (!out.policy) return bad('no policy')
    if (!S.writeStar(star.meta, star.pairs).equals(res.buf)) return bad('not the bytes of its own contents')
    return out
  }
  /// exportSpaceMeta of a space on each side of `on`, each read and held to the
  /// page, then the two compared, writers by DID and data; answers each side's.
  async function exportBoth(kind, key, on = sides) {
    const make = (side) => ({ token: tok(side), params: { space: sp(side, key) } })
    const res = await Promise.all(on.map((side) => call(side.url, 'com.atproto.space.exportSpaceMeta', make(side))))
    const got = {}
    for (const [i, side] of on.entries()) got[side.name] = await readArchive(side, res[i], sp(side, key), describe(side, make(side)))
    const view = (side) => JSON.parse(alias(side, JSON.stringify({ policy: got[side.name].policy, members: got[side.name].members, writers: Object.entries(got[side.name].writers).map(([did, w]) => ({ did, data: w.data })) })))
    const [a, b] = on.map(view)
    for (const v of [a, b]) v?.writers.sort((x, y) => (x.did < y.did ? -1 : 1))
    if (b && !isDeepStrictEqual(a, b)) await differ(`${kind}: com.atproto.space.exportSpaceMeta`, describe(cand, make(cand)), a, b)
    count(kind)
    return got
  }
  /// The archive the page says a space's state is, with no writers.
  const archiveOf = (space, policy, memberList = [], writers = []) => S.writeStar({ $type: 'atproto-space-meta', ver: 1, space }, [
    { key: Buffer.from('policy'), value: S.encode(policy) },
    ...memberList.map(([did, read, write]) => ({ key: Buffer.from(`${MEMBER}/${rkeyOf(did)}`), value: S.encode({ $type: MEMBER, read, write }) })).sort((x, y) => Buffer.compare(x.key, y.key)),
    ...writers.map(([did, w]) => ({ key: Buffer.from(`writer/${did}`), value: S.encode(w) })).sort((x, y) => Buffer.compare(x.key, y.key)),
  ])
  /// exportSpaceMeta must answer exactly `want(side)` on each side.
  async function exportIs(kind, key, want) {
    const make = (side) => ({ token: tok(side), params: { space: sp(side, key) } })
    for (const side of sides) {
      const res = await call(side.url, 'com.atproto.space.exportSpaceMeta', make(side))
      await readArchive(side, res, sp(side, key), describe(side, make(side)))
      if (!res.buf.equals(want(side))) await fail(side, `${kind}: exportSpaceMeta bytes`, describe(side, make(side)), want(side).toString('hex'), res.buf.toString('hex'))
    }
    count(kind)
  }
  const importMeta = (kind, archive, want, opts = {}) => both(kind, 'com.atproto.space.importSpaceMeta', (side) => ({ token: opts.token?.(side) ?? tok(side), raw: archive(side), ctype: opts.ctype }), want)

  // ---- the managing app --------------------------------------------------------------

  const CHECK = 'com.atproto.managedspace.checkAccess'
  const calls = []
  /// What the app answers a call's parameters: {status, body, ctype?}, the
  /// body JSON unless a string.
  let answer = () => ({ status: 200, body: { read: false, write: false } })
  const app = createServer((req, res) => {
    const u = new URL(req.url, 'http://x')
    calls.push({ method: req.method, path: u.pathname, query: Object.fromEntries(u.searchParams), authorization: req.headers.authorization })
    const a = answer(Object.fromEntries(u.searchParams))
    res.writeHead(a.status, { 'content-type': a.ctype ?? 'application/json' }).end(typeof a.body === 'string' ? a.body : JSON.stringify(a.body))
  })
  app.listen(0, '127.0.0.1')
  await once(app, 'listening')
  // An app at a port of the harness that only redirects to the app.
  const redirected = []
  const redirector = createServer((req, res) => { redirected.push(req.url); res.writeHead(302, { location: `http://localhost:${app.address().port}${req.url}` }).end() })
  redirector.listen(0, '127.0.0.1')
  await once(redirector, 'listening')
  const appKey = await Secp256k1Keypair.create()
  const at = (port, form = '') => ({ type: 'AtprotoManagingApp', endpoint: `http://localhost:${port}${form}` })
  const appPort = app.address().port
  // Its endpoints of other forms (spec/SPACES-POLICIES.md, "Asking a managing app: checkAccess").
  const endpoints = {
    path: at(appPort, '/base/path'),
    query: at(appPort, '/base?x=1'),
    endq: at(appPort, '/admin/delete?'),
    frag: at(appPort, '/p#frag'),
    user: { type: 'AtprotoManagingApp', endpoint: `http://u:p@localhost:${appPort}` },
    ftp: { type: 'AtprotoManagingApp', endpoint: `ftp://localhost:${appPort}` },
    noscheme: { type: 'AtprotoManagingApp', endpoint: `localhost:${appPort}` },
    redir: at(redirector.address().port),
  }
  const appOp = await plc.signOperation({ type: 'plc_operation', rotationKeys: [appKey.did()], alsoKnownAs: [], verificationMethods: { atproto: appKey.did() }, services: { forum: at(appPort), ...endpoints }, prev: null }, appKey)
  const appDid = await plc.didForCreateOp(appOp)
  await new plc.Client(plcUrl).sendOperation(appDid, appOp)
  const managingApp = `${appDid}#forum`

  /// The calls the app had since the last look, held to the page: each side's
  /// must be about exactly the repos of `want` (DIDs, or null for a call with
  /// no `repo`; in any order, once or more), with the parameters and service
  /// auth the page says, for each side of `on`, the service auth addressed to
  /// `aud`, the managing app as stored (spec/SPACES-POLICIES.md, "Asking a
  /// managing app: checkAccess").
  async function checkCalls(kind, key, want, on = sides, aud = managingApp) {
    const got = calls.splice(0)
    for (const side of on) {
      const space = sp(side, key)
      const mine = got.filter((c) => c.query.space === space)
      const seen = new Set()
      for (const c of mine) {
        const parts = (c.authorization ?? '').replace(/^Bearer /, '').split('.')
        let header, claims
        try { [header, claims] = parts.slice(0, 2).map((p) => JSON.parse(Buffer.from(p, 'base64url'))) } catch {}
        const wantClaims = { iss: auth(side).did, aud, lxm: CHECK }
        const signed = parts.length === 3 && (await verifySignature(auth(side).key, Buffer.from(`${parts[0]}.${parts[1]}`), Buffer.from(parts[2], 'base64url')).catch(() => false))
        const okClaims = claims && isDeepStrictEqual(Object.keys(claims).sort(), ['aud', 'exp', 'iat', 'iss', 'jti', 'lxm']) && claims.iss === wantClaims.iss && claims.aud === wantClaims.aud && claims.lxm === wantClaims.lxm && claims.exp - claims.iat === 60 && typeof claims.jti === 'string' && claims.jti.length > 0
        const params = 'repo' in c.query ? ['repo', 'space'] : ['space']
        if (c.method !== 'GET' || c.path !== `/xrpc/${CHECK}` || !isDeepStrictEqual(Object.keys(c.query).sort(), params) || !isDeepStrictEqual(header, { typ: 'JWT', alg: 'ES256K' }) || !okClaims || !signed)
          await fail(side, `${kind}: the checkAccess call`, { space: alias(side, space) }, { method: 'GET', path: `/xrpc/${CHECK}`, query: 'space, and repo when there is one; no clientId', header: { typ: 'JWT', alg: 'ES256K' }, claims: { ...wantClaims, iat: '<n>', exp: '<iat + 60>', jti: '<random>' }, signed: 'by the authority #atproto key' }, JSON.parse(alias(side, JSON.stringify({ method: c.method, path: c.path, query: c.query, header, claims, signed }))))
        seen.add(c.query.repo ?? '<no repo>')
      }
      const wantSet = new Set(want.map((w) => w ?? '<no repo>'))
      if (!isDeepStrictEqual([...seen].sort(), [...wantSet].sort())) await fail(side, `${kind}: whom the managing app was asked about`, { space: alias(side, space) }, JSON.parse(alias(side, JSON.stringify([...wantSet].sort()))), JSON.parse(alias(side, JSON.stringify([...seen].sort()))))
    }
    count(kind)
  }

  // ==== 1. policies and lifecycle ==========================================================

  // createSpace, and the policy stored as getSpace answers it
  // (spec/SPACES-POLICIES.md, "Policies", "createSpace", "getSpace").
  const m1 = skey('m')
  await create('createSpace memberspace', m1, MS(), (g, r, side) => (isDeepStrictEqual(g, normalize(side, { status: 200, body: { space: sp(side, m1) } })) ? null : { space: sp(side, m1) }))
  await getSpace('getSpace stored policy', m1, msStored())
  const variants = [
    [PERSONAL, PERSONAL, 'personalspace'],
    [{ ...PERSONAL, publicRead: true, extra: 1 }, PERSONAL, 'personalspace, unknown fields dropped'],
    [MS({ publicRead: true, foo: 'bar', allowedApps: ['https://app.example/client-metadata.json'] }), msStored({ publicRead: true, allowedApps: ['https://app.example/client-metadata.json'] }), 'memberspace, defaults and unknown fields'],
    [MS({ publicWrite: true, publishPolicy: true, publishMembers: true, allowedApps: [] }), msStored({ publicWrite: true, publishPolicy: true, publishMembers: true, allowedApps: [] }), 'memberspace, every flag and an empty allowedApps'],
    [MG(managingApp, { publishMembers: true }), mgStored(managingApp), 'managedspace, its unknown field dropped'],
    [MG('did:web:app.example#svc'), mgStored('did:web:app.example#svc'), 'managedspace, a did:web that need not resolve'],
    [MG('did:web:localhost%3A2583#x'), mgStored('did:web:localhost%3A2583#x'), 'managedspace, a did:web on localhost with a port'],
    [MG(`${appDid}#a/b?c:@!$&'()*+,;=-._~%41`), mgStored(`${appDid}#a/b?c:@!$&'()*+,;=-._~%41`), 'managedspace, every character a fragment may hold'],
  ]
  for (const [policy, stored, what] of variants) {
    const key = skey('v')
    await create(`createSpace ${what}`, key, policy)
    await getSpace(`getSpace ${what}`, key, stored)
  }
  await both('createSpace with no skey', 'com.atproto.space.createSpace', (side) => ({ token: tok(side), body: { spaceType: T, policy: PERSONAL } }), (g, r, side) => {
    const uri = r.body?.space ?? ''
    const prefix = `at://${auth(side).did}/space/${T}/`
    return r.status === 200 && uri.startsWith(prefix) && TID.test(uri.slice(prefix.length)) && isDeepStrictEqual(Object.keys(r.body), ['space']) ? null : { space: `${prefix}<a TID>` }
  }, (g) => ({ ...g, body: { space: g.body?.space?.replace(/[^/]+$/, '<tid>') } }))
  const k512 = 'k'.repeat(511) + String(Math.floor(rand() * 10))
  await create('createSpace with a 512-byte skey', k512, PERSONAL)
  const createErrors = [
    ['an existing space', m1, PERSONAL, err('SpaceAlreadyExists')],
    ['an existing space with an unsupported policy', m1, { $type: 'com.example.policy' }, err('UnsupportedPolicy')],
    ['an unsupported policy', skey('u'), { $type: 'com.example.policy' }, err('UnsupportedPolicy')],
    ['a policy with no $type', skey('u'), { publicRead: true }, err('InvalidRequest')],
    ['a policy that is a list', skey('u'), [], err('InvalidRequest')],
    ['a policy field of the wrong type', skey('u'), MS({ publicRead: 'yes' }), err('InvalidRequest')],
    ['allowedApps not strings', skey('u'), MS({ allowedApps: [1] }), err('InvalidRequest')],
    ['a managingApp that is not a DID', skey('u'), MG('https://app.example'), err('InvalidRequest')],
    ['no managingApp', skey('u'), { $type: 'com.atproto.managedspace.policy' }, err('InvalidRequest')],
    ['a managingApp that is not a string', skey('u'), MG(5), err('InvalidRequest')],
    // (spec/SPACES-POLICIES.md, "Policies": a service reference <did>#<fragment>)
    ...[
      ['a bare DID', appDid], ['did:', 'did:'], ['a did:key', 'did:key:zQ3shokFTS3brHcDQrn82RUDfCZESWL1ZdCEJwekUDPQiYBme#x'], ['another method', 'did:example:abc#x'],
      ['a short did:plc', 'did:plc:abc#x'], ['an empty fragment', `${appDid}#`], ['two fragments', `${appDid}#a#b`], ['a space in the fragment', `${appDid}#a b`],
      ['a broken escape', `${appDid}#%4`], ['a did:web with a path', 'did:web:app.example:path#x'], ['a did:web with a port', 'did:web:app.example%3A443#x'],
    ].map(([what, m]) => [`a managingApp of ${what}`, skey('u'), MG(m), err('InvalidRequest')]),
  ]
  for (const [what, key, policy, want] of createErrors) await create(`createSpace with ${what}`, key, policy, want)
  for (const [what, body, want] of [
    ['a bad spaceType', { spaceType: 'nope', skey: skey('u'), policy: PERSONAL }, err('InvalidRequest')],
    ['a bad skey', { spaceType: T, skey: 'a/b', policy: PERSONAL }, err('InvalidRequest')],
    ['the skey ..', { spaceType: T, skey: '..', policy: PERSONAL }, err('InvalidRequest')],
    ['a 513-byte skey', { spaceType: T, skey: 'k'.repeat(513), policy: PERSONAL }, err('InvalidRequest')],
    ['no policy', { spaceType: T, skey: skey('u') }, err('InvalidRequest')],
  ]) await both(`createSpace with ${what}`, 'com.atproto.space.createSpace', (side) => ({ token: tok(side), body }), want)
  await both('createSpace with no token', 'com.atproto.space.createSpace', () => ({ body: { spaceType: 'nope' } }), err('AuthMissing', 401))
  await both('createSpace with a token not given out', 'com.atproto.space.createSpace', () => ({ token: 'abc.def.ghi', body: { spaceType: T, skey: skey('u'), policy: PERSONAL } }), err('InvalidToken'))
  await both('createSpace by GET', 'com.atproto.space.createSpace', (side) => ({ token: tok(side), params: { spaceType: T } }), err('InvalidRequest'))
  // An app-password session manages spaces (spec/SPACES-POLICIES.md, "What
  // every method here shares").
  const appPassword = {}
  for (const side of sides) {
    const p = await call(side.url, 'com.atproto.server.createAppPassword', { token: tok(side), body: { name: `spaces-${front()}` } })
    const s = await call(side.url, 'com.atproto.server.createSession', { body: { identifier: A.sides[side.name].handle ?? A.handle, password: p.body?.password } })
    if (s.status !== 200) await fail(side, 'an app-password session', { name: '<app password>' }, 'a session', s.body)
    appPassword[side.name] = s.body.accessJwt
  }
  const ap1 = skey('ap')
  await both('createSpace with an app password', 'com.atproto.space.createSpace', (side) => ({ token: appPassword[side.name], body: { spaceType: T, skey: ap1, policy: MS() } }), (g) => (g.status === 200 ? null : 'the space created'))
  await both('putMembers with an app password', 'com.atproto.memberspace.putMembers', (side) => ({ token: appPassword[side.name], body: { space: sp(side, ap1), members: [{ did: bob.did, read: true, write: true }] } }), EMPTY)
  await both('listMembers with an app password', 'com.atproto.memberspace.listMembers', (side) => ({ token: appPassword[side.name], params: { space: sp(side, ap1) } }), { status: 200, body: { members: [{ did: bob.did, read: true, write: true }], cursor: bob.did } })
  await both('getSpace with an app password', 'com.atproto.space.getSpace', (side) => ({ token: appPassword[side.name], params: { space: sp(side, ap1) } }), (g) => (g.status === 200 ? null : 'the space'))
  await both('removeWriter with an app password', 'com.atproto.space.removeWriter', (side) => ({ token: appPassword[side.name], body: { space: sp(side, ap1), repo: bob.did } }), EMPTY)
  await both('removeMembers with an app password', 'com.atproto.memberspace.removeMembers', (side) => ({ token: appPassword[side.name], body: { space: sp(side, ap1), dids: [bob.did] } }), EMPTY)
  await both('updateSpace with an app password', 'com.atproto.space.updateSpace', (side) => ({ token: appPassword[side.name], body: { space: sp(side, ap1), policy: MS() } }), EMPTY)
  await both('deleteSpace with an app password', 'com.atproto.space.deleteSpace', (side) => ({ token: appPassword[side.name], body: { space: sp(side, ap1) } }), EMPTY)

  // getSpace's refusals (spec/SPACES-POLICIES.md, "What every method here
  // shares", "getSpace").
  for (const [what, make, want] of [
    ['of another account', () => ({ params: { space: `at://${bob.did}/space/${T}/${m1}` } }), err('NotAuthorized')],
    ['of a space never created', (side) => ({ params: { space: sp(side, skey('none')) } }), err('SpaceNotFound')],
    ['of another type', (side) => ({ params: { space: sp(side, m1, 'com.example.other') } }), err('SpaceNotFound')],
    ['of a malformed space', () => ({ params: { space: 'at://x' } }), err('InvalidRequest')],
    ['with no space', () => ({}), err('InvalidRequest')],
  ]) await both(`getSpace ${what}`, 'com.atproto.space.getSpace', (side) => ({ token: tok(side), ...make(side) }), want)
  await both('getSpace with no token and a malformed space', 'com.atproto.space.getSpace', () => ({ params: { space: 'nope' } }), err('InvalidRequest'))
  await both('getSpace with no token', 'com.atproto.space.getSpace', (side) => ({ params: { space: sp(side, m1) } }), err('AuthMissing', 401))
  await both('getSpace by POST', 'com.atproto.space.getSpace', (side) => ({ token: tok(side), body: { space: sp(side, m1) } }), err('InvalidRequest'))

  // The member list, put in drawn batches (spec/SPACES-POLICIES.md, "The
  // member list").
  const fakeDid = () => `did:plc:${Array.from({ length: 24 }, () => pick('abcdefghijklmnopqrstuvwxyz234567'.split(''))).join('')}`
  const fake = Array.from({ length: 3 }, fakeDid)
  const web = 'did:web:localhost%3A2583'
  const list = {}
  const byBytes = (x, y) => Buffer.compare(Buffer.from(x), Buffer.from(y))
  for (const batch of batches([bob.did, carol.did, dave.did, web, ...fake])) {
    const given = batch.map((did) => [did, rand() < 0.7, rand() < 0.5])
    await putMembers(`putMembers of ${batch.length}`, m1, given)
    for (const [did, read, write] of given) list[did] = [read, write]
  }
  const asList = () => Object.keys(list).sort(byBytes).map((did) => ({ did, read: list[did][0], write: list[did][1] }))
  await members('listMembers', m1, asList())
  // Replace one member's booleans, the DID given twice: its last entry stands.
  list[bob.did] = [!list[bob.did][0], !list[bob.did][1]]
  await putMembers('putMembers replacing, a DID given twice', m1, [[bob.did, list[bob.did][1], list[bob.did][0]], [carol.did, ...list[carol.did]], [bob.did, ...list[bob.did]]])
  await members('listMembers after a replacement', m1, asList())
  await putMembers('putMembers of no members', m1, [])
  await members('listMembers after no members', m1, asList())
  // Its pages.
  const limit = 2 + Math.floor(rand() * 2)
  let cursor
  const pages = []
  for (let i = 0; i < 10; i++) {
    const want = asList().filter((m) => cursor === undefined || byBytes(m.did, cursor) > 0).slice(0, limit)
    await members('listMembers page', m1, want, { limit, ...(cursor ? { cursor } : {}) })
    pages.push(...want)
    if (!want.length) break
    cursor = want.at(-1).did
  }
  if (!isDeepStrictEqual(pages, asList())) await fail(cand, 'listMembers pages', { limit }, asList(), pages)
  await members('listMembers after every DID', m1, [], { cursor: 'did:zzz:z' })
  await members('listMembers from a cursor before every DID', m1, asList(), { cursor: 'did:a:a' })
  await members('listMembers with an empty cursor', m1, asList(), { cursor: '' })
  for (const c of ['zzzz', 'a', 'did:plc:', 'did:PLC:abc']) await members(`listMembers with the cursor ${c}, no DID`, m1, err('InvalidCursor'), { cursor: c })
  await members('listMembers with limit 0', m1, err('InvalidRequest'), { limit: 0 })
  await members('listMembers with limit 1001', m1, err('InvalidRequest'), { limit: 1001 })
  await members('listMembers with limit 1000', m1, asList(), { limit: 1000 })
  // removeMembers: listed ones, one not listed, one given twice.
  const gone = pick(fake)
  await removeMembers('removeMembers', m1, [gone, fakeDid(), gone])
  delete list[gone]
  await removeMembers('removeMembers of a DID not listed', m1, [fakeDid()])
  await removeMembers('removeMembers of no DIDs', m1, [])
  await removeMembers('removeMembers of the did:web', m1, [web])
  delete list[web]
  await members('listMembers after removals', m1, asList())
  // 100 members at once, and not 101.
  const big = skey('big')
  const hundred = Array.from({ length: 101 }, () => [fakeDid(), rand() < 0.5, rand() < 0.5])
  await create('createSpace for 100 members', big, MS())
  await putMembers('putMembers of 101', big, hundred, err('InvalidRequest'))
  await putMembers('putMembers of 100', big, hundred.slice(0, 100))
  await members('listMembers of 100', big, hundred.slice(0, 100).map(([did, read, write]) => ({ did, read, write })).sort((x, y) => byBytes(x.did, y.did)), { limit: 1000 })
  await removeMembers('removeMembers of 101', big, hundred.map(([did]) => did), err('InvalidRequest'))
  await removeMembers('removeMembers of 100', big, hundred.slice(0, 100).map(([did]) => did))
  await members('listMembers after removing 100', big, [])
  // The authority itself may be a member (its own space, so the list is aliased).
  const own = skey('own')
  await create('createSpace for its authority as member', own, MS())
  await both('putMembers of the authority', 'com.atproto.memberspace.putMembers', (side) => ({ token: tok(side), body: { space: sp(side, own), members: [{ did: auth(side).did, read: false, write: false }] } }), EMPTY)
  await both('listMembers with the authority', 'com.atproto.memberspace.listMembers', (side) => ({ token: tok(side), params: { space: sp(side, own) } }), (g, r, side) => (isDeepStrictEqual(g, normalize(side, { status: 200, body: { members: [{ did: auth(side).did, read: false, write: false }], cursor: auth(side).did } })) ? null : 'the authority, listed'))
  // The member methods' refusals, in their order (spec/SPACES-POLICIES.md,
  // "What every method here shares").
  const pers = skey('p')
  await create('createSpace personalspace', pers, PERSONAL)
  for (const [what, space, want] of [
    ['on a personalspace', (side) => sp(side, pers), err('PolicyMismatch')],
    ['on a space never created', (side) => sp(side, skey('none')), err('SpaceNotFound')],
    ['on another account\'s space', () => `at://${bob.did}/space/${T}/${pers}`, err('NotAuthorized')],
  ]) {
    await both(`putMembers ${what}`, 'com.atproto.memberspace.putMembers', (side) => ({ token: tok(side), body: { space: space(side), members: [{ did: bob.did, read: true, write: true }] } }), want)
    await both(`removeMembers ${what}`, 'com.atproto.memberspace.removeMembers', (side) => ({ token: tok(side), body: { space: space(side), dids: [bob.did] } }), want)
    await both(`listMembers ${what}`, 'com.atproto.memberspace.listMembers', (side) => ({ token: tok(side), params: { space: space(side) } }), want)
    await both(`listMembers ${what}, with a cursor that is no DID`, 'com.atproto.memberspace.listMembers', (side) => ({ token: tok(side), params: { space: space(side), cursor: 'zz' } }), want)
  }
  for (const [what, body, want] of [
    ['a member with no write', (side) => ({ space: sp(side, m1), members: [{ did: bob.did, read: true }] }), err('InvalidRequest')],
    ['a malformed DID', (side) => ({ space: sp(side, m1), members: [{ did: 'bob', read: true, write: true }] }), err('InvalidRequest')],
    ['one member, not a list', (side) => ({ space: sp(side, m1), did: bob.did, read: true, write: true }), err('InvalidRequest')],
    ['a malformed DID and another account\'s space', () => ({ space: `at://${bob.did}/space/${T}/${m1}`, members: [{ did: 'bob', read: true, write: true }] }), err('InvalidRequest')],
  ]) await both(`putMembers with ${what}`, 'com.atproto.memberspace.putMembers', (side) => ({ token: tok(side), body: body(side) }), want)
  await both('removeMembers of a malformed DID', 'com.atproto.memberspace.removeMembers', (side) => ({ token: tok(side), body: { space: sp(side, m1), dids: ['bob'] } }), err('InvalidRequest'))
  await both('removeMembers of one did, not a list', 'com.atproto.memberspace.removeMembers', (side) => ({ token: tok(side), body: { space: sp(side, m1), did: bob.did } }), err('InvalidRequest'))
  await both('putMembers with no token', 'com.atproto.memberspace.putMembers', (side) => ({ body: { space: sp(side, m1), members: [] } }), err('AuthMissing', 401))
  await both('removeMembers with no token', 'com.atproto.memberspace.removeMembers', (side) => ({ body: { space: sp(side, m1), dids: [] } }), err('AuthMissing', 401))

  // updateSpace: wholesale; the member list across a change and a migration
  // (spec/SPACES-POLICIES.md, "updateSpace").
  await update('updateSpace', m1, MS({ publicWrite: true }))
  await getSpace('getSpace after updateSpace', m1, msStored({ publicWrite: true }))
  await update('updateSpace replacing wholesale', m1, MS({ publicRead: true }))
  await getSpace('getSpace after a wholesale replacement', m1, msStored({ publicRead: true }))
  await members('listMembers after a change of configuration', m1, asList())
  for (const [what, key, policy, want] of [
    ['an unsupported policy', m1, { $type: 'com.example.policy' }, err('UnsupportedPolicy')],
    ['a managingApp that is not a DID', m1, MG('x'), err('InvalidRequest')],
    ['a space never created', skey('none'), PERSONAL, err('SpaceNotFound')],
    ['a space never created and an unsupported policy', skey('none'), { $type: 'com.example.policy' }, err('UnsupportedPolicy')],
    ['a space never created and a bad managingApp', skey('none'), MG('x'), err('InvalidRequest')],
  ]) await update(`updateSpace of ${what}`, key, policy, want)
  for (const [what, policy] of [['', PERSONAL], [' and an unsupported policy', { $type: 'com.example.policy' }]]) await both(`updateSpace of another account's space${what}`, 'com.atproto.space.updateSpace', (side) => ({ token: tok(side), body: { space: `at://${bob.did}/space/${T}/${m1}`, policy } }), err('NotAuthorized'))
  await update('updateSpace migrating to managedspace', m1, MG(managingApp))
  await getSpace('getSpace after migrating', m1, mgStored(managingApp))
  await members('listMembers after migrating away', m1, err('PolicyMismatch'))
  await update('updateSpace migrating back to memberspace', m1, MS())
  await members('listMembers after migrating back', m1, [])
  for (const did of Object.keys(list)) delete list[did]

  // removeWriter's answers (what it does to the writer set is stage 3's)
  // (spec/SPACES-POLICIES.md, "The writer set").
  await removeWriter('removeWriter of a DID not in the writer set', m1, bob.did)
  await removeWriter('removeWriter again', m1, bob.did)
  await removeWriter('removeWriter on a personalspace', pers, bob.did)
  await removeWriter('removeWriter of a space never created', skey('none'), bob.did, err('SpaceNotFound'))
  await both('removeWriter of another account\'s space', 'com.atproto.space.removeWriter', (side) => ({ token: tok(side), body: { space: `at://${bob.did}/space/${T}/${m1}`, repo: bob.did } }), err('NotAuthorized'))
  await removeWriter('removeWriter of a malformed DID', m1, 'bob', err('InvalidRequest'))
  await both('removeWriter of a did, not a repo', 'com.atproto.space.removeWriter', (side) => ({ token: tok(side), body: { space: sp(side, m1), did: bob.did } }), err('InvalidRequest'))

  // exportSpaceMeta: the bytes the page says, with no writers
  // (spec/SPACES-POLICIES.md, "exportSpaceMeta").
  const ex = skey('ex')
  const exMembers = [[bob.did, true, false], [carol.did, false, true], [web, true, true]]
  await create('createSpace to export', ex, MS({ publicRead: true }))
  await putMembers('putMembers to export', ex, exMembers)
  await exportIs('exportSpaceMeta of a memberspace', ex, (side) => archiveOf(sp(side, ex), msStored({ publicRead: true }), exMembers))
  await exportBoth('exportSpaceMeta of a memberspace, both sides', ex)
  await exportIs('exportSpaceMeta of a personalspace', pers, (side) => archiveOf(sp(side, pers), PERSONAL))
  for (const [what, make, want] of [
    ['of a space never created', (side) => ({ params: { space: sp(side, skey('none')) } }), err('SpaceNotFound')],
    ['of another account\'s space', () => ({ params: { space: `at://${bob.did}/space/${T}/${ex}` } }), err('NotAuthorized')],
  ]) await both(`exportSpaceMeta ${what}`, 'com.atproto.space.exportSpaceMeta', (side) => ({ token: tok(side), ...make(side) }), want)
  await both('exportSpaceMeta with no token', 'com.atproto.space.exportSpaceMeta', (side) => ({ params: { space: sp(side, ex) } }), err('AuthMissing', 401))
  await both('exportSpaceMeta with no token and a malformed space', 'com.atproto.space.exportSpaceMeta', () => ({ params: { space: 'nope' } }), err('InvalidRequest'))

  // importSpaceMeta: archives the harness writes (spec/SPACES-POLICIES.md,
  // "importSpaceMeta").
  const im = skey('im')
  const W = (k, v) => ({ key: Buffer.from(k), value: S.encode(v) })
  const tid = () => { let t = '3m'; for (let i = 0; i < 11; i++) t += pick('234567abcdefghijklmnopqrstuvwxyz'.split('')); return t }
  const writerValue = () => ({ repoRev: tid(), data: Buffer.from(Array.from({ length: 32 }, () => Math.floor(rand() * 256))), spaceRev: tid() })
  const imWriters = [[bob.did, writerValue()], [carol.did, writerValue()]]
  const imMembers = [[bob.did, true, true], [carol.did, true, false]]
  const imArchive = (side, key = im) => archiveOf(sp(side, key), msStored({ publicWrite: true }), imMembers, imWriters)
  await importMeta('importSpaceMeta', (side) => imArchive(side), EMPTY)
  await exportIs('exportSpaceMeta of what was imported', im, (side) => imArchive(side))
  await getSpace('getSpace of what was imported', im, msStored({ publicWrite: true }))
  await members('listMembers of what was imported', im, imMembers.map(([did, read, write]) => ({ did, read, write })).sort((x, y) => (x.did < y.did ? -1 : 1)))
  await create('createSpace over an imported space', im, PERSONAL, err('SpaceAlreadyExists'))
  await importMeta('importSpaceMeta replacing', (side) => archiveOf(sp(side, im), PERSONAL), EMPTY)
  await exportIs('exportSpaceMeta after a replacing import', im, (side) => archiveOf(sp(side, im), PERSONAL))
  await importMeta('importSpaceMeta over a space created here', (side) => imArchive(side, m1), EMPTY)
  await exportIs('exportSpaceMeta after importing over a created space', m1, (side) => imArchive(side, m1))
  const meta = (side, key, extra = {}) => ({ $type: 'atproto-space-meta', ver: 1, space: sp(side, key), ...extra })
  const i4 = skey('i')
  const accepted = [
    ['metadata with another field', (side) => S.writeStar(meta(side, skey('i'), { foo: 1 }), [W('policy', MS())])],
    ['a writer with another field', (side) => S.writeStar(meta(side, skey('i')), [W('policy', MS()), W(`writer/${bob.did}`, { ...writerValue(), x: 1 })])],
  ]
  for (const [what, archive] of accepted) await importMeta(`importSpaceMeta of ${what}`, archive, EMPTY)
  await importMeta('importSpaceMeta with a Content-Type parameter', (side) => imArchive(side, skey('i')), EMPTY, { ctype: `${STAR}; charset=utf-8` })
  const iu = skey('i')
  await importMeta('importSpaceMeta of a policy with an unknown field', (side) => S.writeStar(meta(side, iu), [W('policy', { ...MS(), zz: 1 })]), EMPTY)
  await getSpace('getSpace of an imported policy, filled in and dropped', iu, msStored())
  const iw = skey('i')
  await importMeta('importSpaceMeta of a did:web member', (side) => S.writeStar(meta(side, iw), [W('policy', MS()), W(`${MEMBER}/did:web:localhost:2583`, { $type: MEMBER, read: true, write: true })]), EMPTY)
  await members('listMembers of an imported did:web member', iw, [{ did: web, read: true, write: true }])
  const [lo, hi] = [bob.did, carol.did].sort()
  const m = (did) => W(`${MEMBER}/${did}`, { $type: MEMBER, read: true, write: true })
  const w = (did) => W(`writer/${did}`, writerValue())
  const refused = [
    ['an unsupported policy', (side) => S.writeStar(meta(side, i4), [W('policy', { $type: 'com.example.policy' })]), err('UnsupportedPolicy')],
    ['a policy with no $type', (side) => S.writeStar(meta(side, i4), [W('policy', { publicRead: true })]), err('InvalidSpaceMeta')],
    ['a policy field of the wrong type', (side) => S.writeStar(meta(side, i4), [W('policy', MS({ publicRead: 1 }))]), err('InvalidSpaceMeta')],
    ['a managingApp that is not a DID', (side) => S.writeStar(meta(side, i4), [W('policy', MG('x'))]), err('InvalidRequest')],
    ['a managingApp with no fragment', (side) => S.writeStar(meta(side, i4), [W('policy', MG(appDid))]), err('InvalidRequest')],
    ['a policy that is no map', (side) => S.writeStar(meta(side, i4), [W('policy', [1])]), err('InvalidSpaceMeta')],
    ['a policy that is no DRISL', (side) => S.writeStar(meta(side, i4), [{ key: Buffer.from('policy'), value: Buffer.from([0xff]) }]), err('InvalidSpaceMeta')],
    ['no policy', (side) => S.writeStar(meta(side, i4), [w(bob.did)]), err('InvalidSpaceMeta')],
    ['no pairs', (side) => S.writeStar(meta(side, i4), []), err('InvalidSpaceMeta')],
    ['an unknown policy state key', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), W('com.example.thing/x', { a: 1 })]), err('InvalidSpaceMeta')],
    ['members under a personalspace', (side) => S.writeStar(meta(side, i4), [W('policy', PERSONAL), m(bob.did)]), err('InvalidSpaceMeta')],
    ['a member key that is not a DID', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), W(`${MEMBER}/bob`, { $type: MEMBER, read: true, write: true })]), err('InvalidSpaceMeta')],
    ['a member with no $type', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), W(`${MEMBER}/${bob.did}`, { read: true, write: true })]), err('InvalidSpaceMeta')],
    ['a member with no write', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), W(`${MEMBER}/${bob.did}`, { $type: MEMBER, read: true })]), err('InvalidSpaceMeta')],
    ['members out of order', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), m(hi), m(lo)]), err('InvalidSpaceMeta')],
    ['a member twice', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), m(lo), m(lo)]), err('InvalidSpaceMeta')],
    ['a writer before a member', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), w(lo), m(lo)]), err('InvalidSpaceMeta')],
    ['writers out of order', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), w(hi), w(lo)]), err('InvalidSpaceMeta')],
    ['the policy after a member', (side) => S.writeStar(meta(side, i4), [m(lo), W('policy', MS())]), err('InvalidSpaceMeta')],
    ['a writer with no spaceRev', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), W(`writer/${lo}`, { repoRev: tid(), data: Buffer.alloc(32) })]), err('InvalidSpaceMeta')],
    ['a writer whose repoRev is named rev', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), W(`writer/${lo}`, { rev: tid(), data: Buffer.alloc(32), spaceRev: tid() })]), err('InvalidSpaceMeta')],
    ['a writer whose repoRev is no TID', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), W(`writer/${lo}`, { ...writerValue(), repoRev: 'nope' })]), err('InvalidSpaceMeta')],
    ['a writer that is no map', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), W(`writer/${lo}`, [1])]), err('InvalidSpaceMeta')],
    ['a writer key that is not a DID', (side) => S.writeStar(meta(side, i4), [W('policy', MS()), W('writer/bob', writerValue())]), err('InvalidSpaceMeta')],
    ['metadata of another profile', (side) => S.writeStar({ ...meta(side, i4), $type: 'atproto-space-repo' }, [W('policy', MS())]), err('InvalidSpaceMeta')],
    ['metadata of version 2', (side) => S.writeStar(meta(side, i4, { ver: 2 }), [W('policy', MS())]), err('InvalidSpaceMeta')],
    ['metadata with a malformed space', (side) => S.writeStar({ ...meta(side, i4), space: 'at://x' }, [W('policy', MS())]), err('InvalidSpaceMeta')],
    ['a truncated archive', (side) => { const a = S.writeStar(meta(side, i4), [W('policy', MS())]); return a.subarray(0, a.length - 1) }, err('InvalidSpaceMeta')],
    ['bytes after the archive', (side) => Buffer.concat([S.writeStar(meta(side, i4), [W('policy', MS())]), Buffer.from([0])]), err('InvalidSpaceMeta')],
    ['bytes that are no archive', () => Buffer.from('hello'), err('InvalidSpaceMeta')],
    ['no bytes', () => Buffer.alloc(0), err('InvalidSpaceMeta')],
    ['another account\'s space', () => S.writeStar({ $type: 'atproto-space-meta', ver: 1, space: `at://${bob.did}/space/${T}/${i4}` }, [W('policy', MS())]), err('NotAuthorized')],
    // Pairs of faults, which show their order.
    ['another account\'s space and an unsupported policy', () => S.writeStar({ $type: 'atproto-space-meta', ver: 1, space: `at://${bob.did}/space/${T}/${i4}` }, [W('policy', { $type: 'com.example.policy' })]), err('NotAuthorized')],
    ['another account\'s space and no policy', () => S.writeStar({ $type: 'atproto-space-meta', ver: 1, space: `at://${bob.did}/space/${T}/${i4}` }, [w(bob.did)]), err('InvalidSpaceMeta')],
    ['an unsupported policy and a member key that is not a DID', (side) => S.writeStar(meta(side, i4), [W('policy', { $type: 'com.example.policy' }), W(`${MEMBER}/bob`, { a: 1 })]), err('UnsupportedPolicy')],
    ['a managingApp with no fragment and a member', (side) => S.writeStar(meta(side, i4), [W('policy', MG(appDid)), m(lo)]), err('InvalidRequest')],
  ]
  for (const [what, archive, want] of refused) await importMeta(`importSpaceMeta of ${what}`, archive, want)
  for (const ctype of ['application/octet-stream', 'application/json', null]) await importMeta(`importSpaceMeta as ${ctype ?? 'no Content-Type'}`, (side) => imArchive(side, i4), err('InvalidRequest'), { ctype })
  await importMeta('importSpaceMeta with an app password', (side) => imArchive(side, i4), err('InvalidToken'), { token: (side) => appPassword[side.name] })
  await both('importSpaceMeta with no token', 'com.atproto.space.importSpaceMeta', (side) => ({ raw: imArchive(side, i4) }), err('AuthMissing', 401))
  await both('getSpace after refused imports', 'com.atproto.space.getSpace', (side) => ({ token: tok(side), params: { space: sp(side, i4) } }), err('SpaceNotFound'))

  // deleteSpace, and creating again (spec/SPACES-POLICIES.md, "deleteSpace",
  // "createSpace").
  await deleteSpace('deleteSpace', ex)
  await deleteSpace('deleteSpace of a deleted space', ex)
  await deleteSpace('deleteSpace of a space never created', skey('none'), err('SpaceNotFound'))
  await both('deleteSpace of another account\'s space', 'com.atproto.space.deleteSpace', (side) => ({ token: tok(side), body: { space: `at://${bob.did}/space/${T}/${ex}` } }), err('NotAuthorized'))
  const nf = err('SpaceNotFound')
  await both('getSpace of a deleted space', 'com.atproto.space.getSpace', (side) => ({ token: tok(side), params: { space: sp(side, ex) } }), nf)
  await members('listMembers of a deleted space', ex, nf)
  await both('exportSpaceMeta of a deleted space', 'com.atproto.space.exportSpaceMeta', (side) => ({ token: tok(side), params: { space: sp(side, ex) } }), nf)
  await update('updateSpace of a deleted space', ex, MS(), nf)
  await putMembers('putMembers of a deleted space', ex, [[bob.did, true, true]], nf)
  await removeMembers('removeMembers of a deleted space', ex, [bob.did], nf)
  await removeWriter('removeWriter of a deleted space', ex, bob.did, nf)
  // authorizeSpaceSync answers a deleted space SpaceDeleted, whatever the
  // request's authorization, once its input is good (spec/SPACES-POLICIES.md,
  // "deleteSpace"; spec/SPACES-CREDENTIALS.md, "authorizeSpaceSync").
  for (const [what, extra, want] of [
    ['no delegation token', {}, err('SpaceDeleted')],
    ['a delegation token that is no JWT', { delegationToken: 'abc' }, err('SpaceDeleted')],
    ['a client attestation that is no JWT', { clientAttestation: 'abc' }, err('SpaceDeleted')],
    ['a notify endpoint', { notify: { endpoint: 'https://syncer.example', token: `t${Math.floor(rand() * 1e6)}` } }, err('SpaceDeleted')],
    ['a credentialKey that is no key', { credentialKey: 'nope' }, err('InvalidRequest')],
  ]) await both(`authorizeSpaceSync of a deleted space, ${what}`, 'com.atproto.space.authorizeSpaceSync', (side) => ({ body: { space: sp(side, ex), credentialKey: S.newP256().did, ...extra } }), want)
  await create('createSpace of a deleted space', ex, MS({ publishPolicy: false }))
  await getSpace('getSpace of a space created again', ex, msStored())
  await members('listMembers of a space created again', ex, [])
  await exportIs('exportSpaceMeta of a space created again', ex, (side) => archiveOf(sp(side, ex), msStored()))
  await deleteSpace('deleteSpace of an imported space', im)
  await importMeta('importSpaceMeta over a deleted space', (side) => imArchive(side), EMPTY)
  await exportIs('exportSpaceMeta of a deleted space imported again', im, (side) => imArchive(side))

  // ==== 2. publishing ========================================================================

  // The records in the authority's own repo in a space, by collection, each
  // as the page says it must be, with its CID (spec/SPACES-POLICIES.md,
  // "Publishing to readers").
  const recordsOf = (kind, key, collection, want) => both(kind, 'com.atproto.space.listRecords', (side) => ({ token: tok(side), params: { space: sp(side, key), repo: auth(side).did, collection } }), (g) => {
    const records = g.body?.records?.map(({ collection: c, rkey, cid, value }) => ({ collection: c, rkey, cid, value })).sort((x, y) => (x.rkey < y.rkey ? -1 : 1))
    const expect = want.map(([rkey, value]) => ({ collection, rkey, cid: S.cidString(S.cidBytes(S.encode(value))), value })).sort((x, y) => (x.rkey < y.rkey ? -1 : 1))
    return g.status === 200 && isDeepStrictEqual(records, expect) ? null : { records: expect }
  })
  const policyRecord = (policy) => ['self', { $type: POLICY, policy }]
  const memberRecord = (did, read, write) => [rkeyOf(did), { $type: MEMBER, read, write }]
  const pub = skey('pub')
  // The authority's published records, as stage 3 expects its writer entry.
  const published = new Map()
  const publish = (records, collection) => { for (const [k] of [...published]) if (k.startsWith(`${collection}/`)) published.delete(k); for (const [rkey, value] of records) published.set(`${collection}/${rkey}`, S.cidString(S.cidBytes(S.encode(value)))) }
  const expectRecords = async (kind, policyRecords, memberRecords) => {
    await recordsOf(`${kind}: the policy record`, pub, POLICY, policyRecords)
    await recordsOf(`${kind}: the member records`, pub, MEMBER, memberRecords)
    publish(policyRecords, POLICY); publish(memberRecords, MEMBER)
  }
  await create('createSpace publishing', pub, MS({ publishPolicy: true, publishMembers: true }))
  await expectRecords('createSpace publishing', [policyRecord(msStored({ publishPolicy: true, publishMembers: true }))], [])
  await putMembers('putMembers published', pub, [[bob.did, true, false], [web, true, true]])
  await expectRecords('putMembers published', [policyRecord(msStored({ publishPolicy: true, publishMembers: true }))], [memberRecord(bob.did, true, false), memberRecord(web, true, true)])
  await both('getRecord of a member record', 'com.atproto.space.getRecord', (side) => ({ token: tok(side), params: { space: sp(side, pub), repo: auth(side).did, collection: MEMBER, rkey: bob.did } }), (g) => (g.status === 200 && isDeepStrictEqual(g.body?.value, { $type: MEMBER, read: true, write: false }) ? null : { value: { $type: MEMBER, read: true, write: false } }))
  // Which changes make a commit of the authority's repo, by its rev.
  const revOf = async (side) => (await call(side.url, 'com.atproto.space.getLatestCommit', { token: tok(side), params: { space: sp(side, pub), repo: auth(side).did } })).body?.commit?.rev ?? null
  async function commits(kind, action, want) {
    const before = {}
    for (const side of sides) before[side.name] = await revOf(side)
    await action()
    for (const side of sides) {
      const after = await revOf(side)
      if ((after !== before[side.name]) !== want) await fail(side, `${kind}: the authority's commit`, { space: alias(side, sp(side, pub)) }, want ? 'a new rev' : `the rev ${before[side.name]}`, after)
    }
    count(kind)
    return before
  }
  /// The operations since `before` (each side's rev) must be one commit of
  /// exactly `want`, [collection/rkey, deleted] each, by listRepoOps.
  async function oneCommit(kind, before, want) {
    const expect = want.map(([path, deleted]) => `${path} ${deleted ? 'deleted' : 'written'}`).sort()
    await both(`${kind}: one commit`, 'com.atproto.space.listRepoOps', (side) => ({ token: tok(side), params: { space: sp(side, pub), repo: auth(side).did, since: before[side.name], limit: 1000 } }), (g) => {
      const ops = g.body?.ops ?? []
      const got = ops.map((o) => `${o.collection}/${o.rkey} ${o.cid === null ? 'deleted' : 'written'}`).sort()
      return g.status === 200 && new Set(ops.map((o) => o.rev)).size === 1 && isDeepStrictEqual(got, expect) ? null : { ops: expect, revs: 'one' }
    }, (g) => ({ status: g.status, ops: (g.body?.ops ?? []).map((o) => `${o.collection}/${o.rkey} ${o.cid === null ? 'deleted' : 'written'}`).sort() }))
  }
  const batch = [[carol.did, rand() < 0.5, rand() < 0.5], [dave.did, rand() < 0.5, rand() < 0.5]]
  const b0 = await commits('putMembers of several makes a commit', () => putMembers('putMembers of several, published, carol given twice', pub, [[carol.did, true, true], ...batch, [web, true, true]]), true)
  await oneCommit('putMembers of several, one given twice, and one setting what was set', b0, [...batch, [web]].map(([did]) => [`${MEMBER}/${rkeyOf(did)}`, false]))
  await commits('putMembers setting what was set makes a commit', () => putMembers('putMembers setting what was set', pub, [[web, true, true]]), true)
  await commits('putMembers of no members makes no commit', () => putMembers('putMembers of no members, published', pub, []), false)
  await commits('updateSpace to the same policy makes a commit', () => update('updateSpace to the same policy', pub, MS({ publishPolicy: true, publishMembers: true })), true)
  await commits('removeMembers of a DID not listed makes no commit', () => removeMembers('removeMembers of a DID not listed, published', pub, [fakeDid()]), false)
  const b1 = await commits('removeMembers of several makes a commit', () => removeMembers('removeMembers of several, published', pub, [carol.did, fakeDid(), dave.did]), true)
  await oneCommit('removeMembers of several, one not listed', b1, [carol.did, dave.did].map((did) => [`${MEMBER}/${rkeyOf(did)}`, true]))
  await expectRecords('removeMembers of several, published', [policyRecord(msStored({ publishPolicy: true, publishMembers: true }))], [memberRecord(bob.did, true, false), memberRecord(web, true, true)])
  await update('updateSpace no longer publishing members', pub, MS({ publishPolicy: true }))
  await expectRecords('updateSpace no longer publishing members', [policyRecord(msStored({ publishPolicy: true }))], [])
  await update('updateSpace publishing members, not the policy', pub, MS({ publishMembers: true }))
  await expectRecords('updateSpace publishing members, not the policy', [], [memberRecord(bob.did, true, false), memberRecord(web, true, true)])
  await removeMembers('removeMembers published', pub, [bob.did])
  await expectRecords('removeMembers published', [], [memberRecord(web, true, true)])
  await update('updateSpace migrating to a published managedspace', pub, MG(managingApp, { publishPolicy: true }))
  await expectRecords('updateSpace migrating to a published managedspace', [policyRecord(mgStored(managingApp, true))], [])
  await both('a direct write of the policy record', 'com.atproto.space.putRecord', (side) => ({ token: tok(side), body: { space: sp(side, pub), repo: auth(side).did, collection: POLICY, rkey: 'self', record: { $type: POLICY, policy: PERSONAL } } }), err('InvalidRequest'))
  await both('a direct write of a member record', 'com.atproto.space.createRecord', (side) => ({ token: tok(side), body: { space: sp(side, pub), repo: auth(side).did, collection: MEMBER, rkey: bob.did, record: { $type: MEMBER, read: true, write: true } } }), err('InvalidRequest'))
  await both('clearRecords of the authority\'s repo', 'com.atproto.space.clearRecords', (side) => ({ token: tok(side), body: { space: sp(side, pub), repo: auth(side).did } }), (g) => (g.status === 200 ? null : 'cleared'))
  await expectRecords('clearRecords keeps the published records', [policyRecord(mgStored(managingApp, true))], [])

  // ==== 3. the writer set ====================================================================

  // Writes enter the writer set by repo update notifications (the
  // notifications' part). Until the server serves
  // com.atproto.space.notifyRepoUpdate, the writes go to both sides as below,
  // but only the reference's writer set is held to the page; from then on,
  // both are, and compared (spec/SPACES-POLICIES.md, "The writer set", "Who is
  // authorized", "For other slices").
  const probe = await call(cand.url, 'com.atproto.space.notifyRepoUpdate', { body: {} })
  const wsides = probe.status === 501 || probe.status === 404 ? [ref] : sides
  if (wsides.length === 1) count('the writer set: the reference alone (the server serves no notifyRepoUpdate)')

  // Each repo's records in each space, so that its data is known.
  const repos = {}
  const repoOf = (side, key, did) => ((repos[`${side.name} ${key} ${did}`] ??= new Map()))
  const dataOf = (side, key, did) => { const lt = new S.LtHash(); for (const [path, cid] of repoOf(side, key, did)) lt.add(`${path}/${cid}`); return lt.digest().toString('hex') }
  const authorWriter = { did: (side) => auth(side).did, token: tok, host: (side) => side.url }
  const asWriter = (p) => ({ did: () => p.did, token: () => p.token, host: () => peerHost })
  /// A write by `who` into its own repo in each side's space, the same record.
  async function write(kind, who, key) {
    const rkey = `r${Math.floor(rand() * 1e9)}`
    const record = { $type: 'com.example.post', text: `${kind} ${rkey}`, createdAt: '2026-11-08T00:00:00.000Z' }
    for (const side of sides) {
      const res = await call(who.host(side), 'com.atproto.space.createRecord', { token: who.token(side), body: { space: sp(side, key), repo: who.did(side), collection: 'com.example.post', rkey, record } })
      if (res.status !== 200) await fail(side, `${kind}: a write into the space`, describe(side, { space: sp(side, key), rkey }), 'written', normalize(side, res))
      repoOf(side, key, who.did(side)).set(`com.example.post/${rkey}`, res.body.cid)
    }
  }
  /// Wait until each side's writer set tracks `who` at its repo's data.
  async function tracked(kind, who, key) {
    const started = Date.now()
    const done = new Set()
    let last = {}
    for (;;) {
      for (const side of wsides) {
        if (done.has(side.name)) continue
        const res = await call(side.url, 'com.atproto.space.exportSpaceMeta', { token: tok(side), params: { space: sp(side, key) } })
        const got = await readArchive(side, res, sp(side, key), { space: alias(side, sp(side, key)) })
        last[side.name] = got.writers[who.did(side)] ?? null
        if (last[side.name]?.data === dataOf(side, key, who.did(side))) done.add(side.name)
      }
      if (done.size === wsides.length) break
      if (Date.now() - started > 15000) {
        const side = wsides.find((s) => !done.has(s.name))
        await fail(side, `${kind}: the writer set tracking a write`, { space: alias(side, sp(side, key)), writer: alias(side, who.did(side)) }, { data: dataOf(side, key, who.did(side)) }, last[side.name])
      }
      await sleep(100)
    }
    count(kind)
  }
  // A sentinel: a write a tracked peer makes after the write in question,
  // which, once tracked, shows that the earlier one has been answered.
  const sentinel = skey('z')
  await create('createSpace for the sentinel', sentinel, MS())
  await putMembers('putMembers for the sentinel', sentinel, [[carol.did, false, true]])
  async function settled(kind) { await write(`${kind} (sentinel)`, asWriter(carol), sentinel); await tracked(`${kind} (sentinel)`, asWriter(carol), sentinel); await sleep(250) }
  /// The writer set must be exactly these, each at its repo's data.
  async function writersAre(kind, key, who) {
    const got = await exportBoth(kind, key, wsides)
    for (const side of wsides) {
      const want = Object.fromEntries(who.map((x) => [x.did(side), dataOf(side, key, x.did(side))]))
      const have = Object.fromEntries(Object.entries(got[side.name].writers).map(([did, v]) => [did, v.data]))
      if (!isDeepStrictEqual(have, want)) await fail(side, `${kind}: the writer set`, { space: alias(side, sp(side, key)) }, JSON.parse(alias(side, JSON.stringify(want))), JSON.parse(alias(side, JSON.stringify(have))))
    }
  }
  const [B, C, D, E] = [bob, carol, dave, eve].map(asWriter)

  const ws = skey('w')
  await create('createSpace for writers', ws, MS())
  await putMembers('putMembers of writers and a reader', ws, [[bob.did, true, true], [carol.did, false, true], [dave.did, true, false]])
  await write('a write by a member who may not write', D, ws)
  await write('a write by a member who may write', B, ws)
  await write('a write by another member who may write', C, ws)
  await write('a write by the authority', authorWriter, ws)
  await tracked('a member\'s write tracked', B, ws)
  await tracked('another member\'s write tracked', C, ws)
  await tracked('the authority\'s write tracked', authorWriter, ws)
  await sleep(250)
  await writersAre('the writer set of a memberspace', ws, [B, C, authorWriter])
  await removeWriter('removeWriter of a writer', ws, bob.did)
  await writersAre('the writer set after removeWriter', ws, [C, authorWriter])
  await removeWriter('removeWriter of a writer again', ws, bob.did)
  await write('a write by a removed writer', B, ws)
  await tracked('a removed writer tracked again', B, ws)
  await putMembers('putMembers taking write away', ws, [[bob.did, true, false]])
  await writersAre('the writer set after putMembers with write false', ws, [C, authorWriter])
  await write('a write by a member whose write was taken away', B, ws)
  await putMembers('putMembers giving write back', ws, [[carol.did, true, true]])
  await settled('after a write not authorized')
  await writersAre('the writer set after a write not authorized', ws, [C, authorWriter])
  await removeMembers('removeMembers of a writer', ws, [carol.did])
  await writersAre('the writer set after removeMembers', ws, [authorWriter])
  // Under publicWrite, an account not listed is tracked, one taken off the
  // list again, and a member whose write is false not.
  await update('updateSpace to publicWrite', ws, MS({ publicWrite: true }))
  await write('a write by anyone under publicWrite', E, ws)
  await write('a write under publicWrite by a member who may not write', D, ws)
  await write('a write under publicWrite by a member removed before', C, ws)
  await tracked('a write under publicWrite tracked', E, ws)
  await tracked('a removed member\'s write under publicWrite tracked', C, ws)
  await settled('under publicWrite, a member who may not write')
  await writersAre('the writer set under publicWrite', ws, [C, E, authorWriter])
  await removeMembers('removeMembers of a writer not listed', ws, [eve.did])
  await writersAre('the writer set after removeMembers of a writer not listed', ws, [C, E, authorWriter])
  await removeWriter('removeWriter of a writer not listed', ws, eve.did)
  await writersAre('the writer set after removeWriter of a writer not listed', ws, [C, authorWriter])
  await removeWriter('removeWriter of the authority', ws, authorWriter.did)
  await writersAre('the writer set without its authority', ws, [C])
  await write('a write by the authority after its removal', authorWriter, ws)
  await tracked('the authority tracked again', authorWriter, ws)
  await update('updateSpace migrating to personalspace', ws, PERSONAL)
  await writersAre('the writer set after migrating', ws, [C, authorWriter])
  const cBefore = Object.fromEntries(sides.map((side) => [side.name, dataOf(side, ws, carol.did)]))
  await write('a write by a writer the new policy does not authorize', C, ws)
  await settled('under personalspace')
  {
    const got = await exportBoth('the writer set keeps a writer not authorized', ws, wsides)
    for (const side of wsides) if (got[side.name].writers[carol.did]?.data !== cBefore[side.name]) await fail(side, 'a write the policy does not authorize changes nothing in the writer set', { space: alias(side, sp(side, ws)) }, { data: cBefore[side.name] }, got[side.name].writers[carol.did] ?? null)
  }
  await deleteSpace('deleteSpace of a space with writers', ws)
  await create('createSpace again after writers', ws, MS())
  await writersAre('the writer set of a space created again', ws, [])
  // The personalspace tracks no one but its authority.
  const pw = skey('pw')
  await create('createSpace personalspace for writers', pw, PERSONAL)
  await write('a write into a personalspace', B, pw)
  await write('the authority\'s write into its personalspace', authorWriter, pw)
  await tracked('the authority tracked in its personalspace', authorWriter, pw)
  await settled('in a personalspace')
  await writersAre('the writer set of a personalspace', pw, [authorWriter])
  // A managedspace asks its app about each writer but the authority, without
  // a client, and takes its `write` (spec/SPACES-POLICIES.md, "Asking a
  // managing app: checkAccess").
  const mw = skey('mw')
  answer = (q) => ({ status: 200, body: { read: true, write: q.repo === carol.did } })
  await create('createSpace managedspace for writers', mw, MG(managingApp))
  calls.length = 0
  await write('a write the managing app refuses', B, mw)
  await write('a write the managing app allows', C, mw)
  await write('the authority\'s write into a managedspace', authorWriter, mw)
  await tracked('a write the managing app allows, tracked', C, mw)
  await tracked('the authority tracked in a managedspace', authorWriter, mw)
  await sleep(250)
  await writersAre('the writer set of a managedspace', mw, [C, authorWriter])
  await checkCalls('the managing app asked about writes', mw, [bob.did, carol.did], wsides)
  // A write the app fails to decide is not tracked; in a space of its own,
  // as the writer's PDS may ask again later.
  const mf = skey('mf')
  answer = (q) => ({ status: 200, body: { read: false, write: q.repo === carol.did } })
  await create('createSpace managedspace for a write not decided', mf, MG(managingApp))
  await write('a write the managing app allows, before', C, mf)
  await tracked('a write the managing app allows, before, tracked', C, mf)
  calls.length = 0
  answer = () => ({ status: 500, body: { error: 'InternalServerError' } })
  await write('a write the managing app fails to decide', B, mf)
  await settled('a write the managing app fails to decide')
  await writersAre('the writer set after a write the managing app fails to decide', mf, [C])
  await checkCalls('the managing app asked about a write it fails to decide', mf, [bob.did], wsides)
  // The authority's published records are its writes, tracked like any.
  for (const side of sides) { const r = repoOf(side, pub, auth(side).did); r.clear(); for (const [path, cid] of published) r.set(path, cid) }
  await tracked('the authority\'s published records tracked', authorWriter, pub)

  // ==== 4. reads =============================================================================

  /// authorizeSpaceSync of each side's space, with `who`'s delegation token
  /// or none; a credential is compared as there or not, its content being
  /// the credentials' part (spec/SPACES-POLICIES.md, "Who is authorized",
  /// "For other slices").
  async function credential(kind, key, who, want) {
    await both(kind, 'com.atproto.space.authorizeSpaceSync', (side) => ({ body: { space: sp(side, key), credentialKey: S.newP256().did, ...(who ? { delegationToken: who.delegation[side.name] } : {}) } }), want, (g) => (g.status === 200 ? { status: 200, credential: typeof g.body?.credential === 'string' } : g))
  }
  /// A delegation token for each side's space from the user's PDS.
  async function delegate(who, key) {
    const out = { delegation: {} }
    for (const side of sides) {
      const host = who === 'authority' ? side.url : peerHost
      const token = who === 'authority' ? tok(side) : who.token
      const res = await call(host, 'com.atproto.space.getDelegationToken', { token, params: { space: sp(side, key) } })
      if (res.status !== 200) await fail(side, 'getDelegationToken', { space: alias(side, sp(side, key)) }, 'a delegation token', normalize(side, res))
      out.delegation[side.name] = res.body.token
    }
    return out
  }
  const granted = (g, r) => (r.status === 200 && typeof r.body?.credential === 'string' ? null : 'a credential')
  const credentialShape = (want) => (g, r) => (want === 'granted' ? granted(g, r) : isDeepStrictEqual(g, err(want, want === 'UpstreamFailure' ? 502 : 400)) ? null : err(want, want === 'UpstreamFailure' ? 502 : 400))
  const rs = skey('r')
  await create('createSpace for reads', rs, MS())
  await putMembers('putMembers of a reader and a writer', rs, [[bob.did, true, false], [carol.did, false, true]])
  const cases = [
    ['a member who may read', () => delegate(bob, rs), 'granted'],
    ['a member who may only write', () => delegate(carol, rs), 'SpaceNotFound'],
    ['someone not a member', () => delegate(dave, rs), 'SpaceNotFound'],
    ['the authority', () => delegate('authority', rs), 'granted'],
    ['no delegation token', async () => null, 'SpaceNotFound'],
  ]
  for (const [what, who, want] of cases) await credential(`authorizeSpaceSync of a memberspace, ${what}`, rs, await who(), credentialShape(want))
  await update('updateSpace to publicRead', rs, MS({ publicRead: true }))
  await credential('authorizeSpaceSync of a publicRead memberspace, no delegation token', rs, null, credentialShape('granted'))
  await credential('authorizeSpaceSync of a publicRead memberspace, someone not a member', rs, await delegate(dave, rs), credentialShape('granted'))
  const allowed = ['https://app.example/client-metadata.json']
  await update('updateSpace to publicRead with allowedApps', rs, MS({ publicRead: true, allowedApps: allowed }))
  await credential('authorizeSpaceSync of allowedApps with no attestation, no delegation token', rs, null, credentialShape('AppNotAuthorized'))
  await credential('authorizeSpaceSync of allowedApps with no attestation, a member', rs, await delegate(bob, rs), credentialShape('AppNotAuthorized'))
  await update('updateSpace to allowedApps alone', rs, MS({ allowedApps: allowed }))
  await credential('authorizeSpaceSync of allowedApps, someone not a member', rs, await delegate(dave, rs), credentialShape('SpaceNotFound'))
  await credential('authorizeSpaceSync of allowedApps, a member', rs, await delegate(bob, rs), credentialShape('AppNotAuthorized'))
  await credential('authorizeSpaceSync of allowedApps, the authority', rs, await delegate('authority', rs), credentialShape('AppNotAuthorized'))
  await credential('authorizeSpaceSync of a personalspace, someone else', pers, await delegate(bob, pers), credentialShape('SpaceNotFound'))
  await credential('authorizeSpaceSync of a personalspace, the authority', pers, await delegate('authority', pers), credentialShape('granted'))
  // A managedspace asks its app about each reader but the authority, a read
  // with no delegation token with no repo, and takes its `read`.
  answer = (q) => ({ status: 200, body: { read: q.repo === bob.did, write: q.repo !== bob.did } })
  calls.length = 0
  await credential('authorizeSpaceSync of a managedspace, a user the app allows', mw, await delegate(bob, mw), credentialShape('granted'))
  await credential('authorizeSpaceSync of a managedspace, a user the app refuses', mw, await delegate(carol, mw), credentialShape('SpaceNotFound'))
  await credential('authorizeSpaceSync of a managedspace, the authority', mw, await delegate('authority', mw), credentialShape('granted'))
  await credential('authorizeSpaceSync of a managedspace, no delegation token, refused', mw, null, credentialShape('SpaceNotFound'))
  await checkCalls('the managing app asked about reads', mw, [bob.did, carol.did, null])
  answer = (q) => ({ status: 200, body: { read: !q.repo, write: false } })
  await credential('authorizeSpaceSync of a managedspace, no delegation token, allowed', mw, null, credentialShape('granted'))
  await checkCalls('the managing app asked about a read with no delegation token', mw, [null])
  // Its answers, taken or failing to decide.
  for (const [what, a, want] of [
    ['answers another field too', { status: 200, body: { read: true, write: false, other: 1 } }, 'granted'],
    ['answers 201', { status: 201, body: { read: true, write: false } }, 'granted'],
    ['errs', { status: 500, body: { error: 'InternalServerError' } }, 'UpstreamFailure'],
    ['refuses the service auth', { status: 401, body: { error: 'AuthRequired' } }, 'UpstreamFailure'],
    ['answers "true"', { status: 200, body: { read: 'true', write: false } }, 'UpstreamFailure'],
    ['answers no write', { status: 200, body: { read: true } }, 'UpstreamFailure'],
    ['answers authorized', { status: 200, body: { authorized: true } }, 'UpstreamFailure'],
    ['answers no JSON', { status: 200, body: 'nope' }, 'UpstreamFailure'],
    ['answers JSON as text/plain', { status: 200, body: { read: true, write: false }, ctype: 'text/plain' }, 'UpstreamFailure'],
    ['answers in 600000 bytes', { status: 200, body: { read: true, write: false, pad: 'x'.repeat(600000) } }, 'UpstreamFailure'],
    ['answers in 400000 bytes', { status: 200, body: { read: true, write: false, pad: 'x'.repeat(400000) } }, 'granted'],
  ]) {
    answer = () => a
    await credential(`authorizeSpaceSync of a managedspace whose app ${what}`, mw, await delegate(bob, mw), credentialShape(want))
    await checkCalls(`the managing app asked though it ${what}`, mw, [bob.did])
  }
  answer = () => ({ status: 200, body: { read: true, write: true } })
  await update('updateSpace to a managing app of a fragment its document lacks', mw, MG(`${appDid}#nope`))
  await credential('authorizeSpaceSync of a managing app of a fragment its document lacks', mw, await delegate(bob, mw), credentialShape('UpstreamFailure'))
  await checkCalls('no call to a managing app of a fragment its document lacks', mw, [])
  // Endpoints of other forms: asked at their origin alone, or not at all.
  for (const [form, asked] of [['path', true], ['query', true], ['endq', true], ['frag', true], ['user', false], ['ftp', false], ['noscheme', false]]) {
    const app = `${appDid}#${form}`
    const what = `an endpoint ${endpoints[form].endpoint.replace(String(appPort), '<port>')}`
    await update(`updateSpace to a managing app of ${what}`, mw, MG(app))
    await credential(`authorizeSpaceSync of a managing app of ${what}`, mw, await delegate(bob, mw), credentialShape(asked ? 'granted' : 'UpstreamFailure'))
    await checkCalls(`${asked ? 'the call to' : 'no call to'} a managing app of ${what}`, mw, asked ? [bob.did] : [], sides, app)
  }
  // Held to the page alone, the reference following redirects: a redirect
  // fails to decide, the app not asked (spec/SPACES-POLICIES.md, "Where the
  // reference departs from this page").
  {
    await update('updateSpace to a managing app that redirects to the app', mw, MG(`${appDid}#redir`))
    const token = (await delegate(bob, mw)).delegation[cand.name]
    calls.length = 0
    redirected.length = 0
    const req = { body: { space: sp(cand, mw), credentialKey: S.newP256().did, delegationToken: token } }
    const g = shape(cand, await call(cand.url, 'com.atproto.space.authorizeSpaceSync', req))
    if (!isDeepStrictEqual(g, err('UpstreamFailure', 502))) await fail(cand, 'authorizeSpaceSync of a managing app that redirects to the app', describe(cand, req), err('UpstreamFailure', 502), g)
    if (calls.length) await fail(cand, 'authorizeSpaceSync of a managing app that redirects: the calls to the app', describe(cand, req), 'none', calls.map((c) => c.path))
    if (!redirected.length) await fail(cand, 'authorizeSpaceSync of a managing app that redirects: asked there', describe(cand, req), 'one request to the redirecting endpoint', 'none')
    count('a managing app that redirects (the page alone)')
  }
  redirector.close()

  // ==== 5. takedown and deactivation =======================================================

  // The reference is put in each state through its own means; the server,
  // only once it serves them: deactivateAccount, and the admin's
  // updateSubjectStatus with PDS_ADMIN_PASSWORD. Until then the server is
  // not asked, and the reference alone is held to the page
  // (spec/SPACES-POLICIES.md, "Takedown and deactivation").
  /// Each method here by an account, `at(side, key)` its spaces' URIs: what
  /// each answers an account deactivated or taken down.
  const management = (at, key) => [
    ['createSpace', 'com.atproto.space.createSpace', () => ({ body: { spaceType: T, skey: skey('s'), policy: PERSONAL } }), 'blocked'],
    ['updateSpace', 'com.atproto.space.updateSpace', (side) => ({ body: { space: at(side, key), policy: MS() } }), 'blocked'],
    ['putMembers', 'com.atproto.memberspace.putMembers', (side) => ({ body: { space: at(side, key), members: [{ did: bob.did, read: true, write: true }] } }), 'blocked'],
    ['removeMembers', 'com.atproto.memberspace.removeMembers', (side) => ({ body: { space: at(side, key), dids: [bob.did] } }), 'blocked'],
    ['removeWriter', 'com.atproto.space.removeWriter', (side) => ({ body: { space: at(side, key), repo: bob.did } }), 'blocked'],
    ['getSpace', 'com.atproto.space.getSpace', (side) => ({ params: { space: at(side, key) } }), 'open'],
    ['listMembers', 'com.atproto.memberspace.listMembers', (side) => ({ params: { space: at(side, key) } }), 'open'],
    ['exportSpaceMeta', 'com.atproto.space.exportSpaceMeta', (side) => ({ params: { space: at(side, key) } }), 'open'],
    ['importSpaceMeta', 'com.atproto.space.importSpaceMeta', (side) => ({ raw: archiveOf(at(side, skey('s')), PERSONAL) }), 'import'],
    ['deleteSpace', 'com.atproto.space.deleteSpace', (side) => ({ body: { space: at(side, key) } }), 'blocked'],
  ]
  async function statusChecks(state, error, enter) {
    const acct = await createAccount()
    const key = skey('st')
    const tokenOf = (side) => acct.sides[side.name].token
    const spOf = (side, k) => `at://${acct.sides[side.name].did}/space/${T}/${k}`
    for (const side of sides) {
      const r = await call(side.url, 'com.atproto.space.createSpace', { token: tokenOf(side), body: { spaceType: T, skey: key, policy: MS() } })
      if (r.status !== 200) await fail(side, `createSpace for an account to be ${state}`, {}, 'the space created', normalize(side, r))
    }
    const inState = []
    for (const side of sides) if (await enter(side, acct)) inState.push(side)
    if (!inState.includes(ref)) await fail(ref, `putting an account ${state}`, {}, 'done', 'refused')
    const compared = inState.includes(cand)
    const blocked = err(error, 401)
    for (const [name, nsid, make, kind] of management(spOf, key)) {
      const want = kind === 'blocked' || (kind === 'import' && state === 'taken down') ? blocked : (g) => (g.status === 200 ? null : 'answered as for an active account')
      const res = []
      for (const side of compared ? sides : [ref]) {
        const req = { token: tokenOf(side), ...make(side) }
        const g = shape(side, await call(side.url, nsid, req))
        const wrong = typeof want === 'function' ? want(g) : isDeepStrictEqual(g, want) ? null : want
        if (wrong) await fail(side, `${name} by an account ${state}`, describe(side, req), wrong, g)
        res.push(g)
      }
      if (compared && !isDeepStrictEqual(res[0], res[1])) await differ(`${name} by an account ${state}`, describe(cand, make(cand)), res[0], res[1])
      count(compared ? `${state}: compared` : `${state}: the reference alone`)
    }
    // Its space repo's writes and getDelegationToken (spec/SPACES-REPO.md,
    // "The order of the checks";
    // spec/SPACES-CREDENTIALS.md, "getDelegationToken", "authorizeSpaceSync"),
    // with its token from before, and authorizeSpaceSync of its space, it the
    // authority: probed on the alpha.
    const didOf = (side) => acct.sides[side.name].did
    const record = (rkey, text = 'x') => ({ collection: 'com.example.post', rkey, record: { $type: 'com.example.post', text } })
    const suspended = err(state === 'taken down' ? 'RepoTakendown' : 'RepoDeactivated')
    const delegated = {}
    const keyOf = S.newP256().did
    const rows = [
      ['space.createRecord', 'com.atproto.space.createRecord', (side) => ({ token: tokenOf(side), body: { space: spOf(side, key), repo: didOf(side), ...record('a') } }), blocked],
      ['space.putRecord', 'com.atproto.space.putRecord', (side) => ({ token: tokenOf(side), body: { space: spOf(side, key), repo: didOf(side), ...record('a') } }), blocked],
      ['space.deleteRecord', 'com.atproto.space.deleteRecord', (side) => ({ token: tokenOf(side), body: { space: spOf(side, key), repo: didOf(side), collection: 'com.example.post', rkey: 'a' } }), blocked],
      ['space.applyWrites', 'com.atproto.space.applyWrites', (side) => ({ token: tokenOf(side), body: { space: spOf(side, key), repo: didOf(side), writes: [{ $type: 'com.atproto.space.applyWrites#create', collection: 'com.example.post', rkey: 'b', value: { $type: 'com.example.post', text: 'b' } }] } }), blocked],
      ['space.clearRecords', 'com.atproto.space.clearRecords', (side) => ({ token: tokenOf(side), body: { space: spOf(side, key), repo: didOf(side) } }), blocked],
      ['space.createRecord, input the lexicon refuses', 'com.atproto.space.createRecord', (side) => ({ token: tokenOf(side), body: { space: 'nope', repo: didOf(side) } }), blocked],
      ['space.createRecord, a body past 1000000 bytes', 'com.atproto.space.createRecord', (side) => ({ token: tokenOf(side), body: { space: spOf(side, key), repo: didOf(side), ...record('c', 'x'.repeat(1100000)) } }), blocked],
      ['space.createRecord, another account\'s repo', 'com.atproto.space.createRecord', (side) => ({ token: tokenOf(side), body: { space: spOf(side, key), repo: bob.did, ...record('d') } }), blocked],
      ['getDelegationToken', 'com.atproto.space.getDelegationToken', (side) => ({ token: tokenOf(side), params: { space: spOf(side, key) } }), blocked],
      ['getDelegationToken of no space-ref', 'com.atproto.space.getDelegationToken', (side) => ({ token: tokenOf(side), params: { space: 'nope' } }), err('InvalidRequest')],
      ['authorizeSpaceSync of its space, no token', 'com.atproto.space.authorizeSpaceSync', (side) => ({ body: { space: spOf(side, key), credentialKey: keyOf } }), suspended],
      ['authorizeSpaceSync of its space, a user\'s token', 'com.atproto.space.authorizeSpaceSync', (side) => ({ body: { space: spOf(side, key), credentialKey: keyOf, delegationToken: delegated[side.name] } }), suspended],
      ['authorizeSpaceSync of its space, that token again (not spent)', 'com.atproto.space.authorizeSpaceSync', (side) => ({ body: { space: spOf(side, key), credentialKey: keyOf, delegationToken: delegated[side.name] } }), suspended],
      ['authorizeSpaceSync of its space never made', 'com.atproto.space.authorizeSpaceSync', (side) => ({ body: { space: spOf(side, 'never'), credentialKey: keyOf } }), suspended],
      ['authorizeSpaceSync of its space, a credentialKey no key', 'com.atproto.space.authorizeSpaceSync', (side) => ({ body: { space: spOf(side, key), credentialKey: 'nope' } }), err('InvalidRequest')],
      ['authorizeSpaceSync of its space, a token that is no JWT', 'com.atproto.space.authorizeSpaceSync', (side) => ({ body: { space: spOf(side, key), credentialKey: keyOf, delegationToken: 'abc' } }), suspended],
    ]
    for (const side of sides) delegated[side.name] = (await call(peerHost, 'com.atproto.space.getDelegationToken', { token: bob.token, params: { space: spOf(side, key) } })).body?.token
    for (const [name, nsid, make, want] of rows) {
      const res = []
      for (const side of compared ? sides : [ref]) {
        const req = make(side)
        const g = shape(side, await call(side.url, nsid, req))
        if (!isDeepStrictEqual(g, want)) await fail(side, `${name} by or of an account ${state}`, describe(side, { ...req, body: req.body && JSON.parse(JSON.stringify(req.body).replace(/x{1000,}/, '<1100000 x>')) }), want, g)
        res.push(g)
      }
      if (compared && !isDeepStrictEqual(res[0], res[1])) await differ(`${name} by or of an account ${state}`, {}, res[0], res[1])
      count(compared ? `${state}: compared` : `${state}: the reference alone`)
    }
    return { acct, compared, key, spOf }
  }
  await statusChecks('deactivated', 'AccountDeactivated', async (side, acct) => {
    const r = await call(side.url, 'com.atproto.server.deactivateAccount', { token: acct.sides[side.name].token, body: {} })
    return r.status === 200
  })
  const adminAuth = (side) => (side === ref ? refPds.adminAuth() : env.PDS_ADMIN_PASSWORD ? `Basic ${Buffer.from(`admin:${env.PDS_ADMIN_PASSWORD}`).toString('base64')}` : null)
  const td = await statusChecks('taken down', 'AccountTakedown', async (side, acct) => {
    const admin = adminAuth(side)
    if (!admin) return false
    const r = await call(side.url, 'com.atproto.admin.updateSubjectStatus', { auth: admin, body: { subject: { $type: 'com.atproto.admin.defs#repoRef', did: acct.sides[side.name].did }, takedown: { applied: true, ref: 'spaces' } } })
    return r.status === 200
  })
  // A taken-down account's allowTakendown session exports its spaces, and
  // nothing else here; the admin token is taken by neither read.
  for (const side of td.compared ? sides : [ref]) {
    const s = await call(side.url, 'com.atproto.server.createSession', { body: { identifier: td.acct.sides[side.name].handle ?? td.acct.handle, password: td.acct.password, allowTakendown: true } })
    if (s.status !== 200) { await fail(side, 'createSession with allowTakendown', {}, 'a session', normalize(side, s)); continue }
    for (const [name, nsid, make] of management(td.spOf, td.key)) {
      const req = { token: s.body.accessJwt, ...make(side) }
      const g = shape(side, await call(side.url, nsid, req))
      const want = name === 'exportSpaceMeta' ? { status: 200, archive: true } : err('InvalidToken')
      if (!isDeepStrictEqual(g, want)) await fail(side, `${name} with an allowTakendown session`, describe(side, req), want, g)
    }
    for (const nsid of ['com.atproto.space.getSpace', 'com.atproto.space.exportSpaceMeta']) {
      const admin = adminAuth(side)
      const g = shape(side, await call(side.url, nsid, { auth: admin, params: { space: td.spOf(side, td.key) } }))
      if (!isDeepStrictEqual(g, err('InvalidToken'))) await fail(side, `${nsid} with the admin token`, {}, err('InvalidToken'), g)
    }
    count(td.compared ? 'taken down: compared' : 'taken down: the reference alone')
  }

  app.close()
}