~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
578 lines · 39.7 KB Raw History
// OAuth for MCP clients (spec/OAUTH-MCP.md), on the server alone, as the
// reference has no MCP endpoint: an account signed in as Claude does, from
// the endpoint's 401 to tool calls with the bearer token it is given, its
// refresh and revocation; where else that token is refused; and what the
// MCP issuer refuses. The writes it makes are made on the reference too.
// Then MCP sessions on accounts of their own, through a takedown, two
// deactivations and a deletion, each change made on both sides alike; and,
// in a run with crashes, sessions made before each restart, after it.

import { isDeepStrictEqual } from 'node:util'
import { FIREHOSE } from '../lib/args.mjs'
import { ADMIN_PASSWORD } from '../lib/env.mjs'
import { checkMail } from '../lib/mail.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { serve } from '../lib/clients.mjs'
import { fail } from '../lib/plc.mjs'
import { count, differ } from '../lib/report.mjs'
import { below, pick } from '../lib/random.mjs'
import { accounts, didOf, nextBatch, noteCommit, noteWrite, tokenOf } from '../lib/state.mjs'
import { both, normalize, xrpc, xrpcHttp } from '../lib/xrpc.mjs'
import { Browser, answer, form, fresh, pkce, target } from '../lib/oauth.mjs'
import { mcpPost } from '../lib/via.mjs'
import { createAccount } from './accounts.mjs'
import { approved } from './oauth.mjs'

/// The legacy revision Claude speaks, and the scope it is given.
const ERA = '2025-11-25'
const SCOPE = 'atproto transition:generic'
/// Claude's two documents, as Claude publishes them, on the client web's
/// host for it: the hosted apps' and Claude Code's.
const HOST = 'https://claude.pds-harness.net'
const HOSTED = `${HOST}/oauth/claude-client-metadata`
const HOSTED_REDIRECT = `${HOST}/api/mcp/auth_callback`
const CODE = `${HOST}/oauth/claude-code-client-metadata`
/// Documents with one thing wrong.
const OTHER_ID = `${HOST}/oauth/other-client-id`
const NO_AUTH_METHOD = `${HOST}/oauth/no-auth-method`
/// A client without the refresh grant.
const NO_REFRESH = `${HOST}/oauth/no-refresh`

/// The resource, the MCP issuer and the resource's metadata
/// (spec/OAUTH-MCP.md, "Names").
const names = () => {
  const origin = new URL(cand.publicUrl).origin
  return { origin, resource: `${origin}/mcp`, issuer: `${origin}/oauth/mcp`, prm: `${origin}/.well-known/oauth-protected-resource/mcp` }
}
const at = (path) => `${cand.url}${path}`
const broke = (what, request, want, got) => fail(cand, `MCP OAuth: ${what}`, request, want, got)

/// Serve Claude's documents and those with one thing wrong on the client
/// web (spec/OAUTH-MCP.md, "Clients").
function publish() {
  const doc = (id, over = {}) => ({ client_id: id, client_name: 'Claude', client_uri: 'https://claude.ai', redirect_uris: [HOSTED_REDIRECT], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', ...over })
  serve(HOSTED, doc(HOSTED))
  serve(CODE, doc(CODE, { client_name: 'Claude Code', redirect_uris: ['http://localhost/callback', 'http://127.0.0.1/callback'] }))
  serve(OTHER_ID, doc(HOSTED))
  const { token_endpoint_auth_method, ...noMethod } = doc(NO_AUTH_METHOD)
  serve(NO_AUTH_METHOD, noMethod)
  serve(NO_REFRESH, doc(NO_REFRESH, { grant_types: ['authorization_code'] }))
}

/// A `tools/call` at the MCP endpoint in Claude's revision: answers its HTTP
/// status, `WWW-Authenticate`, and the JSON-RPC result or the body.
async function toolCall(name, args, authorization) {
  const r = await mcpPost({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, { 'mcp-protocol-version': ERA, ...(authorization ? { authorization } : {}) })
  const m = r.messages?.[0]
  return { http: r.http, challenge: r.headers?.get('www-authenticate') ?? null, result: m?.result ?? null, body: m ?? r.failed ?? null }
}

/// A challenge's parameters, by name.
function challenge(h) {
  if (!h || !/^Bearer\b/i.test(h)) return null
  return Object.fromEntries([...h.matchAll(/(\w+)="([^"]*)"/g)].map(([, k, v]) => [k, v]))
}

/// `/oauth/mcp/authorize` with `params` in a new browser: its answer.
const authorize = (b, params) => b.navigate(at(`/oauth/mcp/authorize?${new URLSearchParams(Object.entries(params).filter(([, v]) => v !== undefined))}`))

/// The parameters of a valid authorization request of `clientId`.
function request(clientId, redirect, over = {}) {
  const pk = pkce()
  return { pk, params: { response_type: 'code', client_id: clientId, redirect_uri: redirect, code_challenge: pk.challenge, code_challenge_method: 'S256', resource: names().resource, state: fresh(12), scope: SCOPE, ...over } }
}

/// Sign `acct` in through `/oauth/mcp/authorize` and the page, as `clientId`
/// to `redirect`: answers `{code, pk, redirect, b, page}`, `b` the browser,
/// the account signed in on it and remembered, and `page` the authorization
/// page (spec/OAUTH-MCP.md, "The authorization request"). On `device`, a
/// browser it is signed in on so, the page's consent alone (spec/OAUTH.md,
/// "The API").
async function signIn(acct, clientId, redirect, scope = SCOPE, device = null) {
  const { issuer } = names()
  const { pk, params } = request(clientId, redirect, { scope })
  const b = device ?? new Browser()
  const start = await authorize(b, params)
  const page = start.headers.location ? new URL(start.headers.location, cand.url).href : null
  const p = page && new URL(page)
  if (start.status !== 303 || p?.pathname !== '/oauth/authorize' || p.searchParams.get('client_id') !== clientId || !p.searchParams.get('request_uri')) {
    return broke('authorize', { client_id: clientId, redirect_uri: redirect }, '303 to /oauth/authorize with the client_id and a request_uri', { status: start.status, location: start.headers.location ?? null, text: start.text.slice(0, 200) })
  }
  const shown = await b.navigate(page)
  if (shown.status !== 200) return broke('the authorization page', { client_id: clientId }, 'the page', { status: shown.status, text: shown.text.slice(0, 200) })
  if (!device) {
    const si = await b.api(page, '/sign-in', { locale: 'en', identifier: acct.handle, password: acct.password, remember: true })
    if (si.status !== 200) return broke('sign-in', { client_id: clientId }, 'signed in', { status: si.status, body: si.json })
  }
  const c = await b.api(page, '/consent', { did: didOf(cand, acct) })
  if (c.status !== 200 || !c.json?.url) return broke('consent', { client_id: clientId, device: Boolean(device) }, 'a url to the redirect', { status: c.status, body: c.json })
  const back = await b.navigate(new URL(c.json.url, cand.url).href, { site: 'same-origin', referer: page })
  const t = target(back.headers.location)
  const want = { to: redirect, state: params.state, iss: issuer, code: true }
  const got = { to: t?.to ?? null, state: t?.params?.state ?? null, iss: t?.params?.iss ?? null, code: Boolean(t?.params?.code) }
  if (!isDeepStrictEqual(got, want)) await broke('the redirect back', { client_id: clientId, redirect_uri: redirect, device: Boolean(device) }, want, { ...got, error: t?.params?.error ?? null, status: back.status })
  return { code: t.params.code, pk, redirect, b, page }
}

/// A form POST to one of the MCP issuer's endpoints.
async function post(path, params) {
  return answer(await fetch(at(path), { method: 'POST', ...form(params) }))
}

/// The code grant at `/oauth/mcp/token` (spec/OAUTH-MCP.md, "The token
/// endpoint").
const exchange = (clientId, { code, pk, redirect }, over = {}) => post('/oauth/mcp/token', { grant_type: 'authorization_code', client_id: clientId, redirect_uri: redirect, code, code_verifier: pk.verifier, resource: names().resource, ...over })

/// A token answer held to the spec; answers its tokens (spec/OAUTH-MCP.md,
/// "The token endpoint").
async function held(what, res, acct, withRefresh) {
  const b = res.body ?? {}
  const ok = res.status === 200 && b.token_type === 'Bearer' && typeof b.access_token === 'string' && b.expires_in >= 899 && b.expires_in <= 900 && b.sub === didOf(cand, acct) && b.scope?.split(' ').includes('atproto') && b.scope.split(' ').includes('transition:generic') && (typeof b.refresh_token === 'string') === withRefresh
  if (!ok) await broke(what, {}, { status: 200, token_type: 'Bearer', expires_in: 900, sub: '<the account>', scope: SCOPE, refresh_token: withRefresh }, { status: res.status, ...b, access_token: b.access_token ? '<token>' : undefined, refresh_token: b.refresh_token ? '<token>' : undefined })
  return { access: b.access_token, refresh: b.refresh_token }
}

/// The access token no longer works at the MCP endpoint: the
/// `invalid_token` challenge (spec/OAUTH-MCP.md, "Tokens at the MCP
/// endpoint").
async function challenged(what, access) {
  const r = await toolCall('server_get_session', {}, `Bearer ${access}`)
  const c = challenge(r.challenge)
  if (r.http !== 401 || c?.error !== 'invalid_token' || c?.resource_metadata !== names().prm) await broke(`/mcp with ${what}`, {}, { http: 401, challenge: { error: 'invalid_token', resource_metadata: names().prm } }, { http: r.http, challenge: r.challenge, body: r.body })
}

/// The refresh grant at `/oauth/mcp/token` (spec/OAUTH-MCP.md, "The token
/// endpoint").
const refreshWith = (clientId, refresh) => post('/oauth/mcp/token', { grant_type: 'refresh_token', client_id: clientId, refresh_token: refresh })

/// A session signed in as the hosted apps and its code exchanged, held to
/// the spec: `{access, refresh, b, page}`, `b` the browser it signed in on.
async function session(what, acct, { scope = SCOPE, device = null } = {}) {
  const s = await signIn(acct, HOSTED, HOSTED_REDIRECT, scope, device)
  return { ...(await held(`token: code (${what})`, await exchange(HOSTED, s), acct, true)), b: s.b, page: s.page }
}

/// The access token works at the MCP endpoint: `server_get_session` is the
/// account's (spec/OAUTH-MCP.md, "Tokens at the MCP endpoint").
async function calls(what, acct, access) {
  const me = await toolCall('server_get_session', {}, `Bearer ${access}`)
  if (me.http !== 200 || me.result?.isError !== false || me.result?.structuredContent?.did !== didOf(cand, acct)) await broke(`/mcp with ${what}: server_get_session`, {}, { http: 200, did: '<the account>' }, me)
  return me
}

/// The session ended: its access token the `invalid_token` challenge at
/// `/mcp`, its refresh token `400 invalid_grant` (spec/OAUTH-MCP.md, "The
/// token endpoint", "Tokens at the MCP endpoint").
async function ended(what, s) {
  await challenged(`the access token of ${what}`, s.access)
  const r = await refreshWith(HOSTED, s.refresh)
  if (r.status !== 400 || r.body?.error !== 'invalid_grant') await broke(`token: the refresh token of ${what}`, {}, '400 invalid_grant', { status: r.status, body: r.body })
}

/// A code approved and not yet exchanged, refused: `400 invalid_grant`.
async function codeRefused(what, approval) {
  const r = await exchange(HOSTED, approval)
  if (r.status !== 400 || r.body?.error !== 'invalid_grant') await broke(`token: ${what}`, {}, '400 invalid_grant', { status: r.status, body: r.body })
}

/// An MCP session of `acct`, signed in as the hosted apps for another
/// check, as spec/OAUTH-ACCOUNT.md lists it: `{access, refresh, clientId,
/// scope, created}`, `scope` its token answer's and `created` the times
/// before and after its code grant; or null before checkMcpOAuth published
/// the clients' documents.
export async function mcpSession(what, acct) {
  if (!published) return null
  const approval = await signIn(acct, HOSTED, HOSTED_REDIRECT)
  const before = Date.now()
  const res = await exchange(HOSTED, approval)
  const after = Date.now()
  return { ...(await held(`token: code (${what})`, res, acct, true)), clientId: HOSTED, scope: res.body?.scope, created: [before, after] }
}

/// The session ended, as `ended` holds it; and a `tools/call` in Claude's
/// revision; for spec/OAUTH-ACCOUNT.md's checks.
export { ended as mcpEnded, toolCall as mcpToolCall }

/// A request of the hosted apps at the MCP issuer, the clients' documents
/// published, and its authorization page loaded on `b`, for another check
/// to sign in on there (checks/passkeys.mjs; spec/OAUTH-MCP.md, "The
/// authorization request"): `{page, pk, state, redirect}`, or null.
export async function mcpPage(b) {
  publish()
  const { pk, params } = request(HOSTED, HOSTED_REDIRECT)
  const start = await authorize(b, params)
  const page = start.headers.location ? new URL(start.headers.location, cand.url).href : null
  if (start.status !== 303 || new URL(page ?? 'x:').pathname !== '/oauth/authorize') return broke('authorize', { client_id: HOSTED }, '303 to /oauth/authorize', { status: start.status, location: start.headers.location ?? null })
  const shown = await b.navigate(page)
  if (shown.status !== 200) return broke('the authorization page', { client_id: HOSTED }, 'the page', { status: shown.status, text: shown.text.slice(0, 200) })
  return { page, pk, state: params.state, redirect: HOSTED_REDIRECT }
}

/// The redirect a consent on `req`'s page (`mcpPage`) answered with `url`,
/// followed on `b`: back to the hosted apps with the MCP issuer, the state
/// and a code; the code exchanged at `/oauth/mcp/token`, its tokens held
/// to the spec for `acct` (spec/OAUTH-MCP.md, "The token endpoint").
/// Answers `{access, refresh}`, or null.
export async function mcpRedeem(acct, b, req, url) {
  const back = await b.navigate(new URL(url, cand.url).href, { site: 'same-origin', referer: req.page })
  const t = target(back.headers.location)
  const want = { to: req.redirect, state: req.state, iss: names().issuer, code: true }
  const got = { to: t?.to ?? null, state: t?.params?.state ?? null, iss: t?.params?.iss ?? null, code: Boolean(t?.params?.code) }
  if (!isDeepStrictEqual(got, want)) return broke('the redirect back', { client_id: HOSTED }, want, { ...got, error: t?.params?.error ?? null, status: back.status })
  return held('token: code', await exchange(HOSTED, { code: t.params.code, pk: req.pk, redirect: req.redirect }), acct, true)
}

const basic = (user, password) => `Basic ${Buffer.from(`${user}:${password}`).toString('base64')}`
/// The admin's auth on each side.
const admin = (side) => (side === ref ? basic('admin', ADMIN_PASSWORD) : cand.admin)

/// The admin applies or lifts the account's takedown on both sides alike,
/// compared (spec/LIFECYCLE.md, "updateSubjectStatus").
async function takedownBoth(kind, acct, applied) {
  const nsid = 'com.atproto.admin.updateSubjectStatus'
  const send = async (side) => answer(await fetch(`${side.url}/xrpc/${nsid}`, { method: 'POST', headers: { 'content-type': 'application/json', authorization: admin(side) }, body: JSON.stringify({ subject: { $type: 'com.atproto.admin.defs#repoRef', did: didOf(side, acct) }, takedown: { applied } }) }))
  const [a, b] = await Promise.all([ref, cand].map(send))
  const [na, nb] = [normalize(ref, a, nsid), normalize(cand, b, nsid)]
  if (!isDeepStrictEqual(na, nb)) await differ(nsid, { subject: `<did:${acct.n}>`, takedown: { applied } }, na, nb)
  count(kind, a.status < 400)
}

/// activateAccount with the account's password session on both sides,
/// compared. Its `#identity` on the firehose carries the handle it has
/// (spec/LIFECYCLE.md, "The firehose").
async function activateBoth(kind, acct) {
  await both(kind, 'com.atproto.server.activateAccount', { token: acct, method: 'POST' })
  for (const side of [ref, cand]) acct.handles[side.name].push(acct.handles[side.name].at(-1))
}

/// The scope that lets an MCP session deactivate its account
/// (spec/OAUTH-SCOPES.md, "What each method needs").
const STATUS_SCOPE = `${SCOPE} account:status?action=manage`

/// A takedown ends every MCP session of the account at once, and every code
/// approved for it; lifted, they stay ended; and a lifting of an account not
/// down ends them too (spec/OAUTH-MCP.md, "Lifecycle and durability";
/// spec/LIFECYCLE.md, "OAuth sessions").
async function mcpTakedown() {
  const acct = await createAccount({ withPassword: true })
  if (!acct) return
  const s = await session('before a takedown', acct)
  await calls('a session before a takedown', acct, s.access)
  const pending = await signIn(acct, HOSTED, HOSTED_REDIRECT, SCOPE, s.b)
  await takedownBoth('updateSubjectStatus takedown (MCP sessions)', acct, true)
  await ended('a session whose account was taken down', s)
  await takedownBoth('updateSubjectStatus lifting a takedown (MCP sessions)', acct, false)
  await ended('a session whose account was taken down, the takedown lifted', s)
  await codeRefused('a code approved before a takedown, exchanged after it is lifted', pending)
  const after = await session('after a takedown is lifted', acct)
  await calls('a session after a takedown is lifted', acct, after.access)
  await takedownBoth('updateSubjectStatus lifting a takedown of an account not down (MCP sessions)', acct, false)
  await ended('a session whose account had a takedown lifted while not down', after)
  // Its password sessions ended with them, on both sides (spec/LIFECYCLE.md,
  // "updateSubjectStatus"): it carries on with new ones.
  const [a, b] = await both('createSession after a takedown is lifted', 'com.atproto.server.createSession', { body: { identifier: acct.handle, password: acct.password } })
  if (a.status === 200 && b.status === 200) {
    acct.sides.reference = { ...acct.sides.reference, token: a.body.accessJwt, refresh: a.body.refreshJwt }
    acct.sides.server = { ...acct.sides.server, token: b.body.accessJwt, refresh: b.body.refreshJwt }
  }
  count('mcp oauth: a takedown, applied and lifted', true)
}

/// Signing out of the device the session signed in on ends no session: it
/// signs the account out of that device alone (spec/OAUTH.md, "The API").
/// A deactivation by the account's password session ends no MCP session,
/// which answers as that session does, and refreshes, but ends the codes
/// approved for it; one with an MCP session's own token ends every MCP
/// session of the account, after its activation too (spec/OAUTH-MCP.md,
/// "Lifecycle and durability"; spec/LIFECYCLE.md, "OAuth sessions").
async function mcpDeactivations() {
  const acct = await createAccount({ withPassword: true })
  if (!acct) return
  let m1 = await session('before a deactivation', acct)
  const pending = await signIn(acct, HOSTED, HOSTED_REDIRECT, SCOPE, m1.b)
  const out = await m1.b.api(m1.page, '/sign-out', { did: didOf(cand, acct) })
  if (out.status !== 200 || out.json?.success !== true) await broke('sign-out on the page', {}, { status: 200, body: { success: true } }, { status: out.status, body: out.json })
  await calls('a session whose account signed out of the device it signed in on', acct, m1.access)
  count('mcp oauth: sign-out', true)

  await both('deactivateAccount with its password session (MCP sessions)', 'com.atproto.server.deactivateAccount', { token: acct, body: {} })
  const password = `Bearer ${tokenOf(cand, acct)}`
  const record = { $type: 'com.example.note', text: 'not written: the account is deactivated' }
  for (const [tool, args, whole] of [['server_check_account_status', {}, true], ['repo_create_record', { repo: didOf(cand, acct), collection: 'com.example.note', record }, false]]) {
    const view = (r) => ({ http: r.http, isError: r.result?.isError ?? null, answer: whole ? r.result?.structuredContent ?? null : r.result?.structuredContent?.error ?? null })
    const [mine, theirs] = [view(await toolCall(tool, args, `Bearer ${m1.access}`)), view(await toolCall(tool, args, password))]
    if (!isDeepStrictEqual(mine, theirs)) await broke(`${tool} with an MCP session of a deactivated account, as with its password session`, { tool }, theirs, mine)
  }
  const me = await toolCall('server_get_session', {}, `Bearer ${m1.access}`)
  const sc = me.result?.structuredContent
  if (me.result?.isError !== false || sc?.did !== didOf(cand, acct) || sc?.active !== false || sc?.status !== 'deactivated') await broke('server_get_session with a session of a deactivated account', {}, { did: '<the account>', active: false, status: 'deactivated' }, me)
  m1 = { ...m1, ...(await held('token: refresh, the account deactivated by its password session', await refreshWith(HOSTED, m1.refresh), acct, true)) }
  await calls('a session refreshed while its account is deactivated', acct, m1.access)
  await codeRefused('a code approved before a deactivation', pending)
  await activateBoth('activateAccount after a deactivation by its password session', acct)
  await calls('a session after its account is activated again', acct, m1.access)
  count('mcp oauth: a deactivation by the password session', true)

  const m2 = await session('with account:status?action=manage', acct, { scope: STATUS_SCOPE })
  const pending2 = await signIn(acct, HOSTED, HOSTED_REDIRECT, SCOPE, m2.b)
  const d = await toolCall('server_deactivate_account', {}, `Bearer ${m2.access}`)
  if (d.http !== 200 || d.result?.isError !== false) await broke('server_deactivate_account with an MCP session\'s token', { scope: STATUS_SCOPE }, 'the account deactivated', d)
  // The reference's account deactivated too, so that both stay alike.
  const r = await xrpcHttp(ref, 'com.atproto.server.deactivateAccount', { token: acct, body: {} })
  if (r.status !== 200) await fail(ref, 'deactivateAccount, as the server\'s account was through MCP', {}, 200, r)
  await ended('the session whose token deactivated its account', m2)
  await ended('a session whose account another session deactivated', m1)
  await codeRefused('a code approved before a deactivation with an MCP token', pending2)
  await activateBoth('activateAccount after a deactivation with an MCP token', acct)
  await ended('the session whose token deactivated its account, after its activation', m2)
  await ended('a session whose account another session deactivated, after its activation', m1)
  count('mcp oauth: a deactivation with an MCP token', true)
}

/// deleteAccount ends every MCP session of the account (spec/OAUTH-MCP.md,
/// "Lifecycle and durability"; spec/LIFECYCLE.md, "deleteAccount", "OAuth
/// sessions"). The account deleted is the run's no longer.
async function mcpDeletion() {
  const acct = await createAccount({ withPassword: true })
  if (!acct) return
  const s = await session('before deleteAccount', acct)
  await both('requestAccountDelete (MCP sessions)', 'com.atproto.server.requestAccountDelete', { token: acct, method: 'POST' })
  const sent = await checkMail('requestAccountDelete (MCP sessions)', { account: `<did:${acct.n}>` })
  const token = (side) => sent[side.name].filter((m) => m.to === acct.email.toLowerCase() && m.kind === 'deleteAccount').at(-1)?.token
  if (!token(cand)) return void (await broke('requestAccountDelete', {}, 'a deleteAccount email', sent.server))
  const [a, b] = await both('deleteAccount (MCP sessions)', 'com.atproto.server.deleteAccount', (side) => ({ body: { did: didOf(side, acct), password: acct.password, token: token(side) } }))
  // It is the last account made, so no other's number is given again.
  if (a.status === 200 && b.status === 200) accounts.splice(accounts.indexOf(acct), 1)
  await ended('a session whose account was deleted', s)
  count('mcp oauth: deleteAccount', true)
}

/// Whether checkMcpOAuth published the clients' documents, which the
/// sessions made before a restart sign in with.
let published = false
/// What `mcpBeforeCrash` made, for `mcpAfterCrash`.
let beforeRestart = null

/// Before the server is killed, on an account with a password and without
/// the email factor, as the hosted apps: a session refreshed, the access
/// token it replaced, a code approved and not exchanged, and a session
/// ended by revocation or by its replaced refresh token sent again; all on
/// one device, the account signed in on it (spec/OAUTH-MCP.md, "Lifecycle
/// and durability"; spec/OAUTH.md, "Durability").
export async function mcpBeforeCrash() {
  beforeRestart = null
  const some = accounts.filter((a) => a.password)
  if (!published || !some.length) return
  const acct = pick(some)
  const now = await xrpcHttp(cand, 'com.atproto.server.getSession', { token: acct })
  if (now.status !== 200 || now.body?.emailAuthFactor === true) return
  const first = await session('before a restart', acct)
  const live = await held('token: refresh, before a restart', await refreshWith(HOSTED, first.refresh), acct, true)
  const code = await signIn(acct, HOSTED, HOSTED_REDIRECT, SCOPE, first.b)
  const how = pick(['revoked', 'ended by a replay'])
  let gone = await session(`to be ${how} before a restart`, acct, { device: first.b })
  if (how === 'revoked') {
    const r = await post('/oauth/mcp/revoke', { client_id: HOSTED, token: gone.refresh })
    if (r.status !== 200) await broke('revoke, before a restart', {}, 200, { status: r.status, body: r.body })
  } else {
    const replaced = gone.refresh
    gone = await held('token: refresh, before a replay', await refreshWith(HOSTED, replaced), acct, true)
    const replay = await refreshWith(HOSTED, replaced)
    if (replay.status !== 400 || replay.body?.error !== 'invalid_grant') await broke('a replaced refresh token, before a restart', {}, '400 invalid_grant', { status: replay.status, body: replay.body })
  }
  beforeRestart = { acct, device: first.b, replaced: first.access, live, code, how, gone }
}

/// After the restart, what was made before it is as it was: the replaced
/// access token challenged, the refreshed session calling a tool and
/// refreshing, the code exchanged, the ended session still ended, and the
/// account still signed in on the device, which consents alone
/// (spec/OAUTH-MCP.md, "Lifecycle and durability"; spec/OAUTH.md,
/// "Durability").
export async function mcpAfterCrash() {
  const s = beforeRestart
  beforeRestart = null
  if (!s) return
  const { acct } = s
  await challenged('an access token replaced before a restart', s.replaced)
  await calls('a session refreshed before a restart', acct, s.live.access)
  await held('token: refresh, after a restart', await refreshWith(HOSTED, s.live.refresh), acct, true)
  const fromCode = await held('token: code approved before a restart', await exchange(HOSTED, s.code), acct, true)
  await calls('a session from a code approved before a restart', acct, fromCode.access)
  await ended(`a session ${s.how} before a restart`, s.gone)
  const again = await session('on a device signed in on before a restart', acct, { device: s.device })
  await calls('a session consented to on a device signed in on before a restart', acct, again.access)
  count('mcp oauth: sessions across a restart', true)
}

/// The authorization request with one thing wrong after its client and
/// redirect URI: a redirect with the error, `iss` and `state`
/// (spec/OAUTH-MCP.md, "The authorization request").
async function refusedByRedirect(name, over, error) {
  const { params } = request(HOSTED, HOSTED_REDIRECT, over)
  const res = await authorize(new Browser(), params)
  const t = target(res.headers.location)
  const want = { status: 303, to: HOSTED_REDIRECT, error, iss: names().issuer, state: params.state }
  const got = { status: res.status, to: t?.to ?? null, error: t?.params?.error ?? null, iss: t?.params?.iss ?? null, state: t?.params?.state ?? null }
  if (!isDeepStrictEqual(got, want)) await broke(`authorize: ${name}`, over, want, got)
  count(`mcp oauth: authorize refused, ${name}`, false)
}

/// The authorization request with its client or redirect URI wrong: a 400
/// page, no redirect (spec/OAUTH-MCP.md, "Clients", "The authorization
/// request").
async function refusedByPage(name, clientId, redirect) {
  const { params } = request(clientId, redirect)
  const res = await authorize(new Browser(), params)
  if (res.status !== 400 || res.headers.location) await broke(`authorize: ${name}`, { client_id: clientId, redirect_uri: redirect }, 'a 400 error page, no redirect', { status: res.status, location: res.headers.location ?? null })
  count(`mcp oauth: authorize refused, ${name}`, false)
}

export async function checkMcpOAuth() {
  const acct = accounts.find((a) => a.password)
  if (!acct) return
  publish()
  published = true
  const { origin, resource, issuer, prm } = names()

  // The challenge, and a tool that needs no account (spec/OAUTH-MCP.md,
  // "Tokens at the MCP endpoint").
  const anon = await toolCall('repo_create_record', { repo: didOf(cand, acct), collection: 'com.example.note', record: { $type: 'com.example.note', text: 'x' } })
  const c = challenge(anon.challenge)
  if (anon.http !== 401 || !isDeepStrictEqual(c, { resource_metadata: prm, scope: SCOPE }) || anon.body?.error !== 'invalid_token') await broke('a tool needing an account, no token', {}, { http: 401, challenge: { resource_metadata: prm, scope: SCOPE }, body: { error: 'invalid_token' } }, anon)
  const open = await toolCall('server_describe_server', {})
  if (open.http !== 200 || open.result?.isError) await broke('a tool needing no account, no token', {}, 'its answer', open)
  const garbage = await toolCall('server_get_session', {}, 'Bearer not-a-token')
  if (garbage.http !== 200 || garbage.result?.structuredContent?.error !== 'InvalidToken') await broke('a token the server did not give out', {}, 'a tool error, InvalidToken, as XRPC answers it', garbage)
  count('mcp oauth: challenge', true)

  // The metadata (spec/OAUTH-MCP.md, "Metadata").
  const meta = await answer(await fetch(at('/.well-known/oauth-protected-resource/mcp')))
  const wantMeta = { resource, authorization_servers: [issuer], scopes_supported: ['atproto', 'transition:generic'], bearer_methods_supported: ['header'], resource_documentation: 'https://atproto.com' }
  if (meta.status !== 200 || meta.headers['access-control-allow-origin'] !== '*' || !isDeepStrictEqual(meta.body, wantMeta)) await broke('protected resource metadata of /mcp', {}, wantMeta, { status: meta.status, cors: meta.headers['access-control-allow-origin'] ?? null, body: meta.body })
  const as = await answer(await fetch(at('/.well-known/oauth-authorization-server/oauth/mcp')))
  const atproto = await answer(await fetch(at('/.well-known/oauth-authorization-server')))
  const wantAs = {
    issuer, authorization_endpoint: `${issuer}/authorize`, token_endpoint: `${issuer}/token`, revocation_endpoint: `${issuer}/revoke`,
    scopes_supported: atproto.body?.scopes_supported, response_types_supported: ['code'], response_modes_supported: ['query'],
    grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'], token_endpoint_auth_methods_supported: ['none'],
    client_id_metadata_document_supported: true, authorization_response_iss_parameter_supported: true, protected_resources: [resource],
  }
  if (as.status !== 200 || !isDeepStrictEqual(as.body, wantAs)) await broke('the MCP issuer\'s metadata', {}, wantAs, { status: as.status, body: as.body })
  count('mcp oauth: metadata', true)

  // Signed in as the hosted apps; the token at the MCP endpoint
  // (spec/OAUTH-MCP.md, "The token endpoint", "Tokens at the MCP endpoint").
  const hosted = await held('token: code (hosted)', await exchange(HOSTED, await signIn(acct, HOSTED, HOSTED_REDIRECT)), acct, true)
  const bearer = `Bearer ${hosted.access}`
  const me = await toolCall('server_get_session', {}, bearer)
  if (me.result?.isError !== false || me.result?.structuredContent?.did !== didOf(cand, acct)) await broke('/mcp with the token: server_get_session', {}, { did: '<the account>' }, me)
  const rkey = `mcp-${nextBatch()}`
  const record = { $type: 'com.example.note', text: 'written through MCP with an MCP token' }
  const put = await toolCall('repo_put_record', { collection: 'com.example.note', rkey, record }, bearer)
  if (put.result?.isError !== false) await broke('/mcp with the token: repo_put_record', { rkey }, 'the record written', put)
  else {
    const read = await xrpcHttp(cand, 'com.atproto.repo.getRecord', { params: { repo: didOf(cand, acct), collection: 'com.example.note', rkey } })
    if (!isDeepStrictEqual(read.body?.value, record)) await broke('getRecord of what the MCP token wrote', { rkey }, record, read.body)
    // The same write on the reference, so the repositories still agree.
    const a = await xrpc(ref, 'com.atproto.repo.putRecord', { body: { repo: acct.handle, collection: 'com.example.note', rkey, record }, token: acct })
    noteWrite(acct, 'com.example.note', rkey, a)
    noteCommit(ref, acct, a)
    noteCommit(cand, acct, { body: put.result.structuredContent })
  }
  count('mcp oauth: tools with the token', true)

  // The token elsewhere (spec/OAUTH-MCP.md, "The token endpoint", "Tokens at
  // the MCP endpoint").
  const asBearer = await xrpcHttp(cand, 'com.atproto.server.getSession', { token: hosted.access })
  if (asBearer.status !== 400 || asBearer.body?.error !== 'InvalidToken') await broke('the token on XRPC, as Bearer', {}, '400 InvalidToken', asBearer)
  const asDpop = await answer(await fetch(at('/xrpc/com.atproto.server.getSession'), { headers: { authorization: `DPoP ${hosted.access}` } }))
  if (asDpop.status !== 401 || asDpop.body?.error !== 'invalid_token') await broke('the token on XRPC, as DPoP', {}, '401 invalid_token', { status: asDpop.status, body: asDpop.body })
  const atAtproto = await post('/oauth/token', { grant_type: 'refresh_token', client_id: HOSTED, refresh_token: hosted.refresh })
  if (atAtproto.status === 200) await broke('the refresh token at /oauth/token', {}, 'refused', atAtproto.status)
  const atproto2 = await approved(acct)
  if (atproto2) {
    const r = await post('/oauth/mcp/token', { grant_type: 'authorization_code', client_id: atproto2.req.clientId, redirect_uri: atproto2.req.redirect, code: atproto2.codes.server, code_verifier: atproto2.req.pk.verifier, resource })
    if (r.status === 200) await broke('an atproto code at /oauth/mcp/token', {}, 'refused', r.status)
  }
  count('mcp oauth: the token refused elsewhere', true)

  // Refresh: new tokens, the old access token challenged; the old refresh
  // token refused, ending the session (spec/OAUTH-MCP.md, "The token
  // endpoint").
  const refreshed = await held('token: refresh', await refreshWith(HOSTED, hosted.refresh), acct, true)
  await challenged('an access token replaced', hosted.access)
  const works = await toolCall('server_get_session', {}, `Bearer ${refreshed.access}`)
  if (works.result?.isError !== false) await broke('/mcp with the refreshed token', {}, 'the session', works)
  const again = await refreshWith(HOSTED, hosted.refresh)
  if (again.status !== 400 || again.body?.error !== 'invalid_grant') await broke('a replaced refresh token', {}, '400 invalid_grant', { status: again.status, body: again.body })
  await challenged('the token of a session ended', refreshed.access)
  count('mcp oauth: refresh', true)

  // Claude Code: a localhost redirect on a port the document does not name
  // (spec/OAUTH-MCP.md, "Clients"); then revoked (spec/OAUTH-MCP.md,
  // "Revocation").
  const native = await signIn(acct, CODE, `http://localhost:${49152 + below(1000)}/callback`)
  const wrongVerifier = await exchange(CODE, native, { code_verifier: pkce().verifier })
  if (wrongVerifier.status !== 400 || wrongVerifier.body?.error !== 'invalid_grant') await broke('token: a wrong code_verifier', {}, '400 invalid_grant', { status: wrongVerifier.status, body: wrongVerifier.body })
  const code2 = await held('token: code (Claude Code)', await exchange(CODE, await signIn(acct, CODE, 'http://localhost:51234/callback')), acct, true)
  const revoked = await post('/oauth/mcp/revoke', { client_id: CODE, token: code2.refresh })
  if (revoked.status !== 200) await broke('revoke', {}, 200, { status: revoked.status, body: revoked.body })
  await challenged('the token of a session revoked', code2.access)
  count('mcp oauth: Claude Code, and revocation', true)

  // A client without the refresh grant: no refresh token, and no refresh
  // (spec/OAUTH-MCP.md, "Clients", "The token endpoint").
  await held('token: code (no refresh grant)', await exchange(NO_REFRESH, await signIn(acct, NO_REFRESH, HOSTED_REDIRECT)), acct, false)
  const noRefresh = await post('/oauth/mcp/token', { grant_type: 'refresh_token', client_id: NO_REFRESH, refresh_token: 'any' })
  if (noRefresh.status !== 400 || noRefresh.body?.error !== 'unauthorized_client') await broke('a refresh grant from a client without it', { client_id: NO_REFRESH }, '400 unauthorized_client', { status: noRefresh.status, body: noRefresh.body })
  count('mcp oauth: a client without the refresh grant', true)

  // Step-up: a narrow token refused for its scope is a 403 naming all it
  // needs; signed in again with that, the call works. A method no scope
  // grants stays a tool error (spec/OAUTH-MCP.md, "Tokens at the MCP
  // endpoint").
  const NARROW = 'atproto repo:com.example.other'
  const narrowAnswer = await exchange(HOSTED, await signIn(acct, HOSTED, HOSTED_REDIRECT, NARROW))
  const narrow = narrowAnswer.body?.access_token
  if (narrowAnswer.status !== 200 || narrowAnswer.body?.scope !== NARROW) await broke('token: code (a narrow scope)', { scope: NARROW }, { status: 200, scope: NARROW }, { status: narrowAnswer.status, scope: narrowAnswer.body?.scope ?? null })
  const stepRkey = `mcp-${nextBatch()}`
  const stepRecord = { $type: 'com.example.note', text: 'written after a step-up' }
  const refused = await toolCall('repo_put_record', { collection: 'com.example.note', rkey: stepRkey, record: stepRecord }, `Bearer ${narrow}`)
  const wantScope = `${NARROW} repo:com.example.note?action=create repo:com.example.note?action=update`
  const sc = challenge(refused.challenge)
  const wantChallenge = { error: 'insufficient_scope', scope: wantScope, resource_metadata: prm }
  const gotChallenge = sc && { error: sc.error, scope: sc.scope, resource_metadata: sc.resource_metadata }
  if (refused.http !== 403 || !isDeepStrictEqual(gotChallenge, wantChallenge) || refused.body?.error !== 'insufficient_scope') await broke('a call the scope refuses', { scope: NARROW, tool: 'repo_put_record' }, { http: 403, challenge: wantChallenge, body: { error: 'insufficient_scope' } }, { http: refused.http, challenge: refused.challenge, body: refused.body })
  const appPassword = await toolCall('server_create_app_password', { name: `mcp-${nextBatch()}` }, `Bearer ${narrow}`)
  if (appPassword.http !== 200 || appPassword.result?.isError !== true) await broke('a method no OAuth token may call', { tool: 'server_create_app_password' }, 'a tool error, not a challenge', { http: appPassword.http, challenge: appPassword.challenge, body: appPassword.body })
  const wider = await exchange(HOSTED, await signIn(acct, HOSTED, HOSTED_REDIRECT, wantScope))
  const stepped = await toolCall('repo_put_record', { collection: 'com.example.note', rkey: stepRkey, record: stepRecord }, `Bearer ${wider.body?.access_token}`)
  if (stepped.result?.isError !== false) await broke('the call after a step-up', { scope: wantScope }, 'the record written', stepped)
  else {
    const a = await xrpc(ref, 'com.atproto.repo.putRecord', { body: { repo: acct.handle, collection: 'com.example.note', rkey: stepRkey, record: stepRecord }, token: acct })
    noteWrite(acct, 'com.example.note', stepRkey, a)
    noteCommit(ref, acct, a)
    noteCommit(cand, acct, { body: stepped.result.structuredContent })
  }
  count('mcp oauth: step-up', true)

  // What the MCP issuer refuses (spec/OAUTH-MCP.md, "Clients", "The
  // authorization request").
  await refusedByRedirect('no resource', { resource: undefined }, 'invalid_target')
  await refusedByRedirect('another resource', { resource: `${origin}/elsewhere` }, 'invalid_target')
  await refusedByRedirect('no PKCE', { code_challenge: undefined, code_challenge_method: undefined }, 'invalid_request')
  await refusedByRedirect('PKCE plain', { code_challenge_method: 'plain' }, 'invalid_request')
  await refusedByRedirect('a scope without atproto', { scope: 'transition:generic' }, 'invalid_scope')
  await refusedByPage('a document naming another client_id', OTHER_ID, HOSTED_REDIRECT)
  await refusedByPage('a document with no token_endpoint_auth_method', NO_AUTH_METHOD, HOSTED_REDIRECT)
  await refusedByPage('a redirect URI the document does not name', HOSTED, `${HOST}/elsewhere`)

  // MCP sessions through their accounts' changes. A deletion leaves its
  // account's events on a live firehose and takes them out of a replay,
  // which the firehose's checks here do not model: with --firehose, no
  // account is deleted.
  await mcpTakedown()
  await mcpDeactivations()
  if (!FIREHOSE) await mcpDeletion()
}