chadtmiller.com/monolith
An atproto PDS
0
0
// The account's own OAuth sessions and devices (spec/OAUTH-ACCOUNT.md), on
// the server alone: the reference serves none of these routes, and its
// account pages' API is a browser's, with its cookies. Each check makes
// accounts of its own, on both sides alike, and signs them in through
// OAuth's flow on the server alone, as checks/oauth-limits.mjs's
// `serverSession` does, each session with a loopback client of its own and
// each browser with a `User-Agent` of its own; with --commands, through
// spec/OAUTH-MCP.md's flow too (checks/oauth-mcp.mjs). The routes' auth and
// what they refuse; the sessions listed and ended; the devices listed and
// signed out of; the routes' tools and commands, called as the routes are;
// and, in a run with crashes, what was ended and signed out of before a
// restart, after it.
import { isDeepStrictEqual } from 'node:util'
import { COMMANDS, STORE } from '../lib/args.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { below, chance, pick } from '../lib/random.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts, didOf, nextBatch, tokenOf } from '../lib/state.mjs'
import { normalize, shown, xrpc, xrpcHttp } from '../lib/xrpc.mjs'
import { Browser, Dpop, answer, form, fresh, newKey, pkce, target } from '../lib/oauth.mjs'
import { issuer, own, pageApi } from '../lib/server.mjs'
import { MCP_LEGACY, MCP_VERSION, OAUTH_ROUTES, viaRouteCommand, viaRouteTool } from '../lib/via.mjs'
import { createAccount } from './accounts.mjs'
import { mcpEnded, mcpSession, mcpToolCall } from './oauth-mcp.mjs'
const CREATE_AP = 'com.atproto.server.createAppPassword'
/// The routes are Monolith's own (spec/OAUTH-ACCOUNT.md), and the checks
/// sign in through the reference's page API.
const able = () => own() && pageApi()
const SESSIONS = '_oauthSessions'
const REVOKE_SESSION = '_oauthRevokeSession'
const DEVICES = '_oauthDevices'
const REVOKE_DEVICE = '_oauthRevokeDevice'
const ROUTES = [SESSIONS, REVOKE_SESSION, DEVICES, REVOKE_DEVICE]
/// Each route's section of spec/OAUTH-ACCOUNT.md, cited as it is.
const CITES = {
[SESSIONS]: 'spec/OAUTH-ACCOUNT.md, "_oauthSessions"',
[REVOKE_SESSION]: 'spec/OAUTH-ACCOUNT.md, "_oauthRevokeSession"',
[DEVICES]: 'spec/OAUTH-ACCOUNT.md, "_oauthDevices"',
[REVOKE_DEVICE]: 'spec/OAUTH-ACCOUNT.md, "_oauthRevokeDevice"',
}
const REVOKES = [REVOKE_SESSION, REVOKE_DEVICE]
/// A route's HTTP method, and the other one (spec/OAUTH-ACCOUNT.md).
const methodOf = (route) => (REVOKES.includes(route) ? 'POST' : 'GET')
const otherMethod = (route) => (methodOf(route) === 'GET' ? 'POST' : 'GET')
const JSON_TYPE = 'application/json; charset=utf-8'
const FORBIDDEN = { status: 403, error: 'Forbidden', message: 'OAuth credentials are not supported for this endpoint' }
const INVALID_TOKEN = { status: 400, error: 'InvalidToken' }
const INVALID_REQUEST = { status: 400, error: 'InvalidRequest' }
const TWO_WEEKS = 14 * 86400 * 1000
/// A datetime in UTC with milliseconds (spec/OAUTH-ACCOUNT.md,
/// "_oauthSessions").
const TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/
/// The server failing what `cite` cites of spec/OAUTH-ACCOUNT.md.
const broke = (cite, what, request, want, got) => differ(`the server's ${what}`, request, want, got, cite)
/// The server failing a step of OAuth's flow these checks take.
const flowBroke = (what, request, want, got) => differ(`the server's ${what}`, request, want, got, 'spec/OAUTH.md, signing in for spec/OAUTH-ACCOUNT.md\'s checks')
const bearer = (token) => `Bearer ${token}`
const who = (acct) => `<did:${acct.n}>`
const iso = ([lo, hi]) => `${new Date(lo).toISOString()} to ${new Date(hi).toISOString()}`
/// Whether `t` is a datetime within a second of the window `[lo, hi]`.
const near = (t, [lo, hi]) => typeof t === 'string' && TIME.test(t) && Date.parse(t) >= lo - 1000 && Date.parse(t) <= hi + 1000
/// The latest `at` first, then by `id`.
const newestFirst = (at) => (a, b) => (a[at] < b[at] ? 1 : a[at] > b[at] ? -1 : a.id < b.id ? -1 : a.id > b.id ? 1 : 0)
/// An id of the same form as `id`, lower case hex, that is not it.
const unlike = (id) => `${id.slice(0, -1)}${id.endsWith('a') ? 'b' : 'a'}`
/// An id as the routes give them: lower case hex (spec/OAUTH-ACCOUNT.md,
/// "_oauthSessions", "_oauthDevices").
const HEX = /^[0-9a-f]+$/
// ---------------------------------------------------------------- clients
let serial = 0
const SCOPES = ['atproto transition:generic', 'atproto transition:generic transition:email']
/// A loopback client of its own, its one redirect URI on a port of its
/// own, so that its `client_id` names one session (spec/OAUTH.md,
/// "Clients").
function newClient() {
serial += 1
const scope = pick(SCOPES)
const redirect = `http://127.0.0.1:${10000 + (serial % 50000)}/callback`
return { scope, redirect, clientId: `http://localhost?${new URLSearchParams({ scope, redirect_uri: redirect })}` }
}
/// A browser of its own: its `User-Agent`, of its own, sometimes past 256
/// characters, and an `X-Forwarded-For` naming its client address, as a
/// proxy before the server would (spec/LIMITS.md, "Rate limits"), sent with
/// each of its requests; by account number, when it last signed in there
/// with `remember`, and the device's `id` as the account's list gave it.
function newDevice() {
serial += 1
const ua = chance(0.3) ? `Mozilla/5.0 (harness device ${serial}; ${'x'.repeat(250 + below(50))})` : `harness-device/${serial} (${pick(['Macintosh', 'X11; Linux', 'iPhone'])})`
const ip = `203.0.113.${1 + below(254)}`
return { b: new Browser(), ua, ip, headers: { 'user-agent': ua, 'x-forwarded-for': ip }, signedIn: {}, ids: {} }
}
// ------------------------------------------------------------------- flow
/// A request of `client` PAR'd on the server, and its authorization page
/// loaded on `device` (spec/OAUTH.md, "Pushed authorization requests", "The
/// authorization page"): `{client, dpop, pk, page, shown}`, or null.
async function request(client, device) {
const dpop = new Dpop(await newKey())
const pk = pkce()
const p = form({ client_id: client.clientId, response_type: 'code', redirect_uri: client.redirect, scope: client.scope, state: fresh(), code_challenge: pk.challenge, code_challenge_method: 'S256' })
const parred = await dpop.send(`${issuer(cand)}/oauth/par`, { method: 'POST', ...p })
if (parred.status !== 201) return void (await flowBroke('PAR', { client_id: client.clientId }, 201, { status: parred.status, body: parred.body }))
const page = `${issuer(cand)}/oauth/authorize?${new URLSearchParams({ client_id: client.clientId, request_uri: parred.body.request_uri })}`
const shown = await device.b.navigate(page, { headers: device.headers })
if (shown.status !== 200) return void (await flowBroke('authorization page', { client_id: client.clientId }, 200, { status: shown.status, text: shown.text.slice(0, 200) }))
return { client, dpop, pk, page, shown }
}
/// `acct` signs in on the page of `req` on `device`, with `remember` (left
/// out when undefined), by its DID (spec/OAUTH.md, "The API"). Notes when
/// the device has it signed in. Answers the API's answer.
async function signIn(acct, device, req, remember) {
const before = Date.now()
const si = await device.b.api(req.page, '/sign-in', { locale: 'en', identifier: didOf(cand, acct), password: acct.password, ...(remember === undefined ? {} : { remember }) }, { headers: device.headers })
const after = Date.now()
if (si.status !== 200) return void (await flowBroke('sign-in', { account: who(acct), remember }, 200, { status: si.status, body: si.json }))
if (remember === true || (remember === undefined && device.signedIn[acct.n])) device.signedIn[acct.n] = [before, after]
else delete device.signedIn[acct.n]
return si.json
}
/// Consent for `acct` on the page of `req` on `device` (with `ephemeral`,
/// its sign-in's token, if it is not signed in there), the redirect, and
/// the code grant (spec/OAUTH.md, "The API", "The redirect", "The token
/// endpoint"). Answers the session: `{clientId, issuer, scope, created,
/// updated, dpop, access, refresh, code, old}`, `created` and `updated` the
/// times before and after its code grant, and `old` its replaced tokens;
/// or null.
async function approve(acct, device, req, ephemeral) {
const shown = { client_id: req.client.clientId, account: who(acct) }
const c = await device.b.api(req.page, '/consent', { did: didOf(cand, acct) }, { headers: device.headers, bearer: ephemeral })
const url = c.json?.url
const back = typeof url === 'string' ? await device.b.navigate(new URL(url, issuer(cand)).href, { site: 'same-origin', referer: req.page, headers: device.headers }) : null
const code = target(back?.headers?.location)?.params?.code
if (c.status !== 200 || !code) return void (await flowBroke('consent and its redirect', shown, 'a code', { status: c.status, body: c.json, location: back?.headers?.location ?? null }))
const before = Date.now()
const t = await req.dpop.send(`${issuer(cand)}/oauth/token`, { method: 'POST', ...form({ grant_type: 'authorization_code', client_id: req.client.clientId, redirect_uri: req.client.redirect, code, code_verifier: req.pk.verifier }) })
const created = [before, Date.now()]
if (t.status !== 200) return void (await flowBroke('token: code', shown, 200, { status: t.status, body: t.body }))
return { clientId: req.client.clientId, issuer: 'atproto', scope: t.body.scope, created, updated: created, dpop: req.dpop, access: t.body.access_token, refresh: t.body.refresh_token, code, old: [] }
}
/// A session of `acct` through `device`, with a client of its own: its
/// request and page, a sign-in with `remember` unless the account is signed
/// in there, consent and the code grant. Answers it, or null.
async function session(acct, device, { remember = true } = {}) {
const req = await request(newClient(), device)
if (!req) return null
let ephemeral
if (!device.signedIn[acct.n]) {
const si = await signIn(acct, device, req, remember)
if (!si) return null
ephemeral = si.ephemeralToken
}
return approve(acct, device, req, ephemeral)
}
/// The refresh grant with the session's refresh token: its tokens, scope
/// and `updated` from the answer (spec/OAUTH.md, "The token endpoint").
async function refresh(s) {
const before = Date.now()
const r = await s.dpop.send(`${issuer(cand)}/oauth/token`, { method: 'POST', ...form({ grant_type: 'refresh_token', client_id: s.clientId, refresh_token: s.refresh }) })
const updated = [before, Date.now()]
if (r.status !== 200) return void (await flowBroke('token: refresh', { client_id: s.clientId }, 200, { status: r.status, body: r.body }))
s.old.push({ access: s.access, refresh: s.refresh })
Object.assign(s, { access: r.body.access_token, refresh: r.body.refresh_token, scope: r.body.scope, updated })
}
/// getSession with the session's access token, as DPoP with its proof
/// (spec/OAUTH.md, "OAuth tokens on XRPC").
const getSession = (s) => s.dpop.send(`${issuer(cand)}/xrpc/com.atproto.server.getSession`, { accessToken: s.access })
/// The session works: getSession answers its account.
async function works(cite, what, acct, s) {
const r = await getSession(s)
if (r.status !== 200 || r.body?.did !== didOf(cand, acct)) await broke(cite, `getSession with ${what}`, { client_id: s.clientId, account: who(acct) }, { status: 200, did: who(acct) }, { status: r.status, body: r.body })
}
/// The session ended: getSession with its access token `401
/// invalid_token`, and the refresh grant with its refresh token, current
/// and replaced, `400 invalid_grant` (spec/OAUTH-ACCOUNT.md,
/// "_oauthRevokeSession").
async function ended(cite, what, s) {
const r = await getSession(s)
if (r.status !== 401 || r.body?.error !== 'invalid_token') await broke(cite, `getSession with ${what}`, { client_id: s.clientId }, { status: 401, error: 'invalid_token' }, { status: r.status, body: r.body })
for (const [which, token] of [['its refresh token', s.refresh], ...(s.old.length ? [['its replaced refresh token', s.old.at(-1).refresh]] : [])]) {
const t = await s.dpop.send(`${issuer(cand)}/oauth/token`, { method: 'POST', ...form({ grant_type: 'refresh_token', client_id: s.clientId, refresh_token: token }) })
if (t.status !== 400 || t.body?.error !== 'invalid_grant') await broke(cite, `token: refresh with ${which}, of ${what}`, { client_id: s.clientId }, { status: 400, error: 'invalid_grant' }, { status: t.status, body: t.body })
}
}
/// A session of `acct` made with an app password of its own, made on both
/// sides alike so that their app passwords stay the same: its access token
/// on the server (spec/SESSIONS.md), or null.
async function appPasswordToken(acct) {
const name = `oauth-account-${nextBatch()}`
const request = { token: acct, body: { name } }
const [a, b] = await Promise.all([xrpc(ref, CREATE_AP, request), xrpc(cand, CREATE_AP, request)])
// The password and createdAt differ; their form is SESSIONS.md's, checked there.
const masked = (side, res) => {
const n = normalize(side, res, CREATE_AP)
return n.status === 200 ? { ...n, body: { ...n.body, password: '<password>', createdAt: '<createdAt>' } } : n
}
const [na, nb] = [masked(ref, a), masked(cand, b)]
if (!isDeepStrictEqual(na, nb)) await differ(CREATE_AP, shown(request), na, nb)
count('createAppPassword (for spec/OAUTH-ACCOUNT.md)', a.status < 400)
if (b.status !== 200) return null
const s = await xrpcHttp(cand, 'com.atproto.server.createSession', { body: { identifier: didOf(cand, acct), password: b.body.password } })
if (s.status !== 200) return void (await flowBroke('createSession with an app password', { account: who(acct) }, 200, s))
return s.body.accessJwt
}
/// Two accounts of their own, with passwords, on both sides alike; or null.
async function twoAccounts() {
const a = await createAccount({ withPassword: true })
const b = a && (await createAccount({ withPassword: true }))
return b ? [a, b] : null
}
// ----------------------------------------------------------------- routes
/// A call of `route` on the server: by its method, or `method`; with
/// `auth`'s `authorization` as the whole header, or its OAuth session's
/// access token as DPoP with a proof; `body` sent as it is, with `type` as
/// its Content-Type (JSON's when there is a body); `query` after the path.
/// Answers its status, Content-Type and body.
async function call(route, { auth = {}, method = methodOf(route), body, type = body === undefined ? undefined : 'application/json', query = '' } = {}) {
const headers = type ? { 'content-type': type } : {}
if (auth.oauth) {
const r = await auth.oauth.dpop.send(`${issuer(cand)}/xrpc/${route}${query}`, { method, headers, body, accessToken: auth.oauth.access })
return { status: r.status, type: r.headers['content-type'] ?? null, body: r.body }
}
if (auth.authorization) headers.authorization = auth.authorization
try {
const r = await answer(await fetch(`${cand.url}/xrpc/${route}${query}`, { method, headers, body }))
return { status: r.status, type: r.headers['content-type'] ?? null, body: r.body }
} catch (err) {
return { status: 0, type: null, body: { error: `request failed: ${err.message}` } }
}
}
/// The account's password session, as the routes take it.
const password = (acct) => ({ authorization: bearer(tokenOf(cand, acct)) })
/// An answer as the auth and request checks hold it.
const refusal = (res, want) => ({ status: res.status, error: res.body?.error ?? null, ...(want.message ? { message: res.body?.message ?? null } : {}) })
/// `_oauthRevokeSession` or `_oauthRevokeDevice` of `id` with the
/// account's password session, and other properties in `extra`: `200 {}`
/// (spec/OAUTH-ACCOUNT.md, "Requests").
async function revoke(route, acct, id, what, extra = {}) {
const input = { id, ...extra }
const res = await call(route, { auth: password(acct), body: JSON.stringify(input) })
if (res.status !== 200 || res.type !== JSON_TYPE || !isDeepStrictEqual(res.body, {})) await broke(CITES[route], `${route} of ${what}`, { account: who(acct), input }, { status: 200, type: JSON_TYPE, body: {} }, res)
}
/// A list route's entries for `acct`, with its password session, held to
/// its answer's form (spec/OAUTH-ACCOUNT.md, "Requests").
async function listOf(route, acct, what) {
const key = route === SESSIONS ? 'sessions' : 'devices'
const res = await call(route, { auth: password(acct) })
if (res.status !== 200 || res.type !== JSON_TYPE || !Array.isArray(res.body?.[key]) || Object.keys(res.body).length !== 1) await broke(CITES[route], `${route} ${what}`, { account: who(acct) }, { status: 200, type: JSON_TYPE, body: { [key]: '[…]' } }, res)
return res.body?.[key] ?? []
}
const SESSION_KEYS = ['clientId', 'createdAt', 'expiresAt', 'id', 'issuer', 'scope', 'updatedAt']
/// `_oauthSessions` of `acct` held to the sessions the harness made: with
/// `exact`, those of `want` and no other, else those of `want` among
/// others; none of `gone`. Each with its client, issuer, scope as its last
/// token answer gave it, `createdAt` within a second of its code grant,
/// `updatedAt` of its last refresh (its `createdAt` until one), `expiresAt`
/// two weeks after `createdAt`, and an `id` the same as before, none of
/// its tokens or its code. The latest `createdAt` first, then by `id`
/// (spec/OAUTH-ACCOUNT.md, "_oauthSessions"). Notes each session's `id`.
async function checkSessions(what, acct, want, { exact = true, gone = [] } = {}) {
const request = { account: who(acct), at: what }
const ss = await listOf(SESSIONS, acct, what)
for (const x of ss) if (!isDeepStrictEqual(Object.keys(x ?? {}).sort(), SESSION_KEYS) || typeof x.id !== 'string' || !HEX.test(x.id)) await broke('spec/OAUTH-ACCOUNT.md, "_oauthSessions"', `${SESSIONS} ${what}`, request, `each session {${SESSION_KEYS.join(', ')}}, its id lower case hex`, x)
const order = [...ss].sort(newestFirst('createdAt')).map((x) => x.id)
if (!isDeepStrictEqual(ss.map((x) => x.id), order)) await broke('spec/OAUTH-ACCOUNT.md, "_oauthSessions"', `${SESSIONS} ${what}`, request, 'the latest createdAt first, then by id', ss)
if (exact && ss.length !== want.length) await broke('spec/OAUTH-ACCOUNT.md, "_oauthSessions"', `${SESSIONS} ${what}`, request, `exactly its ${want.length} sessions not ended: ${want.map((s) => s.clientId).join(', ')}`, ss)
for (const s of want) {
const x = ss.find((y) => y.clientId === s.clientId)
const wanted = { clientId: s.clientId, issuer: s.issuer, scope: s.scope, createdAt: `within a second of ${iso(s.created)}`, updatedAt: s.updated === s.created ? 'its createdAt' : `within a second of ${iso(s.updated)}`, expiresAt: 'two weeks after its createdAt', id: s.id ?? 'none of its tokens or its code' }
if (!x) {
await broke('spec/OAUTH-ACCOUNT.md, "_oauthSessions"', `${SESSIONS} ${what}`, request, wanted, 'not listed')
continue
}
const tokens = [s.access, s.refresh, s.code, ...s.old.flatMap((o) => [o.access, o.refresh])]
const fine = x.issuer === s.issuer && x.scope === s.scope && near(x.createdAt, s.created) && near(x.updatedAt, s.updated) && (s.updated !== s.created || x.updatedAt === x.createdAt) &&
TIME.test(x.expiresAt) && Date.parse(x.expiresAt) - Date.parse(x.createdAt) === TWO_WEEKS && (s.id === undefined || x.id === s.id) && !tokens.includes(x.id)
if (!fine) await broke('spec/OAUTH-ACCOUNT.md, "_oauthSessions"', `${SESSIONS} ${what}`, request, wanted, x)
s.id = x.id
}
for (const s of gone) if (ss.some((y) => y.clientId === s.clientId || (s.id !== undefined && y.id === s.id))) await broke('spec/OAUTH-ACCOUNT.md, "_oauthSessions"', `${SESSIONS} ${what}`, request, `no session of ${s.clientId}: ended, or another account's`, ss)
return ss
}
/// A device's fields: `userAgent` and `ipAddress` left out when its
/// sign-in had none, as other checks' browsers send no `User-Agent`.
const DEVICE_KEYS = ['id', 'ipAddress', 'loginRequired', 'signedInAt', 'userAgent']
const DEVICE_REQUIRED = ['id', 'loginRequired', 'signedInAt']
const deviceShaped = (x) => {
const keys = Object.keys(x ?? {})
return keys.every((k) => DEVICE_KEYS.includes(k)) && DEVICE_REQUIRED.every((k) => keys.includes(k)) && typeof x.id === 'string' && HEX.test(x.id) && TIME.test(x.signedInAt) && typeof x.loginRequired === 'boolean' &&
['userAgent', 'ipAddress'].every((k) => x[k] === undefined || typeof x[k] === 'string')
}
/// What a device is listed with, as the harness knows it: its
/// `User-Agent`'s first 256 characters, and its client address.
const deviceKey = (ua, ip) => `${ua}|${ip}`
const keyOf = (d) => deviceKey(d.ua.slice(0, 256), d.ip)
/// `_oauthDevices` of `acct` held to the devices the harness signed it in
/// on: with `exact`, those of `want` and no other, else those of `want`
/// among others; none of `gone`. Each with its `User-Agent`'s first 256
/// characters, its client address, `signedInAt` within a second of the
/// account's last sign-in there, `loginRequired` false, and an `id` the
/// same as before, none of its cookies. The latest `signedInAt` first, then
/// by `id` (spec/OAUTH-ACCOUNT.md, "_oauthDevices"). Notes each device's
/// `id` for the account.
async function checkDevices(what, acct, want, { exact = true, gone = [] } = {}) {
const request = { account: who(acct), at: what }
const ds = await listOf(DEVICES, acct, what)
for (const x of ds) if (!deviceShaped(x)) await broke('spec/OAUTH-ACCOUNT.md, "_oauthDevices"', `${DEVICES} ${what}`, request, `each device {${DEVICE_REQUIRED.join(', ')}, userAgent?, ipAddress?}, its id lower case hex, signedInAt a datetime, loginRequired a boolean`, x)
const order = [...ds].sort(newestFirst('signedInAt')).map((x) => x.id)
if (!isDeepStrictEqual(ds.map((x) => x.id), order)) await broke('spec/OAUTH-ACCOUNT.md, "_oauthDevices"', `${DEVICES} ${what}`, request, 'the latest signedInAt first, then by id', ds)
if (exact && ds.length !== want.length) await broke('spec/OAUTH-ACCOUNT.md, "_oauthDevices"', `${DEVICES} ${what}`, request, `exactly the ${want.length} devices it is signed in on`, ds)
for (const d of want) {
const x = ds.find((y) => deviceKey(y.userAgent, y.ipAddress) === keyOf(d))
const wanted = { userAgent: d.ua.slice(0, 256), ipAddress: d.ip, signedInAt: `within a second of ${iso(d.signedIn[acct.n])}`, loginRequired: false, id: d.ids[acct.n] ?? 'none of its cookies' }
if (!x) {
await broke('spec/OAUTH-ACCOUNT.md, "_oauthDevices"', `${DEVICES} ${what}`, request, wanted, 'not listed')
continue
}
const fine = near(x.signedInAt, d.signedIn[acct.n]) && x.loginRequired === false && (d.ids[acct.n] === undefined || x.id === d.ids[acct.n]) && ![...d.b.jar.values()].includes(x.id)
if (!fine) await broke('spec/OAUTH-ACCOUNT.md, "_oauthDevices"', `${DEVICES} ${what}`, request, wanted, x)
d.ids[acct.n] = x.id
}
for (const d of gone) if (ds.some((y) => deviceKey(y.userAgent, y.ipAddress) === keyOf(d) || (d.ids[acct.n] !== undefined && y.id === d.ids[acct.n]))) await broke('spec/OAUTH-ACCOUNT.md, "_oauthDevices"', `${DEVICES} ${what}`, request, `no device with User-Agent ${d.ua.slice(0, 60)}…: signed out of, or signed in on without remember`, ds)
return ds
}
/// The accounts a new authorization page on `device` lists, by DID, sorted
/// (spec/OAUTH.md, "The authorization page"); or null.
async function pageLists(device) {
const req = await request(newClient(), device)
if (!req) return null
return { req, dids: (req.shown.data.__sessions ?? []).map((x) => x.account?.did).sort() }
}
// ------------------------------------------------------------------ steps
/// Each route with no token, a token the server did not give out, an app
/// password's session, a refresh token, the admin's `Basic`, and an OAuth
/// access token with its proof: the errors spec/OAUTH-ACCOUNT.md gives,
/// whatever the HTTP method, and nothing listed or ended. Then, with the
/// password session, the other HTTP method; a revocation with no body, a
/// body that is not JSON or not an object, with no `id`, an `id` that is
/// not a string, or another Content-Type: `400 InvalidRequest`, ending
/// nothing; and the lists answering the same whatever parameters they are
/// given (spec/OAUTH-ACCOUNT.md, "Auth", "Requests").
export async function oauthAccountAuth() {
if (!able()) return
const acct = await createAccount({ withPassword: true })
if (!acct) return
const device = newDevice()
const s = await session(acct, device)
if (!s) return
await checkSessions('after a sign-in', acct, [s])
await checkDevices('after a sign-in', acct, [device])
const ids = { [REVOKE_SESSION]: s.id, [REVOKE_DEVICE]: device.ids[acct.n] }
const input = (route) => (REVOKES.includes(route) ? JSON.stringify({ id: ids[route] }) : undefined)
const app = await appPasswordToken(acct)
if (!app) return
const t = tokenOf(cand, acct)
const auths = [
['no Authorization header', {}, { status: 401, error: 'AuthMissing' }],
['a token the server did not give out', { authorization: bearer(pick([`${t.slice(0, -4)}${t.endsWith('AAAA') ? 'BBBB' : 'AAAA'}`, 'not-a-token'])) }, INVALID_TOKEN],
['an app password\'s session', { authorization: bearer(app) }, INVALID_TOKEN],
['a refresh token', { authorization: bearer(acct.sides.server.refresh) }, INVALID_TOKEN],
['the admin\'s Basic', { authorization: cand.admin }, INVALID_TOKEN],
['an OAuth access token, as DPoP with its proof', { oauth: s }, FORBIDDEN],
]
for (const [how, auth, want] of auths) {
for (const route of ROUTES) {
const got = refusal(await call(route, { auth, body: input(route) }), want)
if (!isDeepStrictEqual(got, want)) await broke('spec/OAUTH-ACCOUNT.md, "Auth"', `${route} with ${how}`, { route, auth: how }, want, got)
}
// The token is checked before the HTTP method.
const route = pick(ROUTES)
const method = otherMethod(route)
const got = refusal(await call(route, { auth, method, body: method === 'POST' ? input(REVOKE_SESSION) : undefined }), want)
if (!isDeepStrictEqual(got, want)) await broke('spec/OAUTH-ACCOUNT.md, "Auth"', `${route} by ${method}, with ${how}`, { route, method, auth: how }, want, got)
}
await works('spec/OAUTH-ACCOUNT.md, "Auth"', 'a session the routes were refused the end of', acct, s)
await checkSessions('after calls refused for their auth', acct, [s])
await checkDevices('after calls refused for their auth', acct, [device])
count('oauth account: auth refused', true)
const auth = password(acct)
for (const route of ROUTES) {
const method = otherMethod(route)
const got = refusal(await call(route, { auth, method, ...(method === 'POST' ? { body: '{}' } : { query: `?${new URLSearchParams({ id: ids[route] ?? 'x' })}` }) }), INVALID_REQUEST)
if (!isDeepStrictEqual(got, INVALID_REQUEST)) await broke('spec/OAUTH-ACCOUNT.md, "Requests"', `${route} by ${method}`, { route, method }, INVALID_REQUEST, got)
}
for (const route of REVOKES) {
const id = ids[route]
const faults = [
['no body', { type: pick([undefined, 'application/json']) }],
['a body that is not JSON', { body: pick(['{"id":', `id=${id}`, '']) }],
['a body that is not an object', { body: JSON.stringify(pick([[id], id, 5, null])) }],
['no id', { body: JSON.stringify(pick([{}, { ID: id }, { name: id }])) }],
['an id that is not a string', { body: JSON.stringify({ id: pick([5, null, true, [id], { id }]) }) }],
['another Content-Type', { body: JSON.stringify({ id }), type: pick(['text/plain', 'application/x-www-form-urlencoded']) }],
]
for (const [name, opts] of faults) {
const got = refusal(await call(route, { auth, ...opts }), INVALID_REQUEST)
if (!isDeepStrictEqual(got, INVALID_REQUEST)) await broke('spec/OAUTH-ACCOUNT.md, "Requests"', `${route} with ${name}`, { route, body: opts.body ?? null, type: opts.type ?? null }, INVALID_REQUEST, got)
}
// A body past 153600 bytes, before its Content-Type or JSON is looked
// at: `413`; one of exactly 153600, answered (spec/OAUTH-ACCOUNT.md,
// "Requests"). Its id is the live one, then one of no device or session.
const sized = (n, of) => {
const head = JSON.stringify({ id: of, pad: '' })
return JSON.stringify({ id: of, pad: 'x'.repeat(n - head.length) })
}
const tooLarge = { status: 413, error: 'PayloadTooLargeError' }
const over = { body: sized(153601, id), type: pick(['application/json', 'text/plain']) }
const big = refusal(await call(route, { auth, ...over }), tooLarge)
if (!isDeepStrictEqual(big, tooLarge)) await broke('spec/OAUTH-ACCOUNT.md, "Requests"', `${route} with a body of 153601 bytes`, { route, bytes: 153601, type: over.type }, tooLarge, big)
const full = await call(route, { auth, body: sized(153600, unlike(id)) })
if (full.status !== 200 || !isDeepStrictEqual(full.body, {})) await broke('spec/OAUTH-ACCOUNT.md, "Requests"', `${route} with a body of exactly 153600 bytes`, { route, bytes: 153600 }, { status: 200, body: {} }, { status: full.status, body: full.body })
}
for (const route of [SESSIONS, DEVICES]) {
const plain = await call(route, { auth })
const query = `?${new URLSearchParams({ limit: String(1 + below(3)), cursor: pick(['x', s.id]), id: pick([s.id, 'x']) })}`
const given = await call(route, { auth, query })
if (!isDeepStrictEqual(given, plain)) await broke('spec/OAUTH-ACCOUNT.md, "Requests"', `${route} with parameters`, { route, query }, plain, given)
}
await works('spec/OAUTH-ACCOUNT.md, "Requests"', 'a session the routes were refused the end of', acct, s)
await checkSessions('after requests refused', acct, [s])
await checkDevices('after requests refused', acct, [device])
count('oauth account: requests refused', true)
}
/// An account with sessions of two clients, one refreshed, and two more
/// ended by `/oauth/revoke` and by a replayed refresh token; with
/// --commands, an MCP session too; and another account with one of its
/// own. `_oauthSessions` lists exactly each account's sessions not ended.
/// With --commands, the MCP session's token at an `oauth_` tool is a tool
/// error. Then `_oauthRevokeSession` of one ends it, leaving the other;
/// that of the other account's session's `id`, an `id` no session has, and
/// a session's tokens, ends nothing; and of the MCP session, ends it at
/// `/mcp` (spec/OAUTH-ACCOUNT.md, "_oauthSessions", "_oauthRevokeSession",
/// "Auth").
export async function oauthAccountSessions() {
if (!able()) return
const two = await twoAccounts()
if (!two) return
const [acct, other] = two
const device = newDevice()
const s1 = await session(acct, device)
const s2 = s1 && (await session(acct, device))
const theirs = s2 && (await session(other, newDevice()))
if (!theirs) return
await refresh(pick([s1, s2]))
// Two sessions ended otherwise (spec/OAUTH.md, "Revocation", "The token
// endpoint").
const revoked = await session(acct, device)
const replayed = revoked && (await session(acct, device))
if (!replayed) return
const rv = await revoked.dpop.send(`${issuer(cand)}/oauth/revoke`, { method: 'POST', ...form({ client_id: revoked.clientId, token: pick([revoked.access, revoked.refresh]) }) })
if (rv.status !== 200) await flowBroke('revoke', { client_id: revoked.clientId }, 200, { status: rv.status, body: rv.body })
await refresh(replayed)
const replay = await replayed.dpop.send(`${issuer(cand)}/oauth/token`, { method: 'POST', ...form({ grant_type: 'refresh_token', client_id: replayed.clientId, refresh_token: replayed.old.at(-1).refresh }) })
if (replay.status !== 400 || replay.body?.error !== 'invalid_grant') await flowBroke('token: a replayed refresh token', { client_id: replayed.clientId }, { status: 400, error: 'invalid_grant' }, { status: replay.status, body: replay.body })
const mcp = COMMANDS ? await mcpSession('listed by _oauthSessions', acct) : null
if (mcp) Object.assign(mcp, { issuer: 'mcp', updated: mcp.created, old: [] })
const listed = [s1, s2, ...(mcp ? [mcp] : [])]
await checkSessions('of two clients, one refreshed', acct, listed, { gone: [revoked, replayed, theirs] })
await checkSessions('of another account', other, [theirs], { gone: [s1, s2, revoked, replayed] })
count('oauth account: sessions listed', true)
if (mcp) {
// An MCP session's token at a tool of the routes: refused as a method
// that takes no OAuth token refuses it, a tool error (spec/OAUTH-ACCOUNT.md,
// "Auth"; spec/OAUTH-MCP.md, "Tokens at the MCP endpoint").
const r = pick(OAUTH_ROUTES)
const args = r.required.length ? { id: s1.id } : {}
const got = await mcpToolCall(r.tool, args, bearer(mcp.access))
const view = { http: got.http, isError: got.result?.isError ?? null, structuredContent: got.result?.structuredContent ?? null }
const want = { http: 200, isError: true, structuredContent: { error: FORBIDDEN.error, message: FORBIDDEN.message } }
if (!isDeepStrictEqual(view, want)) await broke('spec/OAUTH-ACCOUNT.md, "Auth"', `tool ${r.tool} with an MCP session's token`, { tool: r.tool, args }, want, { ...view, challenge: got.challenge, body: got.body })
await checkSessions('after an oauth_ tool refused an MCP session\'s token', acct, listed, { gone: [revoked, replayed, theirs] })
}
const [victim, kept] = chance(0.5) ? [s1, s2] : [s2, s1]
await revoke(REVOKE_SESSION, acct, victim.id, 'one of its sessions', chance(0.3) ? { reason: 'harness' } : {})
await ended('spec/OAUTH-ACCOUNT.md, "_oauthRevokeSession"', 'a session _oauthRevokeSession ended', victim)
await works('spec/OAUTH-ACCOUNT.md, "_oauthRevokeSession"', 'a session _oauthRevokeSession left', acct, kept)
const left = [kept, ...(mcp ? [mcp] : [])]
await checkSessions('after one is ended', acct, left, { gone: [victim, revoked, replayed, theirs] })
for (const [what, id] of [['another account\'s session\'s id', theirs.id], ['an id no session has', pick(['', 'no-such-session', unlike(kept.id)])], ['a session\'s access token', kept.access], ['a session\'s refresh token', kept.refresh]]) {
await revoke(REVOKE_SESSION, acct, id, what)
}
await works('spec/OAUTH-ACCOUNT.md, "_oauthRevokeSession"', 'the other account\'s session, after the account revoked its id', other, theirs)
await works('spec/OAUTH-ACCOUNT.md, "_oauthRevokeSession"', 'a session whose tokens were given as an id', acct, kept)
await checkSessions('after revoking ids not its own', acct, left, { gone: [victim, revoked, replayed, theirs] })
await checkSessions('of another account, after the first revoked its id', other, [theirs])
if (mcp) {
await revoke(REVOKE_SESSION, acct, mcp.id, 'an MCP session')
await mcpEnded('an MCP session ended by _oauthRevokeSession', mcp)
await checkSessions('after its MCP session is ended', acct, [kept], { gone: [mcp, victim, revoked, replayed, theirs] })
}
count('oauth account: sessions ended', true)
}
/// A browser in which the account and a second account sign in with
/// `remember`, with a `User-Agent` of its own; another in which the account
/// signs in without `remember`; and a third with `remember`.
/// `_oauthDevices` lists the two remembered ones, with their headers,
/// client addresses and last sign-ins, the same `id` while each lasts. Then
/// `_oauthRevokeDevice` of the first: the account's list loses it, the
/// second account's keeps it, its page lists the second account and not the
/// first, a consent there for the first needs a sign-in again, and the
/// sessions made through it still work; and of an `id` no device has, or
/// none, changes nothing (spec/OAUTH-ACCOUNT.md, "_oauthDevices",
/// "_oauthRevokeDevice").
export async function oauthAccountDevices() {
if (!able()) return
const two = await twoAccounts()
if (!two) return
const [acct, other] = two
const device = newDevice()
const mine = await session(acct, device)
if (!mine) return
await checkDevices('after a sign-in with remember', acct, [device])
const theirs = await session(other, device)
if (!theirs) return
if (chance(0.5)) {
// Signed in there again: its sign-in time is now.
const req = await request(newClient(), device)
if (req && !(await signIn(acct, device, req, pick([true, undefined])))) return
}
const passing = newDevice()
const req = await request(newClient(), passing)
const si = req && (await signIn(acct, passing, req, pick([false, undefined])))
if (!si) return
if (typeof si.ephemeralToken !== 'string') await flowBroke('sign-in without remember', { account: who(acct) }, 'an ephemeralToken', si)
const second = newDevice()
const later = await session(acct, second)
if (!later) return
await checkDevices('on two devices remembered, and one not', acct, [device, second], { gone: [passing] })
await checkDevices('of the second account', other, [device], { gone: [second, passing] })
count('oauth account: devices listed', true)
await revoke(REVOKE_DEVICE, acct, device.ids[acct.n], 'a device', chance(0.3) ? { reason: 'harness' } : {})
delete device.signedIn[acct.n]
await checkDevices('after _oauthRevokeDevice', acct, [second], { gone: [device, passing] })
await checkDevices('of the second account, after the first signed out', other, [device])
const page = await pageLists(device)
if (!page) return
if (!isDeepStrictEqual(page.dids, [didOf(cand, other)])) await broke('spec/OAUTH-ACCOUNT.md, "_oauthRevokeDevice"', 'authorization page after _oauthRevokeDevice', { account: who(acct), other: who(other) }, { __sessions: [who(other)] }, { __sessions: page.dids })
const c = await device.b.api(page.req.page, '/consent', { did: didOf(cand, acct) }, { headers: device.headers })
const p = target(c.json?.url)?.params
if (c.status !== 200 || p?.code || p?.error !== 'invalid_request') await broke('spec/OAUTH-ACCOUNT.md, "_oauthRevokeDevice"', 'consent on a device the account was signed out of', { account: who(acct) }, { status: 200, url: 'with error=invalid_request: it must sign in again' }, { status: c.status, body: c.json })
await works('spec/OAUTH-ACCOUNT.md, "_oauthRevokeDevice"', 'a session made through a device the account was signed out of', acct, mine)
await works('spec/OAUTH-ACCOUNT.md, "_oauthRevokeDevice"', 'the second account\'s session made through that device', other, theirs)
await works('spec/OAUTH-ACCOUNT.md, "_oauthRevokeDevice"', 'a session made through another device', acct, later)
for (const [what, id] of [['an id no device has', pick(['', 'no-such-device', unlike(second.ids[acct.n])])], ['the device it was signed out of', device.ids[acct.n]]]) await revoke(REVOKE_DEVICE, acct, id, what)
await checkDevices('after revoking ids of no device it is signed in on', acct, [second], { gone: [device, passing] })
await checkDevices('of the second account, at the end', other, [device])
count('oauth account: devices signed out of', true)
}
/// Each `oauth_` tool, in every era, and each `pds oauth` command, with the
/// account's password session, an app password's, and none, answering as
/// its route does over XRPC: the same status and error, or the same
/// answer; those of the password session ending what they name
/// (spec/COMMANDS.md, "The account's OAuth sessions", "Auth", "Answers";
/// spec/OAUTH-ACCOUNT.md, "How it is checked").
export async function oauthAccountCommands() {
if (!able() || !COMMANDS) return
const spec = 'spec/COMMANDS.md, "The account\'s OAuth sessions"'
const acct = await createAccount({ withPassword: true })
if (!acct) return
const [d1, d2] = [newDevice(), newDevice()]
const ss = []
for (const d of [d1, d1, d2]) {
const s = await session(acct, d)
if (!s) return
ss.push(s)
}
await checkSessions('before its tools and commands', acct, ss)
await checkDevices('before its tools and commands', acct, [d1, d2])
const app = await appPasswordToken(acct)
if (!app) return
const [sessions, revokeSession, devices, revokeDevice] = OAUTH_ROUTES
const ways = [
...[MCP_VERSION, ...MCP_LEGACY].map((era) => [`tool, ${era}`, (r, args, token) => viaRouteTool(r, args, token, era)]),
['command', (r, args, token) => viaRouteCommand(r, args, { token })],
]
const overXrpc = (r, args, token) => call(r.route, { auth: token ? { authorization: bearer(token) } : {}, body: r.method === 'POST' ? JSON.stringify(args) : undefined })
const shape = (a) => (a.status === 200 ? { status: 200, body: a.body } : { status: a.status, error: a.body?.error ?? null })
const same = async (r, args, [whose, token]) => {
const want = shape(await overXrpc(r, args, token))
for (const [way, fn] of ways) {
const got = shape(await fn(r, args, token))
if (!isDeepStrictEqual(got, want)) await differ(way === 'command' ? `pds oauth ${r.command}` : `tool ${r.tool}`, { auth: whose, args, way }, want, got, spec)
}
}
const auths = [['its password session', tokenOf(cand, acct)], ['an app password\'s session', app], ['none', undefined]]
for (const a of auths) for (const r of [sessions, devices]) await same(r, {}, a)
for (const a of auths.slice(1)) {
await same(revokeSession, { id: ss[0].id }, a)
await same(revokeDevice, { id: d1.ids[acct.n] }, a)
}
await checkSessions('after its tools and commands refused', acct, ss)
await checkDevices('after its tools and commands refused', acct, [d1, d2])
count('oauth account: tools and commands as the routes', true)
// With its password session, one ended by a tool and one by a command.
const own = tokenOf(cand, acct)
const [tool, cmd] = [pick(ways.slice(0, -1)), ways.at(-1)]
const ending = async (r, x, y, what) => {
for (const [[way, fn], id] of [[tool, x], [cmd, y]]) {
const got = shape(await fn(r, { id }, own))
if (!isDeepStrictEqual(got, { status: 200, body: {} })) await differ(way === 'command' ? `pds oauth ${r.command}` : `tool ${r.tool}`, { auth: 'its password session', way, what }, { status: 200, body: {} }, got, spec)
}
}
await ending(revokeSession, ss[0].id, ss[1].id, 'two of its sessions')
await ended('spec/OAUTH-ACCOUNT.md, "_oauthRevokeSession"', 'a session ended through its tool or command', ss[0])
await ended('spec/OAUTH-ACCOUNT.md, "_oauthRevokeSession"', 'a session ended through its tool or command', ss[1])
await works('spec/OAUTH-ACCOUNT.md, "_oauthRevokeSession"', 'a session its tools and commands left', acct, ss[2])
await checkSessions('after its tool and command ended two', acct, [ss[2]], { gone: [ss[0], ss[1]] })
await ending(revokeDevice, d1.ids[acct.n], d2.ids[acct.n], 'both its devices')
await checkDevices('after its tool and command signed it out of both', acct, [], { gone: [d1, d2] })
await works('spec/OAUTH-ACCOUNT.md, "_oauthRevokeDevice"', 'a session made through a device its tool or command signed it out of', acct, ss[2])
count('oauth account: tools and commands ending', true)
}
/// What `oauthAccountBeforeCrash` made, for `oauthAccountAfterCrash`.
let beforeRestart = null
/// Before the server is killed, at some crashes of a run with
/// --crash-every (not --store's, which holds the data directory's size and
/// starts), on an account with a password and without the email factor: a
/// session ended by `_oauthRevokeSession` and one left, each through a
/// device of its own, and the account signed out of the first device by
/// `_oauthRevokeDevice` (spec/OAUTH-ACCOUNT.md, "Durability").
export async function oauthAccountBeforeCrash() {
beforeRestart = null
if (!able() || STORE || !chance(0.4)) return
const some = accounts.filter((a) => a.password)
if (!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 || now.body?.active === false) return
const [gone, kept] = [newDevice(), newDevice()]
const ending = await session(acct, gone)
const live = ending && (await session(acct, kept))
if (!live) return
await checkSessions('before a restart', acct, [ending, live], { exact: false })
await checkDevices('before a restart', acct, [gone, kept], { exact: false })
await revoke(REVOKE_SESSION, acct, ending.id, 'a session, before a restart')
await revoke(REVOKE_DEVICE, acct, gone.ids[acct.n], 'a device, before a restart')
delete gone.signedIn[acct.n]
beforeRestart = { acct, ending, live, gone, kept }
}
/// After the restart, what was made before it is as it was: the session
/// still ended and not listed, the other working and listed; the device
/// still signed out of, its page not listing the account; and the other
/// device listed with its `userAgent` and `ipAddress` (spec/OAUTH-ACCOUNT.md,
/// "Durability").
export async function oauthAccountAfterCrash() {
const b = beforeRestart
beforeRestart = null
if (!b) return
const { acct } = b
await ended('spec/OAUTH-ACCOUNT.md, "Durability"', 'a session ended by _oauthRevokeSession before a restart', b.ending)
await works('spec/OAUTH-ACCOUNT.md, "Durability"', 'a session left before a restart', acct, b.live)
await checkSessions('after a restart', acct, [b.live], { exact: false, gone: [b.ending] })
await checkDevices('after a restart', acct, [b.kept], { exact: false, gone: [b.gone] })
const page = await pageLists(b.gone)
if (page && page.dids.includes(didOf(cand, acct))) await broke('spec/OAUTH-ACCOUNT.md, "Durability"', 'authorization page on a device signed out of before a restart', { account: who(acct) }, { __sessions: 'not the account' }, { __sessions: page.dids })
count('oauth account: across a restart', true)
}