chadtmiller.com/monolith
An atproto PDS
0
0
// OAuth (spec/OAUTH.md): the server as authorization server, driven on both
// sides as a client and a browser would drive it, through lib/oauth.mjs, and
// through @atproto/oauth-client-node, a client app's own library.
//
// Each account keeps its OAuth sessions, `{clientId, scope, key, dpop,
// tokens, old, code}`, where `dpop` holds each side's DPoP state (the one key,
// each side's nonce), `tokens` each side's current access and refresh token,
// `old` the ones they replaced, and `code` the code the session came from.
// Each account also keeps a browser on each side, its device there.
import { isDeepStrictEqual } from 'node:util'
import { NodeOAuthClient, requestLocalLock } from '@atproto/oauth-client-node'
import { below, chance, pick, rand } from '../lib/random.mjs'
import { cand, plcUrl, ref } from '../lib/processes.mjs'
import { fail } from '../lib/plc.mjs'
import { allow, count, differ } from '../lib/report.mjs'
import { accounts, didOf } from '../lib/state.mjs'
import { strip } from '../lib/xrpc.mjs'
import { API, Browser, Dpop, answer, b64u, form, formPost, fresh, newKey, pkce, proof, sha256, signJwt, target, wwwError } from '../lib/oauth.mjs'
import { can, issuer, own, pageApi } from '../lib/server.mjs'
export const sides = () => [ref, cand]
const URN = 'urn:ietf:params:oauth:request_uri:'
const REDIRECT = 'http://127.0.0.1/callback'
const DEFAULT_REDIRECTS = ['http://127.0.0.1/', 'http://[::1]/']
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
const B64TOKEN = /^[A-Za-z0-9\-._~+/]+=*$/
/// `expires_in` of a token answer on each side: the spec's on the server,
/// the reference's own on the reference (spec/OAUTH.md, departures). An
/// implementation other than Monolith may answer either (spec/COMPAT.md).
const TOKEN_LIFE = { reference: [3599, 3600], server: [899, 900] }
/// The loopback clients the harness signs in with (spec/OAUTH.md,
/// "Clients"): each one's declared scope (none: `atproto`) and redirect
/// URIs (none: the defaults).
const CLIENTS = [
{},
{ scope: 'atproto transition:generic', redirects: [REDIRECT] },
{ scope: 'atproto transition:generic transition:email', redirects: [REDIRECT] },
{
scope: 'atproto transition:email repo:* blob:image/* account:email?action=manage identity:handle rpc:app.bsky.feed.getTimeline?aud=* foo:bar repo:com.example.* transition:other',
redirects: [REDIRECT, 'http://[::1]/cb'],
},
{ scope: 'atproto transition:generic transition:chat.bsky', redirects: ['http://127.0.0.1:8080/cb'] },
]
/// A client's `client_id`: `http://localhost`, or `/` after it, then its
/// scope and redirect URIs in the query.
export function clientId(c, slash = false) {
const q = new URLSearchParams()
if (c.scope) q.append('scope', c.scope)
for (const r of c.redirects ?? []) q.append('redirect_uri', r)
return `http://localhost${slash ? '/' : ''}${q.size ? `?${q}` : ''}`
}
const declared = (c) => (c.scope ?? 'atproto').split(' ')
const redirects = (c) => c.redirects ?? DEFAULT_REDIRECTS
// ---------------------------------------------------------------- answers
/// `v` with the side's URL and the accounts' DIDs taken out.
export function norm(side, v) {
if (typeof v === 'string') return strip(side, v)
if (Array.isArray(v)) return v.map((x) => norm(side, x))
if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, norm(side, x)]))
return v
}
/// An answer of the OAuth endpoints or of XRPC with the DPoP scheme: its
/// status, `error` (spec/OAUTH.md, "Errors"), whether it carries a nonce,
/// and `WWW-Authenticate`'s error; with `body` for a success's body as
/// compared.
export function view(side, res, body) {
const v = { status: res.status }
if (res.status >= 400 || res.status === 0) v.error = res.body?.error ?? null
else if (body) v.body = body(res.body)
v.nonce = Boolean(res.headers?.['dpop-nonce'])
const w = wwwError(res.headers?.['www-authenticate'])
if (w) v.www = w
return v
}
/// Send the same request to both sides, `send(side)` making it, and compare
/// `show(side, answer)`. Answers both answers by side name.
export async function compare(kind, request, send, show) {
const [a, b] = await Promise.all(sides().map((side) => send(side)))
const [va, vb] = [show(ref, a), show(cand, b)]
if (!isDeepStrictEqual(va, vb)) await differ(`OAuth: ${kind}`, request, va, vb)
count(`oauth ${kind}`, (a.status ?? 0) < 400)
return { reference: a, server: b }
}
/// A step of the reference's page API: compared on both sides as `compare`
/// compares, when the server has the page API; on the reference alone when
/// it has a sign-in hook instead, its `server` answer then undefined.
export async function onPage(kind, request, send, show) {
if (pageApi()) return compare(kind, request, send, show)
const a = await send(ref)
count(`oauth ${kind}`, (a.status ?? 0) < 400)
return { reference: a, server: undefined }
}
/// Redirect parameters as compared: the request's `state` and the codes
/// named, `error_description` taken out.
function params(side, p, ctx) {
if (!p) return p
const out = {}
for (const [k, v] of Object.entries(p)) {
if (k === 'error_description') continue
if (k === 'state' && ctx?.state === v) out[k] = '<state>'
else if (k === 'code') out[k] = typeof v === 'string' && v ? '<code>' : v
else out[k] = strip(side, v)
}
return out
}
/// Where a URL sends the browser, as compared.
function where(side, url, ctx, fragment = false) {
const t = target(url, fragment)
if (!t || t.unparsed) return t
return { to: strip(side, t.to), params: params(side, t.params, ctx), ...(t.hash ? { hash: t.hash } : {}) }
}
/// An account as the page and the API show it.
const accountView = (side, a) => norm(side, a)
/// A page: its status, error, redirect, and declared data.
function pageView(side, page, ctx) {
const v = { status: page.status }
if (page.data.__errorData) v.error = page.data.__errorData.error ?? null
if (page.status >= 300 && page.status < 400) v.location = where(side, page.headers.location, ctx, ctx?.mode === 'fragment')
const d = page.data.__authorizeData
if (d) v.authorizeData = norm(side, { ...d, requestUri: d.requestUri === ctx?.requestUri?.[side.name] ? '<request_uri>' : d.requestUri })
if (page.data.__sessions) {
const ss = page.data.__sessions.map((s) => ({ ...s, account: accountView(side, s.account) }))
v.sessions = ss.sort((x, y) => (canonical(x) < canonical(y) ? -1 : canonical(x) > canonical(y) ? 1 : 0))
}
if (page.status === 200 && !d && !page.data.__errorData) {
const f = formPost(page.text)
if (f) v.form = { method: f.method, action: strip(side, f.action), params: params(side, f.params, ctx) }
}
return v
}
/// A JSON text of `v` with object keys sorted, to order values by; what is
/// compared is the values themselves, whose key order no client relies on.
function canonical(v) {
if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`
if (v && typeof v === 'object') return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}`
return JSON.stringify(v)
}
/// An API answer.
function apiView(side, res, ctx) {
const v = { status: res.status }
const j = res.json
// A 404's body is the server's own (spec/OAUTH.md, the API).
if (res.status >= 400) {
if (res.status !== 404) v.error = j?.error ?? null
} else if (j && typeof j === 'object') {
const b = {}
for (const [k, x] of Object.entries(j)) {
if (k === 'account') b.account = accountView(side, x)
else if (k === 'ephemeralToken') b.ephemeralToken = typeof x === 'string' && x ? '<ephemeral>' : x
else if (k === 'url') b.url = where(side, x, ctx)
else b[k] = norm(side, x)
}
v.body = b
}
if (res.status < 400 && res.headers['cache-control'] !== 'no-store') v.cacheControl = res.headers['cache-control'] ?? null
return v
}
// ------------------------------------------------------------- requests
/// A DPoP state on each side for `key`.
export const dpops = (key) => ({ reference: new Dpop(key), server: new Dpop(key) })
/// A fresh nonce from `side` for `dpop`: any answer of `/oauth/par` carries
/// one.
export async function freshNonce(side, dpop) {
const res = await answer(await fetch(`${issuer(side)}/oauth/par`, { method: 'POST', ...form({}) }))
if (res.headers['dpop-nonce']) dpop.nonce = res.headers['dpop-nonce']
}
const par = (side, dpop, p, opts = {}) => dpop.send(`${issuer(side)}/oauth/par`, { method: 'POST', ...form(p), ...opts })
const token = (side, dpop, p, opts = {}) => dpop.send(`${issuer(side)}/oauth/token`, { method: 'POST', ...form(p), ...opts })
const revokeOn = (side, dpop, p, opts = {}) => dpop.send(`${issuer(side)}/oauth/revoke`, { method: 'POST', ...form(p), ...opts })
const GET_SESSION = '/xrpc/com.atproto.server.getSession'
const getSessionOn = (side, dpop, accessToken, opts = {}) => dpop.send(`${issuer(side)}${GET_SESSION}`, { accessToken, ...opts })
/// The authorization page's URL for a request.
const pageUrl = (side, clientId, requestUri) => `${issuer(side)}/oauth/authorize?${new URLSearchParams({ client_id: clientId, request_uri: requestUri })}`
/// The handle each side last gave the account, or null if they differ.
export function handleOf(acct) {
const [a, b] = [acct.handles.reference.at(-1), acct.handles.server.at(-1)]
return a === b ? a : null
}
/// The account's OAuth state.
export function oauthOf(acct) {
acct.oauth ??= { sessions: [], browsers: { reference: new Browser(), server: new Browser() }, remembered: false }
return acct.oauth
}
/// An account fit to sign in with on both sides: its handle the same on both.
const signable = () => accounts.filter((a) => handleOf(a))
// --------------------------------------------------------------- metadata
const CORS = ['access-control-allow-origin', 'access-control-allow-methods', 'access-control-allow-headers', 'access-control-max-age']
const corsOf = (h, names = CORS) => Object.fromEntries(names.map((n) => [n, h[n] ?? null]))
/// The authorization server metadata's fields the harness compares; the
/// rest is held to the spec on the server alone.
const AS_UNCOMPARED = ['token_endpoint_auth_signing_alg_values_supported', 'dpop_signing_alg_values_supported', 'request_parameter_supported', 'request_object_signing_alg_values_supported', 'request_object_encryption_alg_values_supported', 'request_object_encryption_enc_values_supported']
/// The metadata documents, the JWKS, and the endpoints' CORS answers
/// (spec/OAUTH.md, "The issuer", "Metadata").
export async function checkOAuthMetadata() {
await compare('protected resource metadata', { get: '/.well-known/oauth-protected-resource' },
async (side) => answer(await fetch(`${issuer(side)}/.well-known/oauth-protected-resource`)),
(side, r) => ({ status: r.status, type: r.headers['content-type']?.split(';')[0] ?? null, cors: r.headers['access-control-allow-origin'] ?? null, body: norm(side, r.body) }))
const as = await compare('authorization server metadata', { get: '/.well-known/oauth-authorization-server' },
async (side) => answer(await fetch(`${issuer(side)}/.well-known/oauth-authorization-server`)),
(side, r) => {
const body = { ...r.body }
for (const k of AS_UNCOMPARED) delete body[k]
return { status: r.status, type: r.headers['content-type']?.split(';')[0] ?? null, cors: corsOf(r.headers), body: norm(side, body) }
})
for (const side of sides()) {
const m = as[side.name].body ?? {}
for (const k of ['token_endpoint_auth_signing_alg_values_supported', 'dpop_signing_alg_values_supported']) {
if (!Array.isArray(m[k]) || !m[k].includes('ES256')) await fail(side, `authorization server metadata's ${k} (spec/OAUTH.md)`, { get: '/.well-known/oauth-authorization-server' }, 'a list with ES256', m[k])
}
}
const sm = as.server.body ?? {}
const extra = Object.keys(sm).filter((k) => k.startsWith('request_object_'))
if (own() && (sm.request_parameter_supported !== false || extra.length)) await fail(cand, 'authorization server metadata (spec/OAUTH.md)', { get: '/.well-known/oauth-authorization-server' }, { request_parameter_supported: false }, { request_parameter_supported: sm.request_parameter_supported, ...(extra.length ? { extra } : {}) })
await compare('JWKS', { get: '/oauth/jwks' }, async (side) => answer(await fetch(`${issuer(side)}/oauth/jwks`)),
(side, r) => ({ status: r.status, cors: corsOf(r.headers), keys: Array.isArray(r.body?.keys) }))
for (const path of ['/.well-known/oauth-authorization-server', '/oauth/jwks', '/oauth/par', '/oauth/token', '/oauth/revoke']) {
await compare(`OPTIONS ${path}`, { options: path, origin: 'http://app.example' },
async (side) => answer(await fetch(`${issuer(side)}${path}`, { method: 'OPTIONS', headers: { origin: 'http://app.example', 'access-control-request-method': 'POST', 'access-control-request-headers': 'content-type,dpop' } })),
(side, r) => ({ status: r.status, cors: corsOf(r.headers), nonce: 'dpop-nonce' in r.headers, cacheControl: r.headers['cache-control'] ?? null, pragma: r.headers.pragma ?? null }))
}
for (const [path, method] of [['/oauth/par', 'GET'], ['/oauth/par', 'PUT'], ['/oauth/token', 'GET'], ['/oauth/token', 'DELETE'], ['/oauth/revoke', 'GET'], ['/oauth/revoke', 'PUT'], ['/oauth/revoke', 'DELETE'], ['/oauth/authorize', 'POST'], ...(pageApi() ? [[`${API}/sign-in`, 'GET'], [`${API}/nope`, 'POST']] : [])]) {
await compare(`${method} ${path}`, { [method]: path }, async (side) => answer(await fetch(`${issuer(side)}${path}`, { method })), (side, r) => ({ status: r.status }))
}
}
// ----------------------------------------------------------------- flows
/// A new authorization request on both sides (spec/OAUTH.md, "Pushed
/// authorization requests"): a client, scope, redirect URI and the rest
/// drawn for `acct`, PAR'd and compared. Answers the request, `{client,
/// clientId, scope, redirect, kept, mode, state, pk, key, dpop, requestUri,
/// params}`, or null if PAR refused it on both sides. With `whole`, the
/// scope asked is the client's, as it declares it.
async function newRequest(acct, { client, extra = {}, kind = 'PAR', whole = false } = {}) {
client ??= pick(CLIENTS)
const id = clientId(client, chance(0.15))
const tokens = declared(client)
let scope = whole ? [...tokens] : tokens.filter((t) => t === 'atproto' || chance(0.6))
if (!whole && chance(0.2)) scope = scope.reverse()
if (!whole && chance(0.1)) scope = [...scope, pick(scope)]
const regs = redirects(client)
let redirect = pick(regs)
if (!new URL(redirect).port && chance(0.25)) {
const u = new URL(redirect)
u.port = String(1024 + below(60000))
redirect = u.href
}
const omit = regs.length === 1 && chance(0.25)
const mode = pick([undefined, undefined, 'query', 'fragment', 'form_post'])
const r = rand()
const hint = r < 0.15 ? (side) => handleOf(acct) : r < 0.2 ? (side) => handleOf(acct).toUpperCase() : r < 0.3 ? (side) => didOf(side, acct) : r < 0.33 ? () => NOBODY : r < 0.36 ? () => 'nobody.test' : null
const opt = {
...(chance(0.15) ? { prompt: pick(['login', 'consent', 'select_account', 'create']) } : {}),
...(chance(0.1) ? { ui_locales: pick(['en', 'fr-CA en', 'ja']) } : {}),
...(chance(0.05) ? { display: pick(['page', 'popup', 'touch', 'wap']) } : {}),
...(chance(0.05) ? { max_age: String(below(1000)) } : {}),
...(chance(0.05) ? { resource: 'http://example.com/mcp' } : {}),
}
const key = await newKey()
const dpop = dpops(key)
const pk = pkce()
const state = fresh(12)
const p = (side) => ({
client_id: id,
response_type: 'code',
...(omit ? {} : { redirect_uri: redirect }),
scope: scope.join(' '),
state,
code_challenge: pk.challenge,
code_challenge_method: 'S256',
...(mode ? { response_mode: mode } : {}),
...(hint ? { login_hint: hint(side) } : {}),
...opt,
...(typeof extra === 'function' ? extra(side) : extra),
})
const json = chance(0.1)
const jkt = chance(0.1)
// A PAR with no DPoP proof, the key bound at the token request, as the
// reference takes it (spec/OAUTH.md, "Pushed authorization requests",
// step 4).
const noProof = chance(0.1)
const send = (side) => {
const body = { ...p(side), ...(jkt ? { dpop_jkt: key.jkt } : {}) }
const opts = noProof ? { dpop: null } : {}
return json ? dpop[side.name].send(`${issuer(side)}/oauth/par`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), ...opts }) : par(side, dpop[side.name], body, opts)
}
const res = await compare(kind, { par: p(ref), json, dpop_jkt: jkt, ...(noProof ? { dpop: 'none' } : {}) }, send, (side, a) => view(side, a, (b) => ({ request_uri: typeof b?.request_uri === 'string' && b.request_uri.startsWith(URN) ? '<request_uri>' : b?.request_uri, expires_in: '<expires_in>' })))
for (const side of sides()) {
const a = res[side.name]
if (a.status === 201 && !(a.body.expires_in >= 299 && a.body.expires_in <= 300)) await fail(side, 'PAR expires_in (spec/OAUTH.md)', { par: p(ref) }, '299 to 300', a.body.expires_in)
}
if (res.reference.status !== 201) return null
return {
client,
clientId: id,
scope: [...new Set(scope)],
redirect: omit ? regs[0] : redirect,
sentRedirect: !omit,
mode,
state,
pk,
key,
dpop,
params: p,
requestUri: { reference: res.reference.body.request_uri, server: res.server.body.request_uri },
}
}
/// Load the request's page on both sides, in each side's `browser`
/// (spec/OAUTH.md, "The authorization page").
async function loadPage(req, browsers, kind = 'authorization page') {
return onPage(kind, { authorize: req.clientId }, (side) => browsers[side.name].navigate(pageUrl(side, req.clientId, req.requestUri[side.name])), (side, p) => pageView(side, p, req))
}
/// Sign the account in on both sides' pages. Answers each side's answer.
/// `extra(side)` adds to the input, as an `emailOtp`.
async function signIn(acct, req, browsers, { identifier, password, remember, kind = 'sign-in', extra = () => ({}) } = {}) {
const how = identifier ?? pick(['handle', 'handle', 'email', 'did', 'HANDLE'])
const id = (side) => (how === 'handle' ? handleOf(acct) : how === 'HANDLE' ? handleOf(acct).toUpperCase() : how === 'email' ? acct.email : how === 'did' ? didOf(side, acct) : how)
const pw = password ?? (acct.password || 'x')
const input = (side) => ({ locale: pick(['en']), identifier: id(side), password: pw, ...(remember === undefined ? {} : { remember }), ...extra(side) })
return onPage(kind, { signIn: { by: how, remember } }, (side) => browsers[side.name].api(pageUrl(side, req.clientId, req.requestUri[side.name]), '/sign-in', input(side)), (side, r) => apiView(side, r, req))
}
/// Consent on both sides. `bearer` is each side's ephemeral token, if any.
async function consent(acct, req, browsers, { scope, bearer, did, kind = 'consent' } = {}) {
const input = (side) => ({ did: did ? did(side) : didOf(side, acct), ...(scope ? { scope } : {}) })
return onPage(kind, { consent: { scope, bearer: Boolean(bearer) } }, (side) => browsers[side.name].api(pageUrl(side, req.clientId, req.requestUri[side.name]), '/consent', input(side), { bearer: bearer?.[side.name] }), (side, r) => apiView(side, r, req))
}
/// Follow the API's `url` to the client on both sides (spec/OAUTH.md,
/// "The redirect").
async function followRedirect(req, browsers, urls, kind = 'redirect') {
return compare(kind, { follow: 'the url the API answered' }, (side) => browsers[side.name].navigate(urls[side.name], { site: 'same-origin', referer: pageUrl(side, req.clientId, req.requestUri[side.name]) }), (side, p) => pageView(side, p, req))
}
/// The answer that sends the browser back to the client, on both sides,
/// compared: on the reference, the API's `url` followed; on the server, the
/// same, or with a sign-in hook, what the hook answers for the account
/// approving the request on the server's own page (or with `approve`
/// false, refusing it).
async function redirectBoth(acct, req, browsers, urls, { approve = true, kind = 'redirect' } = {}) {
if (pageApi()) return followRedirect(req, browsers, urls, kind)
const viaHook = (side) => (side === ref
? browsers.reference.navigate(urls.reference, { site: 'same-origin', referer: pageUrl(ref, req.clientId, req.requestUri.reference) })
: cand.signIn({ identifier: handleOf(acct), password: acct.password }, pageUrl(cand, req.clientId, req.requestUri.server), { approve }))
return compare(kind, { follow: 'the url the API answered', server: `signed in on its own page, ${approve ? 'approving' : 'refusing'}` }, viaHook, (side, p) => pageView(side, p, req))
}
/// The code a redirect page gave the client on `side`, and its parameters.
function codeOf(page, mode) {
if (page.status === 200) return formPost(page.text)?.params ?? {}
return target(page.headers.location, mode === 'fragment')?.params ?? {}
}
/// Exchange each side's code; check what the spec fixes of the answer on
/// each side (spec/OAUTH.md, "The token endpoint"). `auth(side)` gives
/// more parameters, as a client's authentication (spec/OAUTH-CLIENTS.md,
/// "Client authentication"). Answers both answers.
async function exchange(acct, req, codes, { kind = 'token: code', redirect = req.redirect, verifier = req.pk.verifier, clientId = req.clientId, dpop = req.dpop, auth = async () => ({}) } = {}) {
const body = (side) => ({ grant_type: 'authorization_code', client_id: clientId, redirect_uri: redirect, code: codes[side.name], code_verifier: verifier ?? undefined })
const res = await compare(kind, { token: { ...body(ref), code: '<code>' } }, async (side) => token(side, dpop[side.name], { ...body(side), ...(await auth(side)) }), (side, a) => view(side, a, tokenBody(side)))
for (const side of sides()) await holdToken(side, acct, res[side.name], body(ref))
return res
}
/// A token answer's body as compared.
const tokenBody = (side) => (b) => ({ keys: Object.keys(b ?? {}).sort(), token_type: b?.token_type, scope: b?.scope, sub: strip(side, String(b?.sub)) })
/// What the spec fixes of a token answer on `side`.
async function holdToken(side, acct, res, request) {
if (res.status !== 200) return
const b = res.body
const [lo, hi] = TOKEN_LIFE[side.name]
const bad = []
const within = ([l, h]) => b.expires_in >= l && b.expires_in <= h
if (side === cand && !own() && !within(TOKEN_LIFE.server) && within(TOKEN_LIFE.reference)) allow('OAuth access tokens of the reference\'s 60 minutes, not spec/OAUTH.md\'s 15')
else if (!within([lo, hi])) bad.push(`expires_in ${b.expires_in}, not ${lo} to ${hi}`)
// A client without the refresh_token grant is given none
// (spec/OAUTH-CLIENTS.md, "Requests"); whether there is one is compared.
for (const t of ['access_token', ...('refresh_token' in b ? ['refresh_token'] : [])]) if (typeof b[t] !== 'string' || !B64TOKEN.test(b[t])) bad.push(`${t} not a b64token`)
if (b.access_token === b.refresh_token) bad.push('the access and refresh tokens are the same')
if (b.sub !== didOf(side, acct)) bad.push('sub is not the account')
if (bad.length) await fail(side, 'a token answer (spec/OAUTH.md)', request, 'as the spec says', bad)
}
/// getSession with each side's access token of `s` (or `tokens`), compared
/// (spec/OAUTH.md, "OAuth tokens on XRPC").
async function getSessionBoth(s, kind, { tokens, opts = {}, dpop = s.dpop } = {}) {
const at = (side) => (tokens ? tokens[side.name] : s.tokens[side.name].access)
return compare(kind, { getSession: kind }, (side) => getSessionOn(side, dpop[side.name], at(side), typeof opts === 'function' ? opts(side) : opts), (side, a) => view(side, a, (b) => norm(side, b)))
}
/// A full sign-in, compared at each step: PAR, the page, sign-in, consent
/// or a rejection, the redirect, the code exchange, and getSession. The
/// session joins the account's. Answers it, or null.
export async function login(acct, { client, reject = chance(0.08), narrow = chance(0.15), newDevice = chance(0.2), whole = false } = {}) {
const st = oauthOf(acct)
if (newDevice) {
st.browsers = { reference: new Browser(), server: new Browser() }
st.remembered = false
}
const req = await newRequest(acct, { client, whole })
if (!req) return null
const page = await loadPage(req, st.browsers)
if (page.reference.status !== 200) return null
let bearer
if (!(st.remembered && chance(0.5))) {
const remember = pick([true, true, false, undefined])
const si = await signIn(acct, req, st.browsers, { remember })
if (si.reference.status !== 200) return null
if (remember === true) st.remembered = true
else if (remember === false) st.remembered = false
if (si.reference.json.ephemeralToken && chance(0.95)) bearer = { reference: si.reference.json.ephemeralToken, server: si.server?.json?.ephemeralToken }
if (chance(0.2)) await loadPage(req, st.browsers, 'authorization page after sign-in')
}
let scope
if (narrow && can('narrowScope')) {
const kept = req.scope.filter((t) => ['atproto', 'transition:email', 'transition:generic', 'transition:chat.bsky', 'repo:*', 'blob:image/*', 'account:email?action=manage', 'identity:handle', 'rpc:app.bsky.feed.getTimeline?aud=*'].includes(t))
let picked = kept.filter((t) => (t === 'atproto' ? chance(0.9) : chance(0.5)))
// The narrowed scope's order depends on how many tokens `scope` names,
// those the request lacks too.
if (chance(0.4)) picked = picked.reverse()
if (chance(0.3)) picked.push(...pick([['foo:bar'], ['transition:chat.bsky', 'foo:bar'], ['repo:com.example.x']]))
scope = picked.join(' ') || 'atproto'
}
const decided = reject
? await onPage('reject', { reject: true }, (side) => st.browsers[side.name].api(pageUrl(side, req.clientId, req.requestUri[side.name]), '/reject', {}), (side, r) => apiView(side, r, req))
: await consent(acct, req, st.browsers, { scope, bearer })
if (decided.reference.status !== 200) return null
const urls = { reference: decided.reference.json.url, server: decided.server?.json?.url }
const back = await redirectBoth(acct, req, st.browsers, urls, { approve: !reject })
const got = { reference: codeOf(back.reference, req.mode), server: codeOf(back.server, req.mode) }
if (!got.reference.code) return null
const codes = { reference: got.reference.code, server: got.server.code }
const t = await exchange(acct, req, codes)
if (t.reference.status !== 200) return null
const s = {
clientId: req.clientId,
client: req.client,
scope: t.reference.body.scope,
key: req.key,
dpop: req.dpop,
tokens: { reference: { access: t.reference.body.access_token, refresh: t.reference.body.refresh_token }, server: { access: t.server.body.access_token, refresh: t.server.body.refresh_token } },
old: { reference: [], server: [] },
code: codes,
redirect: req.redirect,
pk: req.pk,
issued: Date.now(),
}
await getSessionBoth(s, 'getSession after sign-in')
st.sessions.push(s)
if (st.sessions.length > 8) st.sessions.shift()
return s
}
/// Each side's code in a consent's `url`, or null if the reference gave none.
function codesOf(c) {
const codes = { reference: target(c.reference.json?.url)?.params?.code, server: target(c.server?.json?.url)?.params?.code }
return codes.reference ? codes : null
}
/// An approved request on both sides: PAR, page, sign-in and consent, with
/// each side's code. Answers `{req, codes, browsers}` or null.
export async function approved(acct) {
const req = await newRequest(acct, { client: CLIENTS[1], kind: 'PAR (for another check)' })
if (!req) return null
return approve(acct, req)
}
/// `req` approved on both sides, each in a new browser: page, sign-in and
/// consent, with each side's code. Answers `{req, codes, browsers}` or
/// null. With a server's sign-in hook, the server's code is the one its
/// hook brings back, and the redirect each side answers is compared.
export async function approve(acct, req) {
const browsers = { reference: new Browser(), server: new Browser() }
await loadPage(req, browsers, 'authorization page (for another check)')
const si = await signIn(acct, req, browsers, { remember: true, identifier: 'handle', kind: 'sign-in (for another check)' })
if (si.reference.status !== 200) return null
const c = await consent(acct, req, browsers, { kind: 'consent (for another check)' })
let codes = codesOf(c)
if (!codes) return null
if (!pageApi()) {
const back = await redirectBoth(acct, req, browsers, { reference: c.reference.json.url }, { kind: 'redirect (for another check)' })
codes = { reference: codes.reference, server: codeOf(back.server, req.mode).code }
}
return { req, codes, browsers }
}
// ------------------------------------------------------------------ steps
/// A full sign-in for the account.
export async function oauthLogin(acct) {
if (!handleOf(acct)) return
await login(acct)
}
/// A sign-in gives the device new cookies, and a browser holding the ones
/// from before is that device for 30 seconds, and after that ends it
/// (spec/OAUTH.md, "The authorization page", "Devices"): a page loaded on
/// a new device, its cookies copied to a second browser, a sign-in on the
/// first, whether it renewed the device's cookies; then, at once or 31
/// seconds later, a page with the copied cookies, in the browser that
/// signed in, and with the copied ones again, all compared.
export async function oauthDeviceCookies(acct) {
if (!handleOf(acct) || !acct.password) return
const first = { reference: new Browser(), server: new Browser() }
const req = await newRequest(acct, { client: CLIENTS[1], kind: 'PAR (device cookies)' })
if (!req) return
const page = await loadPage(req, first, 'authorization page (device cookies)')
if (page.reference.status !== 200) return
const copied = { reference: new Browser(), server: new Browser() }
for (const side of sides()) copied[side.name].jar = new Map(first[side.name].jar)
const si = await signIn(acct, req, first, { remember: true, identifier: 'handle', kind: 'sign-in (device cookies)' })
if (si.reference.status !== 200) return
const renewed = (side) => [...first[side.name].jar].some(([k, v]) => k !== 'csrf-token' && copied[side.name].jar.get(k) !== v)
const [ra, rb] = sides().map(renewed)
if (ra !== rb) await differ('OAuth: device cookies at sign-in (spec/OAUTH.md, Devices)', { signIn: 'remember: true' }, { renewed: ra }, { renewed: rb })
count('oauth device cookies renewed at sign-in', ra)
const later = chance(0.4)
if (later) await new Promise((ok) => setTimeout(ok, 31_000))
const when = later ? '31 s after a sign-in' : 'just after a sign-in'
for (const [who, browsers] of [['the cookies from before', copied], ['the browser that signed in', first], ['the cookies from before, again', copied]]) {
const r = await newRequest(acct, { client: CLIENTS[1], kind: 'PAR (device cookies)' })
if (!r) return
await loadPage(r, browsers, `authorization page with ${who}, ${when}`)
}
}
/// How long the harness uses a session's access token before refreshing it
/// first: the server's tokens live 15 minutes, the reference's 60, and a run
/// may be slow, so a token is refreshed three minutes before the server's
/// would expire, whatever the step then does with it.
export const RENEW_AFTER_MS = (TOKEN_LIFE.server[0] - 180) * 1000
/// A session of the account, the newest more often than not, its tokens
/// refreshed first if the server's access token is near its end.
export async function pickSession(acct) {
const ss = oauthOf(acct).sessions
if (!ss.length) return null
const s = chance(0.6) ? ss[ss.length - 1] : pick(ss)
await renew(acct, s)
return s
}
/// Refresh `s` with its current refresh token, compared, if its access
/// token is older than `RENEW_AFTER_MS`.
async function renew(acct, s) {
if (Date.now() - s.issued < RENEW_AFTER_MS) return
const body = (side) => ({ grant_type: 'refresh_token', client_id: s.clientId, refresh_token: s.tokens[side.name].refresh })
const res = await compare('token: refresh (a session near its expiry)', { refresh: 'near expiry' }, (side) => token(side, s.dpop[side.name], body(side)), (side, a) => view(side, a, tokenBody(side)))
for (const side of sides()) await holdToken(side, acct, res[side.name], { refresh: 'near expiry' })
s.issued = Date.now()
if (res.reference.status !== 200) return
for (const side of sides()) {
s.old[side.name].push({ ...s.tokens[side.name] })
s.tokens[side.name] = { access: res[side.name].body.access_token, refresh: res[side.name].body.refresh_token }
}
if (s.old.reference.length > 4) for (const side of sides()) s.old[side.name].shift()
}
/// A refresh (spec/OAUTH.md, "The token endpoint"): with the session's
/// refresh token, a replaced one, another key, another client, or no
/// proof; then getSession with the old and new access tokens.
export async function oauthRefresh(acct) {
const s = await pickSession(acct)
if (!s) return
const r = rand()
const how = r < 0.6 ? 'current' : r < 0.75 && s.old.reference.length ? 'replaced' : r < 0.85 ? 'other key' : r < 0.92 ? 'other client' : 'no proof'
const idx = how === 'replaced' ? below(s.old.reference.length) : null
const rt = (side) => (how === 'replaced' ? s.old[side.name][idx].refresh : s.tokens[side.name].refresh)
const other = how === 'other key' ? dpops(await newKey()) : null
const cid = how === 'other client' ? clientId(pick(CLIENTS.filter((c) => clientId(c) !== s.clientId))) : s.clientId
const body = (side) => ({ grant_type: 'refresh_token', client_id: cid, refresh_token: rt(side) })
const res = await compare(`token: refresh (${how})`, { refresh: how }, (side) => token(side, (other ?? s.dpop)[side.name], body(side), how === 'no proof' ? { dpop: null } : {}), (side, a) => view(side, a, tokenBody(side)))
for (const side of sides()) await holdToken(side, acct, res[side.name], { refresh: how })
const before = { reference: s.tokens.reference.access, server: s.tokens.server.access }
if (res.reference.status === 200) {
s.issued = Date.now()
for (const side of sides()) {
s.old[side.name].push({ ...s.tokens[side.name] })
s.tokens[side.name] = { access: res[side.name].body.access_token, refresh: res[side.name].body.refresh_token }
}
if (s.old.reference.length > 4) for (const side of sides()) s.old[side.name].shift()
await getSessionBoth(s, 'getSession with the replaced access token', { tokens: before })
}
await getSessionBoth(s, `getSession after a refresh (${how})`)
}
/// A revocation of one of the session's tokens, or of none of them
/// (spec/OAUTH.md, "Revocation"), then getSession and a refresh.
export async function oauthRevoke(acct) {
const s = await pickSession(acct)
if (!s) return
const r = rand()
const what = r < 0.3 ? 'access token' : r < 0.55 ? 'refresh token' : r < 0.65 && s.old.reference.length ? 'replaced refresh token' : r < 0.72 && s.old.reference.length ? 'replaced access token' : r < 0.8 ? 'code' : 'garbage'
const tok = (side) => {
const o = s.old[side.name].at(-1)
return { 'access token': s.tokens[side.name].access, 'refresh token': s.tokens[side.name].refresh, 'replaced refresh token': o?.refresh, 'replaced access token': o?.access, code: s.code[side.name], garbage: 'garbage' }[what]
}
const w = rand()
const by = w < 0.8 ? 'own key' : w < 0.9 ? 'other key' : 'no proof'
const dp = by === 'other key' ? dpops(await newKey()) : s.dpop
await compare(`revoke (${what}, ${by})`, { revoke: what, by }, (side) => revokeOn(side, dp[side.name], { client_id: s.clientId, token: tok(side), ...(chance(0.2) ? { token_type_hint: pick(['access_token', 'refresh_token']) } : {}) }, by === 'no proof' ? { dpop: null } : {}), (side, a) => view(side, a, (b) => b))
await getSessionBoth(s, `getSession after a revocation (${what}, ${by})`)
if (chance(0.5)) await oauthRefresh(acct)
}
/// getSession with a session's access token, current or replaced, and with
/// the other schemes and tokens the spec names (spec/OAUTH.md, "OAuth
/// tokens on XRPC").
export async function oauthGetSession(acct) {
const s = await pickSession(acct)
const r = rand()
if (!s || r < 0.15) {
// A password session's token with the DPoP scheme, and an OAuth one
// with Bearer, refreshSession and deleteSession.
const d = dpops(await newKey())
if (s && chance(0.5)) {
const which = pick(['Bearer', 'bearer', 'refreshSession', 'deleteSession'])
const path = which.endsWith('Session') && which !== 'getSession' ? `/xrpc/com.atproto.server.${which}` : GET_SESSION
await compare(`OAuth access token as ${which}`, { which }, (side) => s.dpop[side.name].send(`${issuer(side)}${path}`, { method: path === GET_SESSION ? 'GET' : 'POST', accessToken: s.tokens[side.name].access, scheme: which.toLowerCase() === 'bearer' ? which : 'DPoP' }), (side, a) => view(side, a, (b) => norm(side, b)))
} else {
const which = pick(['access', 'refresh'])
await compare(`password session's ${which} token with DPoP`, { which }, (side) => getSessionOn(side, d[side.name], which === 'access' ? acct.sides[side.name].token : acct.sides[side.name].refresh), (side, a) => view(side, a))
}
return
}
if (r < 0.7 || !s.old.reference.length) return void (await getSessionBoth(s, 'getSession'))
const i = below(s.old.reference.length)
await getSessionBoth(s, 'getSession with a replaced access token', { tokens: { reference: s.old.reference[i].access, server: s.old.server[i].access } })
}
// ------------------------------------------------------------- refusals
/// Base PAR parameters for a valid request of `client`.
function basePar(client = CLIENTS[1]) {
const pk = pkce()
return { client_id: clientId(client), response_type: 'code', redirect_uri: redirects(client)[0], scope: declared(client).join(' '), state: fresh(12), code_challenge: pk.challenge, code_challenge_method: 'S256' }
}
/// Pad `p` with a parameter the server ignores, so that its form is `n`
/// bytes.
function padTo(p, n) {
p.pad = ''
p.pad = 'x'.repeat(n - new URLSearchParams(Object.entries(p).filter(([, v]) => v !== undefined)).toString().length)
}
/// PAR requests with one thing wrong (spec/OAUTH.md, "Pushed authorization
/// requests", "Clients"): `[name, change(params, side)]`.
const PAR_FAULTS = [
['no client_id', (p) => void delete p.client_id],
['empty client_id', (p) => void (p.client_id = '')],
['client_id not a loopback one', (p) => void (p.client_id = pick(['foo', 'http://localhost:8080', 'http://127.0.0.1', 'http://localhost/cb', 'http://localhost#x', 'HTTP://LOCALHOST', 'https://localhost', 'http://localhost?foo=bar', 'http://localhost?scope=atproto&scope=atproto', 'http://localhost?scope=atproto%20atproto', 'http://localhost?scope=transition%3Ageneric', 'http://localhost?scope=', 'http://localhost?scope=atproto%20%20x', 'http://localhost?redirect_uri=https%3A%2F%2Fexample.com%2Fcb', 'http://localhost?redirect_uri=http%3A%2F%2Flocalhost%2Fcb']))],
['redirect URI with a user', (p) => Object.assign(p, { client_id: 'http://localhost?redirect_uri=http%3A%2F%2Fu%3Ap%40127.0.0.1%2Fcb', redirect_uri: 'http://u:p@127.0.0.1/cb', scope: 'atproto' })],
['no response_type', (p) => void delete p.response_type],
['response_type', (p) => void (p.response_type = pick(['token', 'none', 'code id_token', 'bogus', 'id_token']))],
['redirect_uri malformed', (p) => void (p.redirect_uri = pick(['nope', 'http://localhost/callback', 'ftp://x/cb']))],
['redirect_uri not the client\'s', (p) => void (p.redirect_uri = pick(['http://127.0.0.1/other', 'https://example.com/cb', 'com.example:/cb', 'http://[::1]/callback', 'http://127.0.0.1/callback?x=1']))],
['redirect_uri left out, two registered', (p) => Object.assign(p, { client_id: 'http://localhost', scope: 'atproto', redirect_uri: undefined })],
['port not the registered one', (p) => Object.assign(p, { client_id: clientId(CLIENTS[4]), scope: 'atproto', redirect_uri: 'http://127.0.0.1:9090/cb' })],
['no scope', (p) => void delete p.scope],
['scope without atproto', (p) => void (p.scope = 'transition:generic')],
['scope not declared', (p) => void (p.scope = pick(['atproto transition:email', 'atproto openid', 'atproto repo:*']))],
['scope malformed', (p) => void (p.scope = pick(['atproto transition:generic', 'atproto\ttransition:generic', ' atproto', 'atproto "x"']))],
['openid', (p) => Object.assign(p, { client_id: 'http://localhost?scope=atproto%20openid', redirect_uri: 'http://127.0.0.1/', scope: 'atproto openid' })],
['include: of a set with no record', (p) => Object.assign(p, { client_id: 'http://localhost?scope=atproto%20include%3Acom.example.authBasic', redirect_uri: 'http://127.0.0.1/', scope: 'atproto include:com.example.authBasic' })],
['no code_challenge', (p) => void delete p.code_challenge],
['no PKCE', (p) => void (delete p.code_challenge, delete p.code_challenge_method)],
['code_challenge_method', (p) => void (p.code_challenge_method = pick(['plain', 'foo', 'S512']))],
['code_challenge_method left out', (p) => void delete p.code_challenge_method],
['prompt', (p) => void (p.prompt = pick(['none', 'bogus']))],
['ui_locales', (p) => void (p.ui_locales = pick(['english', 'EN', 'en-us']))],
['display', (p) => void (p.display = 'tv')],
['max_age', (p) => void (p.max_age = pick(['-1', 'x', '1.5']))],
['login_hint', (p) => void (p.login_hint = pick(['', 'not a hint!', 'alice@example.com']))],
['claims, nonce or id_token_hint', (p) => Object.assign(p, pick([{ claims: '{}' }, { nonce: 'x' }, { id_token_hint: 'a.b.c' }]))],
['response_mode', (p) => void (p.response_mode = pick(['bogus', 'web_message']))],
// The body's own cap, 100 KiB, the reference's (spec/OAUTH.md): an
// ignored parameter pads the form to exactly the size.
['a body one byte past 100 KiB', (p) => padTo(p, 102401)],
['a body of exactly 100 KiB', (p) => padTo(p, 102400)],
// Long loopback client IDs, each part within its own cap, kept
// (spec/OAUTH.md, "Pushed authorization requests", step 17).
['a loopback client_id whose scope is near 4096 bytes', (p) => {
const scope = scopeOf(4096 - below(64))
Object.assign(p, { client_id: `http://localhost?${new URLSearchParams({ redirect_uri: 'http://127.0.0.1/', scope })}`, redirect_uri: 'http://127.0.0.1/', scope: 'atproto' })
}],
['a loopback client_id of 18470 bytes', (p) => Object.assign(p, { client_id: loopbackOf(CLIENT_ID_CAP), redirect_uri: 'http://127.0.0.1/', scope: 'atproto' })],
['knotless\'s loopback client_id', (p) => Object.assign(p, { client_id: KNOTLESS_ID, redirect_uri: `http://127.0.0.1:${1024 + below(60000)}/callback`, scope: new URL(KNOTLESS_ID).searchParams.get('scope') })],
]
/// The longest loopback `client_id` kept (spec/OAUTH.md, "Pushed
/// authorization requests", step 17).
const CLIENT_ID_CAP = 18470
/// A scope of exactly `n` bytes: `atproto` and distinct `rpc` permissions.
function scopeOf(n) {
const tok = (i, pad = '') => `rpc:com.example.m${i}${pad}?aud=*`
const toks = ['atproto']
while (toks.join(' ').length + 1 + tok(toks.length).length <= n) toks.push(tok(toks.length))
const short = n - toks.join(' ').length
if (short > 0) toks[toks.length - 1] = tok(toks.length - 1, 'x'.repeat(short))
return toks.join(' ')
}
/// Every byte of `s` percent-encoded.
const encodeAll = (s) => [...Buffer.from(s)].map((b) => `%${b.toString(16).toUpperCase().padStart(2, '0')}`).join('')
/// A loopback `client_id` of exactly `n` bytes: a scope of 4096 bytes and
/// `http://127.0.0.1/`, every byte percent-encoded, then a second redirect
/// URI as long as it takes.
function loopbackOf(n) {
const head = `http://localhost/?scope=${encodeAll(scopeOf(4096))}&redirect_uri=${encodeAll('http://127.0.0.1/')}&redirect_uri=${encodeAll('http://127.0.0.1/')}`
const rest = n - head.length
const id = `${head}${encodeAll('x'.repeat(Math.floor(rest / 3)))}${'y'.repeat(rest % 3)}`
if (id.length !== n) throw new Error(`loopbackOf(${n}) is ${id.length} bytes`)
return id
}
/// The knotless CLI's loopback `client_id`, 2857 bytes.
const KNOTLESS_ID = 'http://localhost?redirect_uri=http%3A%2F%2F127.0.0.1%2Fcallback&scope=atproto+repo%3Adev.knotless.repo+repo%3Adev.knotless.ref+repo%3Adev.knotless.claim+repo%3Adev.knotless.pack+repo%3Adev.knotless.redirect+repo%3Adev.knotless.pull+repo%3Adev.knotless.issue+repo%3Adev.knotless.comment+repo%3Adev.knotless.state+repo%3Adev.knotless.hide+repo%3Adev.knotless.block+repo%3Adev.knotless.queue+repo%3Adev.knotless.label+repo%3Adev.knotless.assignment+repo%3Adev.knotless.autoMerge+repo%3Adev.knotless.emails+repo%3Adev.knotless.profile+repo%3Adev.knotless.star+repo%3Adev.knotless.follow+repo%3Adev.knotless.org+repo%3Adev.knotless.orgMember+repo%3Adev.knotless.orgAcceptance+repo%3Adev.knotless.reaction+repo%3Adev.knotless.rerun+repo%3Adev.knotless.cancel+repo%3Adev.knotless.release+repo%3Adev.knotless.releaseYank+repo%3Adev.knotless.theme+repo%3Adev.knotless.check+repo%3Adev.knotless.minutes+blob%3Aapplication%2Fx-git-packed-objects+blob%3Aapplication%2Foctet-stream+blob%3Atext%2Fplain+blob%3Aimage%2Fpng+blob%3Aimage%2Fjpeg+blob%3Aimage%2Fwebp+blob%3Aimage%2Fgif+rpc%3Flxm%3Ddev.knotless.pushRefs%26lxm%3Ddev.knotless.createCommit%26lxm%3Ddev.knotless.putDelegation%26lxm%3Ddev.knotless.getDelegation%26lxm%3Ddev.knotless.putOrgMember%26lxm%3Ddev.knotless.removeOrgMember%26lxm%3Ddev.knotless.joinOrg%26lxm%3Ddev.knotless.leaveOrg%26lxm%3Ddev.knotless.createOrgRepo%26lxm%3Ddev.knotless.getOrg%26lxm%3Ddev.knotless.getProfile%26lxm%3Dcom.atproto.moderation.createReport%26lxm%3Dcom.atproto.admin.updateSubjectStatus%26lxm%3Dcom.atproto.admin.getSubjectStatus%26lxm%3Ddev.knotless.listReports%26lxm%3Ddev.knotless.getUsage%26lxm%3Ddev.knotless.getLogs%26lxm%3Ddev.knotless.inviteRunner%26lxm%3Ddev.knotless.listRunnerInvites%26lxm%3Ddev.knotless.putRunOutput%26lxm%3Ddev.knotless.awaitSpaceWrites%26lxm%3Ddev.knotless.putSecret%26lxm%3Ddev.knotless.deleteSecret%26lxm%3Ddev.knotless.listSecrets%26lxm%3Ddev.knotless.updateRepo%26lxm%3Ddev.knotless.compactRepo%26lxm%3Ddev.knotless.archiveRepo%26lxm%3Ddev.knotless.protectBranch%26lxm%3Ddev.knotless.unprotectBranch%26lxm%3Ddev.knotless.defineLabel%26lxm%3Ddev.knotless.removeLabel%26lxm%3Ddev.knotless.shareRepo%26lxm%3Ddev.knotless.unshareRepo%26lxm%3Ddev.knotless.setTriager%26lxm%3Ddev.knotless.removeTriager%26lxm%3Ddev.knotless.addAgent%26lxm%3Ddev.knotless.removeAgent%26lxm%3Ddev.knotless.addRunner%26lxm%3Ddev.knotless.removeRunner%26lxm%3Ddev.knotless.listNotifications%26lxm%3Ddev.knotless.updateSeen%26lxm%3Ddev.knotless.getPreferences%26lxm%3Ddev.knotless.putPreferences%26lxm%3Ddev.knotless.putSubscription%26lxm%3Ddev.knotless.listSubscriptions%26lxm%3Ddev.knotless.deleteAccountData%26aud%3D*+space%3Adev.knotless.space%3Fauthority%3D*%26manage%3Dcreate%26manage%3Dupdate%26manage%3Ddelete+space%3Adev.knotless.orgSpace%3Fauthority%3D*%26manage%3Dcreate%26manage%3Dupdate%26manage%3Ddelete'
/// One PAR with one thing wrong, on both sides with a fresh nonce.
export async function oauthParRefused() {
const [name, change] = pick(own() ? PAR_FAULTS : PAR_FAULTS.filter(([n]) => !n.includes('100 KiB')))
const p = basePar()
change(p)
const d = dpops(await newKey())
const r = rand()
const how = r < 0.85 ? 'form' : r < 0.92 ? 'json' : r < 0.96 ? 'text/plain' : 'bad json'
if (how !== 'form') for (const side of sides()) await freshNonce(side, d[side.name])
const send = (side) => {
if (how === 'form') return par(side, d[side.name], p)
const ct = how === 'text/plain' ? 'text/plain' : 'application/json'
const body = how === 'json' ? JSON.stringify(Object.fromEntries(Object.entries(p).filter(([, v]) => v !== undefined))) : how === 'bad json' ? '{' : new URLSearchParams(p).toString()
return d[side.name].send(`${issuer(side)}/oauth/par`, { method: 'POST', headers: { 'content-type': ct }, body })
}
await compare(`PAR refused: ${name}${how === 'form' ? '' : ` (${how})`}`, { par: p, how }, send, (side, a) => view(side, a, () => '<accepted>'))
}
/// DPoP proofs with one thing wrong (spec/OAUTH.md, "DPoP"):
/// `[name, (key, htm, htu, nonce, at) => proof]`.
export const DPOP_FAULTS = [
['empty header', async () => ''],
['not a JWT', async () => 'abc'],
['no typ', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, header: { typ: undefined } })],
['typ jwt', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, header: { typ: 'jwt' } })],
['no jwk', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, header: { jwk: undefined } })],
['private jwk', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, header: { jwk: k.privateJwk } })],
['alg none', async (k, m, u, n, at) => {
const claims = { jti: fresh(), htm: m, htu: u, iat: Math.floor(Date.now() / 1000), nonce: n, ...(at ? { ath: sha256(at) } : {}) }
return `${b64u(JSON.stringify({ typ: 'dpop+jwt', alg: 'none', jwk: k.jwk }))}.${b64u(JSON.stringify(claims))}.`
}],
['bad signature', async (k, m, u, n, at) => (await proof(k, m, u, { nonce: n, accessToken: at })).slice(0, -6) + 'AAAAAA'],
['signed by another key', async (k, m, u, n, at) => {
const o = await newKey()
const claims = { jti: fresh(), htm: m, htu: u, iat: Math.floor(Date.now() / 1000), nonce: n, ...(at ? { ath: sha256(at) } : {}) }
return signJwt({ typ: 'dpop+jwt', alg: 'ES256', jwk: k.jwk }, claims, o)
}],
['iat 300 s old', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { iat: Math.floor(Date.now() / 1000) - 300 } })],
['iat 300 s ahead', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { iat: Math.floor(Date.now() / 1000) + 300 } })],
['iat 60 s old', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { iat: Math.floor(Date.now() / 1000) - 60 } })],
['iat 60 s ahead', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { iat: Math.floor(Date.now() / 1000) + 60 } })],
['no iat', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { iat: undefined } })],
['iat a string', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { iat: String(Math.floor(Date.now() / 1000)) } })],
['exp 300 s past', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { exp: Math.floor(Date.now() / 1000) - 300 } })],
['exp 100 s past', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { exp: Math.floor(Date.now() / 1000) - 100 } })],
['no jti', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { jti: undefined } })],
['jti a number', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { jti: 5 } })],
['htm another method', (k, m, u, n, at) => proof(k, m === 'GET' ? 'POST' : 'GET', u, { nonce: n, accessToken: at })],
['htm lower case', (k, m, u, n, at) => proof(k, m.toLowerCase(), u, { nonce: n, accessToken: at })],
['no htu', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { htu: undefined } })],
['htu another path', (k, m, u, n, at) => proof(k, m, `${new URL(u).origin}/oauth/other`, { nonce: n, accessToken: at })],
['htu with a query', (k, m, u, n, at) => proof(k, m, `${u}?x=1`, { nonce: n, accessToken: at })],
['htu with a fragment', (k, m, u, n, at) => proof(k, m, `${u}#x`, { nonce: n, accessToken: at })],
['htu with a trailing slash', (k, m, u, n, at) => proof(k, m, `${u}/`, { nonce: n, accessToken: at })],
['htu https', (k, m, u, n, at) => proof(k, m, u.replace(/^http:/, 'https:'), { nonce: n, accessToken: at })],
['htu upper-case scheme and host', (k, m, u, n, at) => proof(k, m, u.replace(/^http:\/\/[^/]+/, (x) => x.toUpperCase()), { nonce: n, accessToken: at })],
['htu with a user', (k, m, u, n, at) => proof(k, m, u.replace('http://', 'http://u:p@'), { nonce: n, accessToken: at })],
['no nonce', (k, m, u, n, at) => proof(k, m, u, { accessToken: at })],
['a nonce never given', (k, m, u, n, at) => proof(k, m, u, { nonce: 'not-a-nonce', accessToken: at })],
['nonce a number', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { nonce: 5 } })],
['ath given at the AS, wrong at XRPC', (k, m, u, n, at) => proof(k, m, u, { nonce: n, over: { ath: sha256('x') } })],
['no ath', (k, m, u, n, at) => proof(k, m, u, { nonce: n, accessToken: at, over: { ath: undefined } })],
]
/// A request with a DPoP proof with one thing wrong, or replayed
/// (spec/OAUTH.md, "DPoP", "Single-use values"), at PAR, the token or
/// revocation endpoint, or getSession, with a nonce fresh on each side.
export async function oauthDpopRefused(acct) {
const s = await pickSession(acct)
const where = pick(['par', 'par', 'token', 'revoke', ...(s ? ['getSession', 'getSession'] : [])])
const fault = chance(0.1) ? ['replayed'] : chance(0.05) ? ['two headers'] : pick(DPOP_FAULTS)
const name = fault[0]
const key = s && where === 'getSession' ? s.key : await newKey()
const d = s && where === 'getSession' ? s.dpop : dpops(key)
for (const side of sides()) await freshNonce(side, d[side.name])
const p = basePar()
const req = (side) => {
const at = where === 'getSession' ? s.tokens[side.name].access : undefined
if (where === 'par') return { url: `${issuer(side)}/oauth/par`, method: 'POST', ...form({ ...p, state: fresh(12) }) }
if (where === 'token') return { url: `${issuer(side)}/oauth/token`, method: 'POST', ...form({ grant_type: 'refresh_token', client_id: p.client_id, refresh_token: 'not-a-refresh-token' }) }
if (where === 'revoke') return { url: `${issuer(side)}/oauth/revoke`, method: 'POST', ...form({ client_id: p.client_id, token: 'garbage' }) }
return { url: `${issuer(side)}${GET_SESSION}`, method: 'GET', headers: { authorization: `DPoP ${at}` }, at }
}
const send = async (side) => {
const r = req(side)
const u = new URL(r.url)
const htu = u.origin + u.pathname
const nonce = d[side.name].nonce
const headers = { ...(r.headers ?? {}) }
let res
if (name === 'replayed' || name === 'two headers') {
const pr = await proof(key, r.method, htu, { nonce, accessToken: r.at })
const h = (dp) => [...Object.entries(headers), ...dp.map((x) => ['dpop', x])]
if (name === 'replayed') {
await fetch(r.url, { method: r.method, headers: h([pr]), body: r.body })
res = await fetch(r.url, { method: r.method, headers: h([pr]), body: r.body })
} else {
const pr2 = await proof(key, r.method, htu, { nonce, accessToken: r.at })
res = await fetch(r.url, { method: r.method, headers: h([pr, pr2]), body: r.body })
}
} else {
const pr = await fault[1](key, r.method, htu, nonce, r.at)
res = await fetch(r.url, { method: r.method, headers: { ...headers, dpop: pr }, body: r.body })
}
return answer(res)
}
await compare(`DPoP refused at ${where}: ${name}`, { where, proof: name }, send, (side, a) => view(side, a, () => '<accepted>'))
}
/// The authorization page, the API and the redirect, each with one thing
/// wrong (spec/OAUTH.md, "The authorization page", "The API", "The
/// redirect").
export async function oauthAuthorizeRefused(acct) {
if (!handleOf(acct)) return
const r = rand()
if (r < 0.35) return pageRefused(acct)
if (r < 0.85) return apiRefused(acct)
return redirectRefused(acct)
}
async function pageRefused(acct) {
const kind = pick(['headers', 'headers', 'query', 'other client', 'other device', 'after consent', 'after the exchange', 'unknown'])
if (kind === 'after consent' || kind === 'after the exchange') {
const a = await approved(acct)
if (!a) return
if (kind === 'after the exchange') await exchange(acct, a.req, a.codes, { kind: 'token: code (for another check)' })
await loadPage(a.req, a.browsers, `authorization page ${kind}`)
// Ending an approved request spends its code.
if (kind === 'after consent') await exchange(acct, a.req, a.codes, { kind: 'token: the code of a request ended by a reload' })
return
}
const req = await newRequest(acct, { client: CLIENTS[1], kind: 'PAR (for another check)' })
if (!req) return
const b = { reference: new Browser(), server: new Browser() }
if (kind === 'headers') {
const [name, headers] = pick([
['no Sec-Fetch headers', { 'sec-fetch-mode': undefined, 'sec-fetch-dest': undefined, 'sec-fetch-site': undefined }],
['Sec-Fetch-Mode cors', { 'sec-fetch-mode': 'cors' }],
['Sec-Fetch-Dest empty', { 'sec-fetch-dest': 'empty' }],
['Sec-Fetch-Site bogus', { 'sec-fetch-site': 'bogus' }],
['no Sec-Fetch-Site', { 'sec-fetch-site': undefined }],
['another Origin', { origin: 'http://evil.example' }],
['the issuer as Origin', 'own'],
['Sec-Fetch-Site none', { 'sec-fetch-site': 'none' }],
])
await compare(`authorization page: ${name}`, { page: name }, (side) => b[side.name].navigate(pageUrl(side, req.clientId, req.requestUri[side.name]), { headers: headers === 'own' ? { origin: issuer(side) } : headers }), (side, p) => pageView(side, p, req))
if (chance(0.5)) await loadPage(req, b, 'authorization page after a refused load')
return
}
if (kind === 'query') {
const [name, q] = pick([
['no client_id', (side) => `request_uri=${encodeURIComponent(req.requestUri[side.name])}`],
['no request_uri', () => `client_id=${encodeURIComponent(req.clientId)}`],
['malformed request_uri', () => `client_id=${encodeURIComponent(req.clientId)}&request_uri=urn%3Ax`],
['bad client_id', (side) => `client_id=foo&request_uri=${encodeURIComponent(req.requestUri[side.name])}`],
])
return void (await compare(`authorization page: ${name}`, { page: name }, (side) => b[side.name].navigate(`${issuer(side)}/oauth/authorize?${q(side)}`), (side, p) => pageView(side, p, req)))
}
if (kind === 'unknown') {
return void (await compare('authorization page: a request never made', { page: 'unknown request' }, (side) => b[side.name].navigate(pageUrl(side, req.clientId, `${URN}req-${'0'.repeat(32)}`)), (side, p) => pageView(side, p, req)))
}
if (kind === 'other client') {
const other = clientId(pick(CLIENTS.filter((c) => clientId(c) !== req.clientId)))
await compare('authorization page: another client\'s request', { page: 'other client' }, (side) => b[side.name].navigate(pageUrl(side, other, req.requestUri[side.name])), (side, p) => pageView(side, p, req))
return void (await loadPage(req, b, 'authorization page of a request ended'))
}
// another device
await loadPage(req, b, 'authorization page (for another check)')
const b2 = { reference: new Browser(), server: new Browser() }
await loadPage(req, b2, 'authorization page on another device')
await loadPage(req, b, 'authorization page after another device')
}
/// API calls with one thing wrong, on a loaded page.
async function apiRefused(acct) {
const req = await newRequest(acct, { client: CLIENTS[1], kind: 'PAR (for another check)' })
if (!req) return
const b = { reference: new Browser(), server: new Browser() }
await loadPage(req, b, 'authorization page (for another check)')
const page = (side) => pageUrl(side, req.clientId, req.requestUri[side.name])
const input = (side) => ({ locale: 'en', identifier: handleOf(acct), password: acct.password || 'x', remember: true })
const call = (name, fn) => compare(`API: ${name}`, { api: name }, fn, (side, r) => apiView(side, r, req))
const fault = pick([
'no CSRF header', 'CSRF mismatch', 'Sec-Fetch-Mode cors', 'Sec-Fetch-Site cross-site', 'another Origin', 'no Origin', 'Referer elsewhere', 'Referer with a malformed request_uri',
'form body', 'an extra field', 'bad locale', 'bad identifier', 'empty password', 'remember a string', 'wrong password', 'unknown account', 'no such endpoint',
'consent before sign-in', 'consent for another account', 'consent without atproto', 'consent with a malformed scope', 'consent twice', 'reject twice', 'reject after consent',
'consent with a token not requested', 'consent on another device', 'consent with a malformed did',
'ephemeral token of another request', 'sign-out', 'consent after sign-out',
])
const headers = {
'no CSRF header': { 'x-csrf-token': undefined },
'CSRF mismatch': { 'x-csrf-token': '0'.repeat(24) },
'Sec-Fetch-Mode cors': { 'sec-fetch-mode': 'cors' },
'Sec-Fetch-Site cross-site': { 'sec-fetch-site': 'cross-site' },
'another Origin': { origin: 'http://evil.example' },
'no Origin': { origin: undefined },
}[fault]
if (headers) return void (await call(`sign-in, ${fault}`, (side) => b[side.name].api(page(side), '/sign-in', input(side), { headers })))
if (fault === 'Referer elsewhere') return void (await call('sign-in, Referer elsewhere', (side) => b[side.name].api(`${issuer(side)}/elsewhere`, '/sign-in', input(side))))
if (fault === 'Referer with a malformed request_uri') return void (await call('sign-in, malformed request_uri', (side) => b[side.name].api(`${issuer(side)}/oauth/authorize?request_uri=urn:x`, '/sign-in', input(side))))
if (fault === 'form body') return void (await call('sign-in, form body', (side) => b[side.name].api(page(side), '/sign-in', null, { headers: { 'content-type': 'application/x-www-form-urlencoded' }, raw: 'a=b' })))
if (fault === 'no such endpoint') return void (await call('no such endpoint', (side) => b[side.name].api(page(side), '/nope', {})))
const bad = {
'an extra field': (side) => ({ ...input(side), extra: 1 }),
'bad locale': (side) => ({ ...input(side), locale: 'english' }),
'bad identifier': (side) => ({ ...input(side), identifier: 'not valid!' }),
'empty password': (side) => ({ ...input(side), password: '' }),
'remember a string': (side) => ({ ...input(side), remember: 'yes' }),
'wrong password': (side) => ({ ...input(side), password: `${acct.password ?? ''}x` }),
'unknown account': (side) => ({ ...input(side), identifier: 'nobody.test' }),
}[fault]
if (bad) return void (await call(`sign-in, ${fault}`, (side) => b[side.name].api(page(side), '/sign-in', bad(side))))
if (fault === 'consent before sign-in') return void (await consent(acct, req, b, { kind: 'consent before sign-in' }))
if (fault === 'reject twice') {
await call('reject', (side) => b[side.name].api(page(side), '/reject', {}))
return void (await call('reject again', (side) => b[side.name].api(page(side), '/reject', {})))
}
const si = await signIn(acct, req, b, { remember: fault === 'ephemeral token of another request' ? false : true, identifier: 'handle', kind: 'sign-in (for another check)' })
if (si.reference.status !== 200) return
if (fault === 'consent for another account') return void (await consent(acct, req, b, { did: () => NOBODY, kind: 'consent for another account' }))
if (fault === 'consent without atproto') return void (await consent(acct, req, b, { scope: 'transition:generic', kind: 'consent without atproto' }))
if (fault === 'consent with a malformed scope') return void (await consent(acct, req, b, { scope: pick(['atproto x', 'atproto "x"', ' atproto', 'atproto\\x']), kind: 'consent with a malformed scope' }))
if (fault === 'consent with a malformed did') return void (await consent(acct, req, b, { did: () => 'not-a-did', kind: 'consent with a malformed did' }))
if (fault === 'consent with a token not requested') {
const c = await consent(acct, req, b, { scope: `${req.scope.join(' ')} transition:chat.bsky`, kind: 'consent with a token not requested' })
const codes = codesOf(c)
if (codes) await exchange(acct, req, codes, { kind: 'token: code of a consent with a token not requested' })
return
}
if (fault === 'consent on another device') {
// The request was loaded on `b`; another browser, signed in there, consents.
const other = { reference: new Browser(), server: new Browser() }
const req2 = await newRequest(acct, { client: CLIENTS[1], kind: 'PAR (for another check)' })
if (!req2) return
await loadPage(req2, other, 'authorization page (for another check)')
await signIn(acct, req2, other, { remember: true, identifier: 'handle', kind: 'sign-in (for another check)' })
return void (await compare('consent on another device', { consent: 'another device' }, (side) => other[side.name].api(page(side), '/consent', { did: didOf(side, acct) }), (side, r) => apiView(side, r, req)))
}
if (fault === 'consent twice' || fault === 'reject after consent') {
const c = await consent(acct, req, b, { kind: 'consent (for another check)' })
if (fault === 'consent twice') await consent(acct, req, b, { kind: 'consent again' })
else await call('reject after consent', (side) => b[side.name].api(page(side), '/reject', {}))
const codes = codesOf(c)
if (codes) await exchange(acct, req, codes, { kind: `token: the code of a request ended by ${fault === 'consent twice' ? 'a second consent' : 'a rejection'}` })
return
}
if (fault === 'sign-out' || fault === 'consent after sign-out') {
await call('sign-out', (side) => b[side.name].api(page(side), '/sign-out', { did: didOf(side, acct) }))
if (fault === 'consent after sign-out') await consent(acct, req, b, { kind: 'consent after sign-out' })
return void (await loadPage(req, b, 'authorization page after sign-out'))
}
// An ephemeral token of another request on the same device.
const eph = { reference: si.reference.json.ephemeralToken, server: si.server.json?.ephemeralToken }
const req2 = await newRequest(acct, { client: CLIENTS[1], kind: 'PAR (for another check)' })
if (!req2) return
await loadPage(req2, b, 'authorization page (for another check)')
await consent(acct, req2, b, { bearer: eph, kind: 'consent with the ephemeral token of another request' })
}
/// The redirect with one thing wrong.
async function redirectRefused(acct) {
const a = await approved(acct)
if (!a) return
const { req, browsers: b } = a
const page = (side) => pageUrl(side, req.clientId, req.requestUri[side.name])
const consentUrl = (side) => `${issuer(side)}/oauth/authorize/redirect?${new URLSearchParams({ redirect_mode: 'query', redirect_uri: REDIRECT, iss: issuer(side), state: req.state, code: a.codes[side.name] })}`
const [name, go] = pick([
['no Referer', (side) => b[side.name].navigate(consentUrl(side), { site: 'same-origin' })],
['cross-site', (side) => b[side.name].navigate(consentUrl(side), { site: 'cross-site', referer: page(side) })],
['Referer without request_uri', (side) => b[side.name].navigate(consentUrl(side), { site: 'same-origin', referer: `${issuer(side)}/oauth/authorize` })],
['neither code nor error', (side) => b[side.name].navigate(`${issuer(side)}/oauth/authorize/redirect?${new URLSearchParams({ redirect_mode: 'query', redirect_uri: REDIRECT, state: 's' })}`, { site: 'same-origin', referer: page(side) })],
['another target', (side) => b[side.name].navigate(`${issuer(side)}/oauth/authorize/redirect?${new URLSearchParams({ redirect_mode: pick(['query']), redirect_uri: 'https://elsewhere.example/x', state: 's', iss: 'x', code: 'abc' })}`, { site: 'same-origin', referer: page(side) })],
['an error', (side) => b[side.name].navigate(`${issuer(side)}/oauth/authorize/redirect?${new URLSearchParams({ redirect_mode: 'fragment', redirect_uri: REDIRECT, state: 's', iss: 'x', error: 'access_denied', error_description: 'no', extra: '1' })}`, { site: 'same-origin', referer: page(side) })],
['bad redirect_mode', (side) => b[side.name].navigate(consentUrl(side).replace('redirect_mode=query', 'redirect_mode=bogus'), { site: 'same-origin', referer: page(side) })],
])
await compare(`redirect: ${name}`, { redirect: name }, go, (side, p) => pageView(side, p, { ...req, mode: name === 'an error' ? 'fragment' : 'query' }))
}
/// The token endpoint with one thing wrong (spec/OAUTH.md, "The token
/// endpoint").
export async function oauthTokenRefused(acct) {
if (!handleOf(acct)) return
const r = rand()
if (r < 0.4) {
const p = basePar()
const d = dpops(await newKey())
const [name, body, opts] = pick([
['no grant_type', { client_id: p.client_id, refresh_token: 'x' }],
['bogus grant_type', { grant_type: 'bogus', client_id: p.client_id }],
['client_credentials', { grant_type: 'client_credentials', client_id: p.client_id }],
['no client_id', { grant_type: 'refresh_token', refresh_token: 'x' }],
['bad client_id', { grant_type: 'refresh_token', client_id: 'foo', refresh_token: 'x' }],
['a refresh token never given', { grant_type: 'refresh_token', client_id: p.client_id, refresh_token: pick(['garbage', `ref-${'a'.repeat(64)}`]) }],
['empty refresh token', { grant_type: 'refresh_token', client_id: p.client_id, refresh_token: '' }],
['no code', { grant_type: 'authorization_code', client_id: p.client_id, redirect_uri: REDIRECT, code_verifier: 'a'.repeat(43) }],
['a code never given', { grant_type: 'authorization_code', client_id: p.client_id, redirect_uri: REDIRECT, code: 'garbage', code_verifier: 'a'.repeat(43) }],
['code_verifier too short', { grant_type: 'authorization_code', client_id: p.client_id, redirect_uri: REDIRECT, code: 'x', code_verifier: 'a'.repeat(42) }],
['code_verifier with other characters', { grant_type: 'authorization_code', client_id: p.client_id, redirect_uri: REDIRECT, code: 'x', code_verifier: '!'.repeat(43) }],
['no redirect_uri', { grant_type: 'authorization_code', client_id: p.client_id, code: 'x', code_verifier: 'a'.repeat(43) }],
['text/plain', { grant_type: 'refresh_token', client_id: p.client_id, refresh_token: 'x' }, { headers: { 'content-type': 'text/plain' } }],
])
return void (await compare(`token refused: ${name}`, { token: body }, (side) => token(side, d[side.name], body, opts ?? {}), (side, a) => view(side, a, () => '<accepted>')))
}
const a = await approved(acct)
if (!a) return
const { req, codes } = a
const [name, opts] = pick([
['wrong code_verifier', { verifier: fresh(32) }],
['no code_verifier', { verifier: null }],
['another redirect_uri', { redirect: 'http://127.0.0.1/other' }],
['another client', { clientId: clientId(CLIENTS[2]) }],
['another DPoP key', { dpop: dpops(await newKey()) }],
['no DPoP proof', 'no proof'],
['the code twice', 'twice'],
])
if (opts === 'no proof') {
const body = (side) => ({ grant_type: 'authorization_code', client_id: req.clientId, redirect_uri: req.redirect, code: codes[side.name], code_verifier: req.pk.verifier })
await compare('token refused: no DPoP proof', { token: 'no proof' }, (side) => token(side, req.dpop[side.name], body(side), { dpop: null }), (side, x) => view(side, x, () => '<accepted>'))
return void (await exchange(acct, req, codes, { kind: 'token: code after a refusal without a proof' }))
}
if (opts === 'twice') {
const t = await exchange(acct, req, codes, { kind: 'token: code (for another check)' })
await exchange(acct, req, codes, { kind: 'token: the same code again' })
if (t.reference.status !== 200) return
const s = { dpop: req.dpop, tokens: { reference: { access: t.reference.body.access_token }, server: { access: t.server.body.access_token } } }
await getSessionBoth(s, 'getSession after the code was used again')
return void (await compare('token: refresh after the code was used again', { refresh: 'after code reuse' }, (side) => token(side, req.dpop[side.name], { grant_type: 'refresh_token', client_id: req.clientId, refresh_token: t[side.name].body.refresh_token }), (side, x) => view(side, x, tokenBody(side))))
}
await exchange(acct, req, codes, { ...opts, kind: `token refused: ${name}` })
await exchange(acct, req, codes, { kind: `token: code after a refusal (${name})` })
}
/// The revocation endpoint with one thing wrong in its request
/// (spec/OAUTH.md, "Revocation").
export async function oauthRevokeRefused() {
const p = basePar()
const d = dpops(await newKey())
const [name, body, opts] = pick([
['no client_id', { token: 'x' }],
['no token', { client_id: p.client_id }],
['empty token', { client_id: p.client_id, token: '' }],
['bogus token_type_hint', { client_id: p.client_id, token: 'x', token_type_hint: 'bogus' }],
['no nonce', { client_id: p.client_id, token: 'x' }, { retry: false }],
['JSON', JSON.stringify({ client_id: p.client_id, token: 'x' }), { headers: { 'content-type': 'application/json' } }],
['text/plain', 'x', { headers: { 'content-type': 'text/plain' } }],
])
const send = (side) => (typeof body === 'string' ? d[side.name].send(`${issuer(side)}/oauth/revoke`, { method: 'POST', body, ...opts }) : revokeOn(side, d[side.name], body, opts ?? {}))
await compare(`revoke refused: ${name}`, { revoke: body }, send, (side, a) => view(side, a, (b) => b))
}
// ---------------------------------------------------------- the library
/// A client app's own library, @atproto/oauth-client-node, as a loopback
/// client on each side: authorize, the page, callback, getSession, a
/// refresh, signOut, and restore after it. With a server's sign-in hook,
/// the server signs in through it, and of the pages only the redirect's
/// status is compared.
export async function oauthClientLibrary(acct) {
const handle = handleOf(acct)
if (!handle || !acct.password) return
const scope = pick(['atproto', 'atproto transition:generic', 'atproto transition:email'])
const flow = async (side) => {
const out = {}
const store = () => {
const m = new Map()
return { get: async (k) => m.get(k), set: async (k, v) => void m.set(k, v), del: async (k) => void m.delete(k) }
}
const id = clientId({ scope, redirects: [REDIRECT] })
const client = new NodeOAuthClient({
clientMetadata: { client_id: id, scope, redirect_uris: [REDIRECT], response_types: ['code'], grant_types: ['authorization_code', 'refresh_token'], token_endpoint_auth_method: 'none', application_type: 'native', dpop_bound_access_tokens: true },
stateStore: store(),
sessionStore: store(),
handleResolver: side.url,
plcDirectoryUrl: plcUrl,
allowHttp: true,
requestLock: requestLocalLock,
})
const errName = (e) => `${e?.constructor?.name}: ${strip(side, String(e?.message ?? e)).slice(0, 160)}`
let url
try {
url = await client.authorize(handle, { scope })
} catch (e) {
return { authorize: errName(e) }
}
out.authorize = { to: strip(side, url.origin + url.pathname), params: [...url.searchParams.keys()].sort() }
// The reference's page and its API, as a browser drives them.
const throughPage = async () => {
const steps = {}
const b = new Browser()
const pageRes = await b.navigate(url.href)
steps.page = pageRes.status
if (pageRes.status !== 200) return { steps }
const si = await b.api(url.href, '/sign-in', { locale: 'en', identifier: handle, password: acct.password, remember: true })
steps.signIn = si.status
if (si.status !== 200) return { steps }
const c = await b.api(url.href, '/consent', { did: si.json.account.did })
steps.consent = c.status
if (!c.json?.url) return { steps }
return { steps, back: await b.navigate(c.json.url, { site: 'same-origin', referer: url.href }) }
}
const { steps, back } = side === cand && !pageApi() ? { steps: {}, back: await cand.signIn({ identifier: handle, password: acct.password }, url.href, { approve: true }) } : await throughPage()
if (pageApi()) Object.assign(out, steps)
if (!back) return out
out.redirect = back.status
const loc = back.headers.location
if (!loc) return out
let session
try {
session = (await client.callback(new URL(loc).searchParams)).session
} catch (e) {
out.callback = errName(e)
return out
}
out.did = strip(side, session.did)
const gs = async () => {
try {
const r = await session.fetchHandler(GET_SESSION)
return { status: r.status, body: norm(side, await r.json()) }
} catch (e) {
return errName(e)
}
}
out.getSession = await gs()
const info = await session.getTokenInfo(false).catch(errName)
out.tokenInfo = typeof info === 'string' ? info : { scope: info.scope, sub: strip(side, info.sub), iss: strip(side, info.iss), aud: strip(side, String(info.aud)) }
out.refresh = await session.getTokenInfo(true).then(() => 'refreshed', errName)
out.getSessionAfterRefresh = await gs()
out.signOut = await session.signOut().then(() => 'signed out', errName)
out.restore = await client.restore(session.did).then(() => 'restored', (e) => e?.constructor?.name)
return out
}
await compare(`the client library (${scope})`, { client: '@atproto/oauth-client-node', scope }, async (side) => ({ status: 200, out: await flow(side) }), (side, r) => r.out)
}
// ------------------------------------------------------------ departures
/// The departures spec/OAUTH.md lists (spec/OAUTH.md, "Where the reference
/// departs from the specs"): the server held to the spec alone.
export async function oauthDepartures() {
const d = new Dpop(await newKey())
const p = basePar()
const which = pick(['no state', 'empty state', 'a state used before', 'a parameter twice', 'no PAR', ...Object.keys(PAR_CAPS)])
const want = { status: 400, error: 'invalid_request' }
let got
if (which in PAR_CAPS) {
const [change, status] = PAR_CAPS[which]
const q = { ...p, ...change(p) }
got = view(cand, await par(cand, d, q))
return void (await held(which, q, status === 201 ? { status: 201, error: null } : want, got))
}
if (which === 'no state' || which === 'empty state') got = view(cand, await par(cand, d, { ...p, state: which === 'no state' ? undefined : '' }))
else if (which === 'a state used before') {
const first = await par(cand, d, p)
if (first.status !== 201) return void (await fail(cand, 'PAR (spec/OAUTH.md)', p, 201, view(cand, first)))
got = view(cand, await par(cand, d, { ...p, code_challenge: pkce().challenge }))
} else if (which === 'a parameter twice') {
got = view(cand, await d.send(`${issuer(cand)}/oauth/par`, { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: `${new URLSearchParams(p)}&scope=atproto` }))
} else {
const q = new URLSearchParams({ ...p })
const page = await new Browser().navigate(`${issuer(cand)}/oauth/authorize?${q}`)
got = { status: page.status, error: page.data.__errorData?.error ?? null }
}
await held(which, p, want, got)
}
/// PAR's caps (spec/OAUTH.md, "Pushed authorization requests", step 17):
/// each a change to a good request, and whether it is kept (`201`) or
/// refused. The reference keeps them all.
const PAR_CAPS = {
'a state of 1024 bytes': [() => ({ state: fresh(768) }), 201],
'a state of 1025 bytes': [() => ({ state: `${fresh(768)}x` }), 400],
'a code_challenge of 44 characters': [(p) => ({ code_challenge: `${p.code_challenge}A` }), 400],
'a code_challenge of 42 characters': [(p) => ({ code_challenge: p.code_challenge.slice(1) }), 400],
'ui_locales of 16 tags': [() => ({ ui_locales: Array(16).fill('en').join(' ') }), 201],
'ui_locales of 17 tags': [() => ({ ui_locales: Array(17).fill('en').join(' ') }), 400],
'a loopback client_id of 18471 bytes': [() => ({ client_id: loopbackOf(CLIENT_ID_CAP + 1), redirect_uri: 'http://127.0.0.1/', scope: 'atproto' }), 400],
}
async function held(which, request, want, got) {
const g = { status: got.status, error: got.error ?? null }
if (!isDeepStrictEqual(g, want)) await fail(cand, `OAuth departure "${which}" (spec/OAUTH.md, held to the spec)`, request, want, g)
count(`oauth departure: ${which}`, true)
}
// ---------------------------------------------------------------- crashes
let beforeCrash = []
/// Before the server is killed: a fresh nonce for some sessions on each
/// side, and a proof of getSession sent once, to replay after.
export async function oauthBeforeCrash() {
beforeCrash = []
const all = accounts.flatMap((a) => (a.oauth?.sessions ?? []).map((s) => [a, s]))
for (let i = 0; i < Math.min(3, all.length); i++) {
const [acct, s] = pick(all)
await renew(acct, s)
for (const side of sides()) await freshNonce(side, s.dpop[side.name])
const proofs = {}
for (const side of sides()) proofs[side.name] = await proof(s.key, 'GET', `${issuer(side)}${GET_SESSION}`, { nonce: s.dpop[side.name].nonce, accessToken: s.tokens[side.name].access })
// The call before the crash, compared: whether its token was good
// decides what the proof sent again must answer.
const before = await compare('getSession before a crash, its proof to send again', { replay: 'before a restart' }, async (side) => answer(await fetch(`${issuer(side)}${GET_SESSION}`, { headers: { authorization: `DPoP ${s.tokens[side.name].access}`, dpop: proofs[side.name] } })), (side, a) => view(side, a, (b) => norm(side, b)))
beforeCrash.push({ acct, s, proofs, refusedForToken: wwwError(before.server.headers?.['www-authenticate']) === 'invalid_token' })
}
}
/// After the restart (spec/OAUTH.md, "Durability", "Single-use values"):
/// the proofs sent before refused as replayed, the nonce given before
/// taken, and a refresh and getSession. A proof whose call was refused for
/// its token was held in memory alone (spec/OAUTH.md, "DPoP", step 5): sent
/// again after the restart, the server refuses it for its token again,
/// `invalid_token`, where the reference, never restarted, answers
/// `invalid_dpop_proof`; the server is held to the spec alone there.
export async function oauthAfterCrash() {
for (const { acct, s, proofs, refusedForToken } of beforeCrash) {
const again = async (side) => answer(await fetch(`${issuer(side)}${GET_SESSION}`, { headers: { authorization: `DPoP ${s.tokens[side.name].access}`, dpop: proofs[side.name] } }))
if (refusedForToken) {
const a = await again(cand)
const got = { status: a.status, www: wwwError(a.headers?.['www-authenticate']) }
if (got.status !== 401 || got.www !== 'invalid_token') await fail(cand, 'a DPoP proof sent before a crash, again, its call refused for its token then (spec/OAUTH.md, DPoP step 5: held in memory alone)', { replay: 'across a restart' }, { status: 401, www: 'invalid_token' }, got)
count('oauth departure: a proof of a call refused for its token, again after a restart', false)
} else await compare('a DPoP proof sent before a crash, again', { replay: 'across a restart' }, again, (side, a) => view(side, a, (b) => norm(side, b)))
await getSessionBoth(s, 'getSession after a crash, with the nonce given before', { opts: { retry: false } })
if (chance(0.5)) await oauthRefresh(acct)
}
beforeCrash = []
}
// ------------------------------------------------------------- shared
// What checks/oauth-clients.mjs shares with these checks.
export { pageView, apiView, where, par, token, revokeOn, getSessionOn, GET_SESSION, URN, pageUrl, loadPage, signIn, consent, redirectBoth, codeOf, codesOf, exchange, tokenBody, holdToken, getSessionBoth, newRequest, renew, CLIENTS }