chadtmiller.com/monolith
An atproto PDS
0
0
// What the Bluesky app needs beyond the repository (spec/PROXY.md):
// requests forwarded to the services lib/services.mjs runs, with service
// tokens; getServiceAuth; preferences; and the app.bsky methods the server
// serves itself. Each step sends its request to the reference, takes what
// the services got, then sends it to the server and takes what they got, so
// what each side forwarded is its own; both what each side answered and what
// it forwarded are compared, and every service token is held to the spec.
// Sessions are password sessions, app passwords', and OAuth sessions whose
// scopes allow some of the calls (`rpc`, spec/OAUTH-SCOPES.md), each call
// then made with `DPoP` and a proof.
import { isDeepStrictEqual } from 'node:util'
import { gzipSync } from 'node:zlib'
import { verifySignature } from '@atproto/crypto'
import { below, chance, pick, rand, subset, value, word } from '../lib/random.mjs'
import { cand, plcUrl, ref } from '../lib/processes.mjs'
import { fail } from '../lib/plc.mjs'
import { count, differ } from '../lib/report.mjs'
import { accounts, didOf, noteCommit, noteWrite, tokenOf } from '../lib/state.mjs'
import { answerWith, services, takeRequests } from '../lib/services.mjs'
import { noteRefs } from './blobs.mjs'
import { normalize, strip, xrpc } from '../lib/xrpc.mjs'
import { proof, wwwError } from '../lib/oauth.mjs'
import { issuer } from '../lib/server.mjs'
import { handleOf, login, pickSession } from './oauth.mjs'
const SIDES = () => [ref, cand]
/// The user agent every request here is sent with, which no side may pass on.
const UA = 'pds-harness-proxy/1'
/// Request headers a side passes on, but those starting `x-atproto-`.
const FORWARDED = ['accept-language', 'atproto-accept-labelers', 'x-bsky-topics', 'content-type', 'content-encoding']
/// Request headers the harness sends that no side may pass on.
const KEPT_BACK = ['cookie', 'origin', 'referer', 'x-not-forwarded', 'dpop', 'atproto-proxy']
/// The target's response headers a side passes on, but the content type.
const ANSWERED = ['content-language', 'atproto-repo-rev', 'atproto-content-labelers', 'retry-after', 'x-upstream-secret', 'set-cookie']
/// The methods never forwarded (spec/PROXY.md, "Which requests are forwarded").
const PROTECTED = [
'com.atproto.admin.sendEmail', 'com.atproto.identity.requestPlcOperationSignature', 'com.atproto.identity.signPlcOperation',
'com.atproto.identity.updateHandle', 'com.atproto.server.activateAccount', 'com.atproto.server.confirmEmail',
'com.atproto.server.createAppPassword', 'com.atproto.server.deactivateAccount', 'com.atproto.server.getAccountInviteCodes',
'com.atproto.server.getSession', 'com.atproto.server.listAppPasswords', 'com.atproto.server.requestAccountDelete',
'com.atproto.server.requestEmailConfirmation', 'com.atproto.server.requestEmailUpdate', 'com.atproto.server.revokeAppPassword',
'com.atproto.server.updateEmail',
]
/// A DID no directory or service knows.
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
/// An account no server here holds, whose views the AppView answers.
const OTHER = { did: 'did:plc:ewvi7nxzyoun6zhxrhs64oiz', handle: 'other.example.com' }
const SOME_CID = 'bafyreie5737gdxlw5i64vzichcalba3z2v5n6icifvx5xytvske7mr3hpm'
const THIS_YEAR = String(new Date().getUTCFullYear())
const now = () => Date.now() / 1000
let serial = 0
/// One request to `side`, as it is: `{method, path, headers, body, token}`,
/// `path` from `/xrpc/`; a `token` that is `{dpop, access}` is an OAuth
/// session's, sent with `DPoP` and a proof. Answers `{status, headers, text}`.
async function send(side, { method = 'GET', path, headers = {}, body, token }) {
const h = { 'user-agent': UA, 'accept-encoding': 'identity', ...headers }
if (token && typeof token === 'object') return sendDpop(side, token, { method, path, headers: h, body })
if (token) h.authorization = `Bearer ${token}`
try {
const res = await fetch(side.url + path, { method, headers: h, body, redirect: 'manual' })
const text = method === 'HEAD' ? '' : await res.text()
return { status: res.status, headers: Object.fromEntries(res.headers), text }
} catch (err) {
return { status: 0, headers: {}, text: JSON.stringify({ error: `request failed: ${err.message}` }) }
}
}
/// A request with an OAuth access token and a proof, to the side's issuer,
/// retried once with the nonce a `use_dpop_nonce` refusal gives.
async function sendDpop(side, t, { method, path, headers, body }) {
const url = issuer(side) + path
const u = new URL(url)
for (let attempt = 0; ; attempt++) {
const h = { ...headers, authorization: `DPoP ${t.access}`, dpop: await proof(t.dpop.key, method, u.origin + u.pathname, { nonce: t.dpop.nonce, accessToken: t.access }) }
let res
try {
res = await fetch(url, { method, headers: h, body, redirect: 'manual' })
} catch (err) {
return { status: 0, headers: {}, text: JSON.stringify({ error: `request failed: ${err.message}` }) }
}
const text = method === 'HEAD' ? '' : await res.text()
const out = { status: res.status, headers: Object.fromEntries(res.headers), text }
if (out.headers['dpop-nonce']) t.dpop.nonce = out.headers['dpop-nonce']
const wantsNonce = wwwError(out.headers['www-authenticate']) === 'use_dpop_nonce' || parse(text)?.error === 'use_dpop_nonce'
if (!(wantsNonce && attempt === 0)) return out
}
}
const parse = (text) => {
try {
return text ? JSON.parse(text) : null
} catch {
return undefined
}
}
/// Each account's DID on `side`, URL-encoded as in a query, named alike on
/// both sides, and `extra`'s pairs.
const namesOn = (side, extra = []) => [...accounts.map((a) => [encodeURIComponent(didOf(side, a)), `<did:${a.n}>`]), ...extra]
/// A JSON value with what differs between the sides taken out: DIDs and the
/// times the side wrote records this year.
function plain(side, v, extra) {
if (typeof v === 'string') return strip(side, v, extra)
if (Array.isArray(v)) return v.map((x) => plain(side, x, extra))
if (v && typeof v === 'object') {
const out = {}
for (const [k, x] of Object.entries(v)) out[k] = k === 'indexedAt' && typeof x === 'string' && x.startsWith(THIS_YEAR) ? '<written>' : plain(side, x, extra)
return out
}
return v
}
/// What a side answered, with what may differ taken out.
function answerView(side, res, extra) {
const headers = Object.fromEntries(ANSWERED.filter((h) => h in res.headers).map((h) => [h, strip(side, res.headers[h], extra)]))
const lag = 'atproto-upstream-lag' in res.headers
if (res.status >= 400 || res.status === 0) return { status: res.status, error: parse(res.text)?.error ?? null, headers, lag }
const type = res.headers['content-type']?.split(';')[0].trim() ?? null
const json = type === 'application/json' ? parse(res.text) : undefined
return { status: res.status, type, headers, lag, body: json !== undefined ? plain(side, json, extra) : strip(side, res.text, extra) }
}
/// Each signing key, by DID, as a did:key: the `atproto` verification
/// method of the DID's data in the directory.
const keys = new Map()
async function signingKey(did) {
if (!keys.has(did)) {
const r = await fetch(`${plcUrl}/${did}/data`)
const data = r.ok ? await r.json() : null
keys.set(did, data?.verificationMethods?.atproto ?? null)
}
return keys.get(did)
}
/// Every service token's `jti` each side has made.
const jtis = { reference: new Set(), server: new Set() }
/// A service token, held to spec/PROXY.md, "Service tokens": its header,
/// exactly its claims, `exp - iat` (60, or `exp` as asked), `iat` within the
/// window, a new `jti`, `iss` an account here, and a signature by that
/// account's key.
/// Answers its claims with DIDs named and times taken out.
async function tokenView(side, token, window, shownAs, { exp } = {}) {
const what = 'service token (spec/PROXY.md)'
const parts = typeof token === 'string' ? token.split('.') : []
let header, payload
try {
;[header, payload] = parts.slice(0, 2).map((p) => JSON.parse(Buffer.from(p, 'base64url').toString('utf8')))
} catch {}
if (parts.length !== 3 || !header || !payload) return fail(side, what, shownAs, 'a JWT', token)
if (!isDeepStrictEqual(header, { typ: 'JWT', alg: 'ES256K' })) await fail(side, `${what} header`, shownAs, { typ: 'JWT', alg: 'ES256K' }, header)
const { iat, iss, aud, exp: e, lxm, jti, ...rest } = payload
if (Object.keys(rest).length) await fail(side, `${what} claims`, shownAs, 'iat, iss, aud, exp, lxm and jti alone', payload)
if (!Number.isInteger(iat) || iat < Math.floor(window[0]) - 2 || iat > Math.ceil(window[1]) + 2) await fail(side, `${what} iat`, shownAs, `within ${window}`, iat)
if (exp === undefined ? e - iat !== 60 : e !== exp) await fail(side, `${what} exp`, shownAs, exp === undefined ? 'iat + 60' : exp, { iat, exp: e })
if (typeof jti !== 'string' || !jti || jtis[side.name].has(jti)) await fail(side, `${what} jti`, shownAs, 'a string not seen before', jti)
jtis[side.name].add(jti)
const owner = accounts.find((a) => didOf(side, a) === iss)
if (!owner) return fail(side, `${what} iss`, shownAs, 'an account here', iss)
const key = await signingKey(iss)
const [h, p, sig] = parts
let ok = false
try {
ok = !!key && (await verifySignature(key, new TextEncoder().encode(`${h}.${p}`), Buffer.from(sig, 'base64url')))
} catch {}
if (!ok) await fail(side, `${what} signature`, shownAs, `signed by ${iss}'s #atproto key, ${key}`, 'a signature that does not verify')
return { iss: `<did:${owner.n}>`, aud: strip(side, String(aud)), lxm: lxm ?? null }
}
/// What a side forwarded, one request, with what may differ taken out.
async function sentView(side, r, window, shownAs, { jsonBody = false, extra, encoding = false } = {}) {
const h = r.headers
const headers = {}
for (const [k, v] of Object.entries(h)) if (FORWARDED.includes(k) || k.startsWith('x-atproto-')) headers[k] = strip(side, String(v), extra)
if (encoding) headers['accept-encoding'] = h['accept-encoding'] ?? null
const auth = h.authorization
let token = null
if (auth !== undefined) token = auth.startsWith('Bearer ') ? await tokenView(side, auth.slice(7), window, shownAs) : { unexpected: auth }
const body = !r.body.length ? null : jsonBody ? plain(side, parse(r.body.toString('utf8')) ?? r.body.toString('utf8'), extra) : r.body.toString('base64')
return {
service: r.service,
method: r.method,
path: strip(side, r.path, namesOn(side, extra)),
headers,
keptBack: KEPT_BACK.filter((k) => k in h),
agent: Object.values(h).includes(UA),
body,
token,
}
}
/// Send `request(side)` to each side in turn, the services answering
/// `answer(side, request)`, and compare what each answered and forwarded.
/// `opts.extra(side)` names more strings alike on both sides; `opts.answer`
/// and `opts.sent` change a side's view of its answer or of a forwarded
/// request before they are compared. Answers each side's `{res, fwd}`.
async function exchange(kind, shownAs, request, answer, opts = {}) {
const out = {}
const views = {}
try {
for (const side of SIDES()) {
takeRequests()
answerWith((r) => answer(side, r))
const t0 = now()
const req = request(side)
const res = await send(side, req)
const window = [t0, now()]
const fwd = takeRequests()
const extra = opts.extra?.(side) ?? []
const sent = []
for (const r of fwd) sent.push(await sentView(side, r, window, shownAs, { ...opts, extra }))
let a = answerView(side, res, extra)
if (opts.answer) a = await opts.answer(side, a, res, window)
// An OAuth call's answer: its nonce, its `WWW-Authenticate` error, and
// the scope a refusal names (spec/OAUTH-SCOPES.md, "Proxied calls").
if (req.token && typeof req.token === 'object') {
a = { ...(typeof a === 'object' ? a : { answer: a }), nonce: 'dpop-nonce' in res.headers, www: wwwError(res.headers['www-authenticate']) }
if (parse(res.text)?.error === 'ScopeMissingError') a.message = parse(res.text)?.message ?? null
}
views[side.name] = { answer: a, sent: opts.sent ? opts.sent(sent) : sent }
out[side.name] = { res, fwd }
}
} finally {
answerWith()
}
if (!isDeepStrictEqual(views.reference, views.server)) await differ(kind, shownAs, views.reference, views.server)
count(kind, out.reference.res.status < 400 && out.reference.res.status > 0)
return out
}
/// A path with its query: `/xrpc/<method>?<query>`.
const xrpcPath = (method, query) => `/xrpc/${method}${query ? `?${query}` : ''}`
const qs = (params) =>
Object.entries(params)
.flatMap(([k, v]) => (Array.isArray(v) ? v : [v]).map((x) => `${encodeURIComponent(k)}=${encodeURIComponent(x)}`))
.join('&')
// Sessions
// --------
/// Each account's sessions made with an app password here, privileged or
/// not, by kind: `{plain, privileged}`, each `{reference, server}` access
/// tokens, or null where the account's token cannot make app passwords.
const appSessions = new Map()
async function appSessionsOf(acct) {
if (appSessions.has(acct)) return appSessions.get(acct)
const made = { plain: null, privileged: null }
for (const kind of ['plain', 'privileged']) {
const tokens = {}
const name = `proxy ${kind} ${++serial}`
const statuses = {}
for (const side of SIDES()) {
const ap = await send(side, { method: 'POST', path: '/xrpc/com.atproto.server.createAppPassword', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name, privileged: kind === 'privileged' }), token: tokenOf(side, acct) })
statuses[side.name] = ap.status
const password = parse(ap.text)?.password
if (ap.status !== 200 || !password) continue
const s = await send(side, { method: 'POST', path: '/xrpc/com.atproto.server.createSession', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ identifier: didOf(side, acct), password }) })
tokens[side.name] = parse(s.text)?.accessJwt
}
if (statuses.reference !== statuses.server) await differ('createAppPassword', { name, privileged: kind === 'privileged' }, statuses.reference, statuses.server)
if (tokens.reference && tokens.server) made[kind] = tokens
}
appSessions.set(acct, made)
return made
}
/// Loopback clients whose scopes allow some of the calls the steps make,
/// to the services they go to, as `rpc` names them (spec/OAUTH-SCOPES.md,
/// "What a scope allows", "What each method needs", "Proxied calls");
/// `transition:generic` allows any but chat's, which `transition:chat.bsky`
/// adds.
const proxyClients = () => {
const aud = (did, id) => `${did}#${id}`.replace(/%/g, '%25').replace(/#/g, '%23')
const appview = aud(services.appview.did, 'bsky_appview')
return [
'atproto transition:generic',
'atproto transition:generic transition:chat.bsky',
`atproto rpc:app.bsky.feed.getTimeline?aud=* rpc:app.bsky.actor.getPreferences?aud=${appview} rpc:app.bsky.actor.putPreferences?aud=*`,
`atproto rpc:app.bsky.feed.getPosts?aud=${appview} rpc:chat.bsky.convo.listConvos?aud=${aud(services.chat.did, 'bsky_chat')} rpc:com.example.custom.thing?aud=*`,
`atproto rpc?lxm=app.bsky.feed.getFeed&lxm=app.bsky.feed.getFeedSkeleton&lxm=app.bsky.actor.getProfile&aud=* rpc:app.bsky.notification.registerPush?aud=${aud(services.appview.did, 'bsky_notif')}`,
`atproto rpc:app.bsky.graph.muteActor?aud=${appview} rpc:com.example.custom.do?aud=${aud(services.elsewhere.did, 'bsky_x')} rpc:app.bsky.unspecced.getConfig?aud=*`,
'atproto',
].map((scope) => ({ scope, redirects: ['http://127.0.0.1/callback'] }))
}
/// An OAuth session of the account: one it has, or a new one with a client of `proxyClients`.
async function oauthSessionOf(acct) {
if (!handleOf(acct)) return null
const s = await pickSession(acct)
if (s && chance(0.5)) return s
return (await login(acct, { client: pick(proxyClients()), reject: false, narrow: false })) ?? s
}
/// A session of the account: its own token, an app password's, or an OAuth
/// session's, whose `token(side)` is `{dpop, access}`.
async function sessionOf(acct, kinds = ['full', 'plain', 'privileged', 'oauth']) {
const kind = pick(kinds)
if (kind === 'full') return { kind, token: (side) => tokenOf(side, acct) }
if (kind === 'oauth') {
const s = await oauthSessionOf(acct)
if (s) return { kind: `oauth ${s.scope}`, token: (side) => ({ dpop: s.dpop[side.name], access: s.tokens[side.name].access }) }
return { kind: 'full', token: (side) => tokenOf(side, acct) }
}
const s = (await appSessionsOf(acct))[kind]
return s ? { kind, token: (side) => s[side.name] } : { kind: 'full', token: (side) => tokenOf(side, acct) }
}
// Targets
// -------
/// An `atproto-proxy` header that names a service the sides reach.
const goodTarget = () =>
pick([
() => `${services.appview.did}#bsky_appview`,
() => `${services.appview.did}#bsky_notif`,
() => `${services.chat.did}#bsky_chat`,
() => `${services.elsewhere.did}#atproto_labeler`,
() => `${services.elsewhere.did}#bsky_x`,
() => `${services.elsewhere.did}#ip`,
() => `${services.elsewhere.did}#full`,
])()
/// An `atproto-proxy` header that does not, by why.
const badTargets = () => ({
'no DID': `#bsky_chat`,
'no service id': services.chat.did,
'empty service id': `${services.chat.did}#`,
'two #': `${services.chat.did}#a#b`,
'a space': `${services.chat.did}#bsky chat`,
'a DID the directory does not know': `${NOBODY}#bsky_chat`,
'a did:web whose document is not found': `did:web:localhost%3A${services.chat.port}#x`,
'a did:web where nothing listens': 'did:web:localhost%3A1#x',
'a document of another DID': `${services.idMismatch.did}#x`,
'a document with an entry without a type': `${services.untyped.did}#x`,
'a did:key': 'did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK#x',
'a did:example': 'did:example:abc#x',
'not a DID': 'notadid#x',
'a DID in upper case': `${services.chat.did.toUpperCase()}#bsky_chat`,
'no such service': `${services.elsewhere.did}#nope`,
'a service id in another case': `${services.elsewhere.did}#Bsky_X`,
'a service in upper case, unreachable': `${services.elsewhere.did}#BSKY_X`,
'an ftp endpoint': `${services.elsewhere.did}#ftp`,
'an HTTP: endpoint': `${services.elsewhere.did}#upper`,
'an object endpoint': `${services.elsewhere.did}#object`,
'an endpoint with a path': `${services.elsewhere.did}#path`,
'an endpoint with a query': `${services.elsewhere.did}#query`,
'an endpoint with a fragment': `${services.elsewhere.did}#fragment`,
'an endpoint where nothing listens': `${services.elsewhere.did}#down`,
'a did:web with a path': `${services.elsewhere.did}:a#atproto_labeler`,
})
// Forwarding
// ----------
const FORWARD_GET = ['app.bsky.feed.getPosts', 'app.bsky.graph.getFollows', 'app.bsky.unspecced.getConfig', 'chat.bsky.convo.listConvos', 'com.example.custom.thing', 'App.Bsky.Feed.GetLikes', '9a.b.c', 'foo', 'a-b.c-d']
const FORWARD_POST = ['app.bsky.graph.muteActor', 'app.bsky.notification.updateSeen', 'chat.bsky.convo.sendMessage', 'com.example.custom.do']
/// A query string, its bytes as a client might send them.
function query() {
const parts = []
for (let i = below(4); i > 0; i--) {
const k = pick(['uris', 'limit', 'cursor', 'q', 'actor', 'x'])
const v = pick([() => String(below(100)), () => 'at://did:plc:abc/app.bsky.feed.post/3k', () => word(), () => 'a b', () => 'did:plc:ewvi7nxzyoun6zhxrhs64oiz'])()
parts.push(`${k}=${chance(0.7) ? encodeURIComponent(v) : v.replace(/ /g, '+')}`)
}
return parts.join('&')
}
/// Request headers: some each side passes on, some it does not.
function requestHeaders() {
const h = {}
if (chance(0.4)) h['accept-language'] = pick(['fr', 'en-US,en;q=0.9', 'ja'])
if (chance(0.4)) h['atproto-accept-labelers'] = pick(['did:plc:ar7c4by46qjdydhdevvrndac;redact', 'did:plc:ar7c4by46qjdydhdevvrndac, did:web:labeler.example.com'])
if (chance(0.3)) h[`x-atproto-${pick(['thing', 'debug', 'a-b'])}`] = pick(['1', 'yes', 'a b'])
if (chance(0.2)) h['x-bsky-topics'] = 'a,b'
for (const k of subset(['cookie', 'origin', 'referer', 'x-not-forwarded', 'dpop'], 0.2)) h[k] = k === 'origin' || k === 'referer' ? 'http://app.example.com' : 'v'
if (chance(0.3)) h['accept-encoding'] = pick(['gzip', 'gzip, deflate, br'])
return h
}
/// What a service answers, the same for both sides.
function serviceAnswer() {
const status = pick([200, 200, 200, 200, 201, 202, 204, 301, 400, 401, 403, 404, 413, 418, 429, 500, 501, 502, 503, 504])
const type = pick(['application/json', 'application/json', 'application/json; charset=utf-8', 'text/plain; charset=utf-8', 'application/vnd.ipld.car', 'application/problem+json', null])
const headers = {}
if (type) headers['content-type'] = type
if (chance(0.3)) headers['content-language'] = 'de'
if (chance(0.3)) headers['atproto-repo-rev'] = '3l' + pick(['abcdefghijk', 'zzzzzzzzzzz'])
if (chance(0.3)) headers['atproto-content-labelers'] = 'did:plc:ar7c4by46qjdydhdevvrndac'
if (chance(0.3)) headers['retry-after'] = '5'
if (chance(0.3)) headers['x-upstream-secret'] = 's'
if (chance(0.2)) headers['set-cookie'] = 'a=b'
if (status === 301) headers.location = 'http://elsewhere.example.com/'
let body
if (status === 204 || status === 301) body = ''
else if (status >= 400) body = pick([() => JSON.stringify({ error: pick(['Custom', 'NotFound', 'InvalidRequest']), message: 'm' }), () => JSON.stringify({ error: 'OnlyName' }), () => JSON.stringify({ message: 'only message' }), () => JSON.stringify({ error: 5 }), () => 'not json', () => ''])()
else body = chance(0.7) ? JSON.stringify({ answer: value(), n: below(10) }) : pick(['plain text', '', '\u00e9t\u00e9'])
return { status, headers, body }
}
/// A request for a method neither side serves, with or without a header
/// naming the target, and the service answering anything (spec/PROXY.md,
/// "Environment", "Which requests are forwarded", "The target", "What is
/// sent", "What is answered").
export async function forwarded(acct) {
const method = pick(['GET', 'GET', 'GET', 'POST', 'POST', 'HEAD'])
const nsid = pick(method === 'POST' ? FORWARD_POST : FORWARD_GET)
const q = chance(0.6) ? query() : ''
const headers = requestHeaders()
if (chance(0.6)) headers['atproto-proxy'] = chance(0.1) ? '' : goodTarget()
let body
if (method === 'POST') {
const r = rand()
if (r < 0.5) {
headers['content-type'] = 'application/json'
body = JSON.stringify({ actor: OTHER.did, extra: value() })
} else if (r < 0.65) {
headers['content-type'] = 'application/json'
headers['content-encoding'] = 'gzip'
body = gzipSync(JSON.stringify({ seenAt: '2020-01-01T00:00:00.000Z' }))
} else if (r < 0.8) {
headers['content-type'] = 'application/octet-stream'
body = Buffer.from([0, 1, 2, 255, below(256)])
} else if (r < 0.9) {
headers['content-type'] = 'text/plain; charset=utf-8'
body = word()
}
}
// chat.bsky methods need a full or privileged session; the refused step
// sends them with others.
const session = await sessionOf(acct, nsid.toLowerCase().startsWith('chat.bsky.') ? ['full', 'privileged', 'oauth'] : ['full', 'plain', 'privileged', 'oauth', 'oauth'])
const a = serviceAnswer()
const path = xrpcPath(nsid, q)
const shownAs = { method, path, headers, body: body === undefined ? undefined : String(body).slice(0, 80), session: session.kind, serviceAnswers: a }
const kind = `forwarded ${method}${'atproto-proxy' in headers ? ' with atproto-proxy' : ''}`
await exchange(kind, shownAs, (side) => ({ method, path, headers, body, token: session.token(side) }), () => a, { encoding: true })
}
// Refused
// -------
/// A request that must not be forwarded, or not as asked: each malformed or
/// unreachable target, other HTTP methods, malformed paths, wrong tokens,
/// privileged methods, methods served in another case, and methods never
/// forwarded (spec/PROXY.md, "Which requests are forwarded", "The target",
/// "What is answered").
export async function refused(acct) {
const token = (side) => tokenOf(side, acct)
const answer = () => ({ status: 200, headers: { 'content-type': 'application/json' }, body: '{"ok":true}' })
const r = rand()
if (r < 0.35) {
const [why, target] = pick(Object.entries(badTargets()))
const noToken = chance(0.15)
const path = xrpcPath(pick(FORWARD_GET), '')
return void (await exchange(`refused: ${why}${noToken ? ', no token' : ''}`, { path, 'atproto-proxy': target, noToken }, (side) => ({ path, headers: { 'atproto-proxy': target }, token: noToken ? undefined : token(side) }), answer))
}
if (r < 0.45) {
const which = pick(['none', 'refresh', 'garbage', 'basic'])
const headers = chance(0.5) ? { 'atproto-proxy': goodTarget() } : {}
const path = xrpcPath(pick(FORWARD_GET), '')
const tok = (side) => (which === 'refresh' ? acct.sides[side.name].refresh : which === 'garbage' ? 'abc.def.ghi' : which === 'none' ? undefined : token(side))
const extra = which === 'basic' ? { authorization: 'Basic YWRtaW46eA==' } : {}
return void (await exchange(`refused: token ${which}`, { path, headers, token: which }, (side) => ({ path, headers: { ...headers, ...extra }, token: which === 'basic' ? undefined : tok(side) }), answer))
}
if (r < 0.52) {
const method = pick(['PUT', 'DELETE', 'PATCH'])
const path = xrpcPath(pick(FORWARD_GET), '')
return void (await exchange(`refused: ${method}`, { method, path }, (side) => ({ method, path, token: token(side) }), answer))
}
if (r < 0.6) {
const name = pick(['a..b', 'a.b/c', '.a', 'a.', '-a.b', 'a.b//'])
const path = `/xrpc/${name}`
return void (await exchange('refused: a malformed method name', { path }, (side) => ({ path, token: token(side) }), answer))
}
if (r < 0.72) {
const s = await sessionOf(acct, ['plain', 'privileged'])
const nsid = pick(['chat.bsky.convo.listConvos', 'CHAT.BSKY.convo.getLog', 'Chat.Bsky.Actor.DeclareStuff'])
const headers = chance(0.5) ? { 'atproto-proxy': `${services.chat.did}#bsky_chat` } : {}
const path = xrpcPath(nsid, '')
return void (await exchange(`chat with an app password's session, ${s.kind}`, { path, headers, session: s.kind }, (side) => ({ path, headers, token: s.token(side) }), answer, { encoding: true }))
}
if (r < 0.85) {
// Served by both sides, in another case: answered, not forwarded.
const [nsid, served, tok] = pick([
['com.atproto.server.DESCRIBESERVER', 'com.atproto.server.describeServer', false],
['com.atproto.server.getsession', 'com.atproto.server.getSession', true],
['app.bsky.actor.GETPREFERENCES', 'app.bsky.actor.getPreferences', true],
])
const path = xrpcPath(nsid, '')
const headers = chance(0.5) ? { 'atproto-proxy': goodTarget() } : {}
return void (await exchange(`a method served, in another case`, { path, headers }, (side) => ({ path, headers, token: tok ? token(side) : undefined }), answer, {
answer: (side, a, res) => (res.status === 200 ? normalize(side, { status: 200, body: parse(res.text) }, served) : a),
}))
}
// Methods never forwarded: the reference serves them all, so only that
// neither side forwards one is compared. They go by GET, so that none is
// made: a procedure by GET is refused, and deactivateAccount with `{}`
// would deactivate the account.
const nsid = PROTECTED[below(PROTECTED.length)]
const cased = pick([nsid, nsid.toUpperCase(), nsid.toLowerCase()])
const path = xrpcPath(cased, '')
const headers = { 'atproto-proxy': goodTarget() }
await exchange('a method never forwarded', { path, headers }, (side) => ({ path, headers, token: token(side) }), answer, {
answer: () => 'not compared: the reference serves it',
})
}
// getServiceAuth
// --------------
/// getServiceAuth with `aud`, `lxm` and `exp` from each rule, by every kind
/// of session; each token held to the spec (spec/PROXY.md, "getServiceAuth",
/// "Service tokens").
export async function serviceAuth(acct) {
const t = Math.floor(now())
const params = {}
if (chance(0.97)) {
const good = [() => services.chat.did, () => services.appview.did, () => `${services.chat.did}#bsky_chat`, () => 'did:web:example.com', () => `${NOBODY}#bsky-x.y`, () => 'did:web:localhost%3A8080#x']
const bad = [
() => 'did:example:abc', () => 'did:key:z6MkhaXgBZDvotDkL5257faiztiGiC2QtKLGpbnnEGta2doK', () => 'did:plc:abc',
() => `${services.chat.did}#`, () => 'did:web:example.com%3A8080', () => 'did:web:a:b', () => 'nope', () => `${NOBODY}#a b`,
]
params.aud = pick(chance(0.75) ? good : bad)()
}
if (chance(0.6)) {
const p = PROTECTED[below(PROTECTED.length)]
params.lxm = chance(0.6) ? pick(['app.bsky.feed.getPosts', 'com.atproto.repo.getRecord', 'chat.bsky.convo.listConvos']) : pick(['CHAT.BSKY.x.y', 'com.atproto.server.createAccount', 'COM.ATPROTO.SERVER.createaccount', p, p.toUpperCase(), '*', 'not an nsid'])
}
if (chance(0.5)) params.exp = chance(0.5) ? pick([t + 30, t + 1800]) : pick([0, -1, t - 30, t + 90, t + 3700, 'soon', `${t + 10}.5`])
const s = chance(0.05) ? { kind: 'none', token: () => undefined } : chance(0.03) ? { kind: 'refresh', token: (side) => acct.sides[side.name].refresh } : await sessionOf(acct)
const path = xrpcPath('com.atproto.server.getServiceAuth', qs(params))
const exp = Number.isInteger(params.exp) && params.exp !== 0 ? params.exp : params.exp === 0 ? 0 : undefined
if (chatInAnotherCase(s, params.lxm) && params.aud !== undefined) return void (await chatHeldToSpec(s, path, params))
await exchange(`getServiceAuth${s.kind === 'full' ? '' : `, ${s.kind} session`}`, { params, session: s.kind }, (side) => ({ path, token: s.token(side) }), () => ({ status: 500, headers: {}, body: '' }), {
answer: async (side, a, res, window) => {
if (res.status !== 200) return a
const token = parse(res.text)?.token
return { status: 200, token: await tokenView(side, token, window, { params }, { exp }) }
},
})
}
/// Whether a call of method `lxm` with session `s` is one where the
/// reference departs from spec/OAUTH-SCOPES.md: a `chat.bsky.` method named
/// in another case, with an OAuth scope of `transition:generic` but not
/// `transition:chat.bsky`, which the reference's case-minding prefix check
/// allows (probed: getServiceAuth of `Chat.Bsky.convo.getLog` answers a
/// token).
function chatInAnotherCase(s, lxm) {
if (typeof lxm !== 'string' || !s.kind.startsWith('oauth ')) return false
const scope = s.kind.slice('oauth '.length).split(' ')
return lxm.toLowerCase().startsWith('chat.bsky.') && !lxm.startsWith('chat.bsky.') && scope.includes('transition:generic') && !scope.includes('transition:chat.bsky')
}
/// That departure, held to the spec on the server alone: getServiceAuth of
/// the method, and the method forwarded to the chat service, each `403
/// ScopeMissingError`, with nothing sent on (spec/OAUTH-SCOPES.md, "What a
/// scope allows", "Proxied calls").
async function chatHeldToSpec(s, path, params) {
const forwardedPath = xrpcPath('Chat.Bsky.convo.getLog', '')
for (const [what, req] of [['getServiceAuth', { path }], ['a chat method forwarded, in another case', { path: forwardedPath, headers: { 'atproto-proxy': `${services.chat.did}#bsky_chat` } }]]) {
takeRequests()
const res = await send(cand, { ...req, token: s.token(cand) })
const sent = takeRequests()
const error = parse(res.text)?.error ?? null
if (res.status !== 403 || error !== 'ScopeMissingError' || sent.length) await differ(`the server's ${what} with ${s.kind}`, { params, path: req.path }, '403 ScopeMissingError, nothing sent on', { status: res.status, error, sent: sent.length }, 'spec/OAUTH-SCOPES.md: transition:generic allows no chat.bsky. method, in any case')
}
count('chat in another case, transition:generic alone', false)
}
/// A step for that departure: a session of `transition:generic` alone,
/// signed in through the compared flow, then held to the spec as above.
export async function chatCase(acct) {
if (!handleOf(acct)) return
const s = await login(acct, { client: proxyClients()[0], reject: false, narrow: false })
if (!s) return
const params = { aud: `${services.chat.did}#bsky_chat`, lxm: pick(['Chat.Bsky.convo.getLog', 'CHAT.BSKY.convo.sendMessage', 'chat.Bsky.actor.getActorMetadata']) }
await chatHeldToSpec({ kind: `oauth ${s.scope}`, token: (side) => ({ dpop: s.dpop[side.name], access: s.tokens[side.name].access }) }, xrpcPath('com.atproto.server.getServiceAuth', qs(params)), params)
}
// Preferences
// -----------
/// A birth date `years` ago, and more than two days from its anniversary.
function birthDate(years) {
const d = new Date()
d.setUTCFullYear(d.getUTCFullYear() - years)
d.setUTCDate(d.getUTCDate() + (chance(0.5) ? 1 : -1) * (3 + below(150)))
return `${d.toISOString().slice(0, 10)}T12:00:00.000Z`
}
const atUri = () => `at://${OTHER.did}/app.bsky.feed.generator/${pick(['whats-hot', 'a', 'b'])}`
/// A preference, valid or not.
function preference() {
const D = 'app.bsky.actor.defs#'
return pick([
() => ({ $type: `${D}adultContentPref`, ...(chance(0.7) ? { enabled: chance(0.5) } : {}) }),
() => ({ $type: `${D}contentLabelPref`, label: pick(['nsfw', 'gore']), visibility: pick(['hide', 'warn', 'ignore', 'odd']) }),
() => ({ $type: `${D}savedFeedsPrefV2`, items: [{ id: String(below(9)), type: pick(['feed', 'timeline', 'other']), value: atUri(), pinned: chance(0.5) }] }),
() => ({ $type: `${D}savedFeedsPref`, pinned: [atUri()], saved: [] }),
() => ({ $type: `${D}personalDetailsPref`, ...(chance(0.8) ? { birthDate: birthDate(pick([10, 12, 13, 15, 16, 17, 18, 30])) } : {}) }),
() => ({ $type: `${D}declaredAgePref`, isOverAge13: true }),
() => ({ $type: `${D}feedViewPref`, feed: 'home', ...(chance(0.5) ? { hideReplies: chance(0.5) } : {}) }),
() => ({ $type: `${D}threadViewPref`, ...(chance(0.7) ? { sort: pick(['oldest', 'weird']) } : {}) }),
() => ({ $type: `${D}interestsPref`, tags: ['art', word()] }),
() => ({ $type: `${D}mutedWordsPref`, items: [{ value: word() || 'x', targets: [pick(['content', 'tag', 'other'])] }] }),
() => ({ $type: `${D}hiddenPostsPref`, items: [`at://${OTHER.did}/app.bsky.feed.post/3k`] }),
() => ({ $type: 'app.bsky.custom.pref', data: value(), extra: word() }),
() => ({ $type: pick(['app.bsky', 'app.bsky.x y']), n: below(9) }),
])()
}
/// A preference that is refused, by why.
function badPreference() {
const D = 'app.bsky.actor.defs#'
return pick([
['a field of the wrong type', { $type: `${D}adultContentPref`, enabled: 'yes' }],
['a required field missing', { $type: `${D}savedFeedsPrefV2`, items: [{ type: 'feed' }] }],
['no $type', { enabled: true }],
['not an object', pick(['x', null, 5])],
['a $type not a string', { $type: 5 }],
['another namespace', { $type: pick(['com.example.pref', 'app.bskyx.pref', '']) }],
['a birthDate not a datetime', { $type: `${D}personalDetailsPref`, birthDate: pick(['yesterday', '2008-11-10']) }],
['a string too long', { $type: `${D}mutedWordsPref`, items: [{ value: 'x'.repeat(10001), targets: ['content'] }] }],
])
}
/// putPreferences of a random list, valid or not, or getPreferences, with
/// every kind of session, sometimes with an `atproto-proxy` header
/// (spec/PROXY.md, "Preferences", "putPreferences", "getPreferences", "Data").
export async function preferences(acct) {
const s = chance(0.03) ? { kind: 'none', token: () => undefined } : await sessionOf(acct)
const headers = chance(0.12) ? { 'atproto-proxy': pick([() => `${services.appview.did}#bsky_appview`, goodTarget, () => 'garbage', () => ''])() } : {}
if (chance(0.55)) {
let list = Array.from({ length: below(5) }, preference)
let why = ''
if (chance(0.15)) {
const [w, bad] = badPreference()
why = `, ${w}`
list.splice(below(list.length + 1), 0, bad)
}
const body = chance(0.03) ? {} : { preferences: list, ...(chance(0.1) ? { other: 1 } : {}) }
const shownAs = { putPreferences: body, session: s.kind, headers }
await exchange(`putPreferences${why}${s.kind === 'full' ? '' : `, ${s.kind} session`}`, shownAs, (side) => ({ method: 'POST', path: xrpcPath('app.bsky.actor.putPreferences'), headers: { ...headers, 'content-type': 'application/json' }, body: JSON.stringify(body), token: s.token(side) }), () => ({ status: 200, headers: {}, body: '' }))
}
const a = { status: 200, headers: { 'content-type': 'application/json' }, body: JSON.stringify({ preferences: [{ $type: 'app.bsky.actor.defs#adultContentPref', enabled: true }] }) }
const q = chance(0.1) ? 'x=1' : ''
await exchange(`getPreferences${s.kind === 'full' ? '' : `, ${s.kind} session`}`, { getPreferences: {}, session: s.kind, headers }, (side) => ({ path: xrpcPath('app.bsky.actor.getPreferences', q), headers, token: s.token(side) }), () => a)
}
// Read after write
// ----------------
/// Write `record` with `nsid` to the account's repository on both sides,
/// and note it as the other steps do. Only that both sides take it is
/// compared: the reference checks `app.bsky` records against its lexicons
/// and answers `validationStatus: "valid"`, which spec/REPO.md does not ask
/// of the server.
async function write(acct, nsid, collection, rkey, record) {
const [a, b] = await Promise.all(SIDES().map((side) => xrpc(side, nsid, { body: { repo: didOf(side, acct), collection, rkey, record }, token: acct })))
const kind = `${nsid.split('.').pop()} of ${collection}`
if (a.status !== 200 || b.status !== 200) await differ(kind, { collection, rkey, record }, normalize(ref, a, nsid), normalize(cand, b, nsid), a.status !== 200 ? 'the reference fails the check it is held to' : undefined)
count(kind, true)
noteWrite(acct, collection, rkey, a)
noteCommit(ref, acct, a)
noteCommit(cand, acct, b)
// The blobs its record references are the account's, as listBlobs lists them.
noteRefs(acct, a, [{ rkey: `${collection}/${rkey}`, value: record }], [record])
}
/// A record key that is a TID, the `serial`th, as `app.bsky.feed.post`
/// needs.
const tidKey = (n) => `3p${n.toString(32).replace(/./g, (c) => '234567abcdefghijklmnopqrstuvwxyz'[parseInt(c, 32)]).padStart(11, '2')}`
/// A blob uploaded to both sides, its ref.
async function blob(acct) {
const bytes = Buffer.concat([Buffer.from('89504e470d0a1a0a', 'hex'), Buffer.from(`proxy ${below(1000)}`)])
let ref_
for (const side of SIDES()) {
const r = await send(side, { method: 'POST', path: '/xrpc/com.atproto.repo.uploadBlob', headers: { 'content-type': 'image/png' }, body: bytes, token: tokenOf(side, acct) })
ref_ ??= parse(r.text)?.blob
}
return ref_
}
/// Each side's latest commit's rev for the account.
async function revs(acct) {
const out = {}
for (const side of SIDES()) out[side.name] = parse((await send(side, { path: xrpcPath('com.atproto.sync.getLatestCommit', qs({ did: didOf(side, acct) })) })).text)?.rev
return out
}
const PAST = ['2001-01-01T00:00:00.000Z', '2010-06-01T00:00:00.000Z', '2020-01-01T00:00:00.000Z']
const FUTURE = '2999-01-01T00:00:00.000Z'
const basic = (did, handle, valid) => ({ did, ...(valid ? { handle } : {}), displayName: 'Stale', avatar: 'https://stale.example.com/a.jpg' })
const postView = (did, handle, x, valid) => ({ uri: `at://${did}/app.bsky.feed.post/3kold${x.n}`, cid: SOME_CID, author: basic(did, handle, valid), record: { $type: 'app.bsky.feed.post', text: 'old', createdAt: x.at }, indexedAt: x.at })
/// The account's profile and posts written, then a read-after-write method,
/// the AppView answering views of the account and others with a rev from
/// before the writes, after them, or none; images as the CDN pattern makes
/// them (spec/PROXY.md, "Other methods the server serves for the app", "Read
/// after write", "Environment", "Data").
export async function readAfterWrite(acct) {
// The account needs a record from before, for a rev to mean anything.
if (!acct.records.size || chance(0.1)) await write(acct, 'com.atproto.repo.createRecord', 'com.example.note', `pb${++serial}`, { $type: 'com.example.note', text: 'before' })
const before = await revs(acct)
const img = chance(0.5) ? await blob(acct) : null
if (chance(0.5)) {
const profile = { $type: 'app.bsky.actor.profile' }
if (chance(0.7)) profile.displayName = pick(['New name', 'Ünïcode', ''])
if (chance(0.5)) profile.description = 'new description'
if (img && chance(0.7)) profile.avatar = img
if (img && chance(0.4)) profile.banner = img
await write(acct, 'com.atproto.repo.putRecord', 'app.bsky.actor.profile', 'self', profile)
}
for (let i = below(3); i > 0; i--) {
const post = { $type: 'app.bsky.feed.post', text: word(), createdAt: '2026-01-01T00:00:00.000Z' }
const r = rand()
if (img && r < 0.3) post.embed = { $type: 'app.bsky.embed.images', images: [{ image: img, alt: 'alt', ...(chance(0.5) ? { aspectRatio: { width: 3, height: 2 } } : {}) }] }
else if (r < 0.5) post.embed = { $type: 'app.bsky.embed.external', external: { uri: 'https://example.com/', title: 't', description: 'd', ...(img && chance(0.5) ? { thumb: img } : {}) } }
await write(acct, 'com.atproto.repo.createRecord', 'app.bsky.feed.post', tidKey(++serial), post)
}
const after = await revs(acct)
const which = pick(['before', 'before', 'before', 'after', 'none', 'ancient', 'garbage'])
const revOf = (side) => ({ before: before[side.name], after: after[side.name], none: null, ancient: '2222222222222', garbage: 'zzzz' })[which]
const valid = chance(0.9)
const json = chance(0.92)
const method = pick(['getProfile', 'getProfiles', 'getTimeline', 'getAuthorFeed', 'getActorLikes'])
const nsid = method.startsWith('getProfile') ? `app.bsky.actor.${method}` : `app.bsky.feed.${method}`
const byHandle = chance(0.5)
const params = (side) => (method === 'getProfile' ? { actor: byHandle ? acct.handle : didOf(side, acct) } : method === 'getProfiles' ? { actors: [didOf(side, acct), OTHER.did] } : method === 'getTimeline' ? {} : { actor: didOf(side, acct) })
const headers = requestHeaders()
// The view the AppView answers, drawn once and made for each side's DID.
const ownFirst = chance(0.7)
const shape = Array.from({ length: below(4) }, (_, i) => ({ own: i === 0 ? ownFirst : chance(0.5), repost: chance(0.2), at: pick(i === 0 && chance(0.2) ? [FUTURE] : PAST), n: below(9) }))
const profileOwn = chance(0.8)
const view = (side) => {
const did = didOf(side, acct)
const handle = acct.handle
if (method === 'getProfile') return profileOwn ? { did, handle, displayName: 'Stale', description: 'stale', avatar: 'https://stale.example.com/a.jpg', banner: 'https://stale.example.com/b.jpg', followersCount: 3, ...(valid ? {} : { handle: undefined }) } : { did: OTHER.did, handle: OTHER.handle, displayName: 'Other' }
if (method === 'getProfiles') return { profiles: [{ did, ...(valid ? { handle } : {}), description: 'stale' }, { did: OTHER.did, handle: OTHER.handle }] }
return {
cursor: 'c1',
feed: shape.map((x) => ({
post: x.own ? postView(did, handle, x, valid) : postView(OTHER.did, OTHER.handle, x, true),
...(x.repost ? { reason: { $type: 'app.bsky.feed.defs#reasonRepost', by: basic(did, handle, true), indexedAt: x.at } } : {}),
})),
}
}
const status = pick([200, 200, 200, 201, 203])
const more = subset([['content-language', 'de'], ['atproto-content-labelers', 'did:plc:ar7c4by46qjdydhdevvrndac'], ['retry-after', '5']], 0.3)
const answer = (side) => {
const headers = { 'content-type': json ? 'application/json; charset=utf-8' : 'text/plain', ...Object.fromEntries(more) }
const rev = revOf(side)
if (rev) headers['atproto-repo-rev'] = rev
return { status, headers, body: JSON.stringify(view(side)) }
}
const extra = (side) => [before[side.name], after[side.name]].filter(Boolean).map((r, i) => [r, i ? '<rev:after>' : '<rev:before>']).sort((a, b) => b[0].length - a[0].length)
const s = await sessionOf(acct, ['full', 'full', 'oauth'])
const shownAs = { method: nsid, rev: which, valid, json, shape: method.startsWith('getProfile') ? { profileOwn } : shape, session: s.kind }
await exchange(`read after write: ${method}, rev ${which}${valid ? '' : ', invalid view'}${s.kind === 'full' ? '' : ', oauth session'}`, shownAs, (side) => ({ path: xrpcPath(nsid, qs(params(side))), headers, token: s.token(side) }), (side) => answer(side), { extra })
}
// getRecord, getFeed, registerPush
// --------------------------------
/// getRecord of a repository no server here holds: forwarded with no token
/// (spec/PROXY.md, "com.atproto.repo.getRecord").
export async function foreignRecord(acct) {
const repo = pick([NOBODY, OTHER.did, OTHER.handle, 'nobody.test'])
const params = { repo, collection: pick(['app.bsky.feed.post', 'com.example.note']), rkey: pick(['3kabc', 'self']) }
if (chance(0.2)) params.cid = SOME_CID
const headers = chance(0.3) ? { 'atproto-proxy': goodTarget() } : {}
const a = pick([
{ status: pick([200, 201]), headers: { 'content-type': 'application/json', 'atproto-repo-rev': '3lxyz' }, body: JSON.stringify({ uri: `at://${OTHER.did}/${params.collection}/${params.rkey}`, value: { text: 'x' } }) },
{ status: 400, headers: { 'content-type': 'application/json' }, body: '{"error":"RecordNotFound","message":"nope"}' },
{ status: 500, headers: { 'content-type': 'application/json' }, body: '{"error":"Boom"}' },
])
const withToken = chance(0.5)
await exchange('getRecord of a repository not here', { params, headers, withToken, serviceAnswers: a }, (side) => ({ path: xrpcPath('com.atproto.repo.getRecord', qs(params)), headers, token: withToken ? tokenOf(side, acct) : undefined }), () => a)
}
/// getFeed, its record read from the AppView answering each way; or
/// registerPush or unregisterPush to each kind of service (spec/PROXY.md,
/// "Other methods the server serves for the app", "getFeed", "registerPush
/// and unregisterPush").
export async function feedAndPush(acct) {
const s = await sessionOf(acct, ['full', 'full', 'oauth'])
const by = s.kind === 'full' ? '' : ', oauth session'
if (chance(0.5)) {
const feed = chance(0.9) ? `at://${pick([OTHER.did, OTHER.handle])}/app.bsky.feed.generator/${pick(['whats-hot', 'f'])}` : pick([`at://${OTHER.did}`, `at://${OTHER.did}/app.bsky.feed.generator`])
const record = pick([
() => ({ status: 200, body: { uri: feed, cid: SOME_CID, value: { $type: 'app.bsky.feed.generator', did: services.feedgen.did, displayName: 'F', createdAt: PAST[0] } } }),
() => ({ status: 200, body: { uri: feed, value: { did: services.feedgen.did } } }),
() => ({ status: 200, body: { uri: feed, value: { did: 5 } } }),
() => ({ status: 200, body: { value: { did: services.feedgen.did } } }),
() => ({ status: 400, body: { error: 'RecordNotFound', message: 'nope' } }),
() => ({ status: 500, body: { error: 'Boom' } }),
].flatMap((f, i) => (i < 2 ? [f, f, f] : [f])))()
const skeleton = pick([{ status: 200, body: { feed: [] } }, { status: 400, body: { error: 'UnknownFeed' } }])
const headers = chance(0.3) ? { 'atproto-proxy': `${services.chat.did}#bsky_chat` } : {}
const params = { feed, ...(chance(0.5) ? { limit: 5 } : {}) }
const answer = (side, r) => {
const x = r.path.startsWith('/xrpc/com.atproto.repo.getRecord') ? record : skeleton
return { status: x.status, headers: { 'content-type': 'application/json' }, body: JSON.stringify(x.body) }
}
return void (await exchange(`getFeed${by}`, { params, headers, record, skeleton, session: s.kind }, (side) => ({ path: xrpcPath('app.bsky.feed.getFeed', qs(params)), headers, token: s.token(side) }), answer))
}
const method = pick(['registerPush', 'unregisterPush'])
const serviceDid = pick([services.appview.did, services.appview.did, services.notif.did, services.notifOther.did, services.chat.did, NOBODY, 'nope'])
const body = { serviceDid, token: 'device-token', platform: pick(['ios', 'android', 'web', 'windows']), appId: 'xyz.blueskyweb.app', ...(chance(0.3) ? { ageRestricted: chance(0.5) } : {}) }
if (chance(0.05)) delete body.appId
const a = pick([{ status: 200, body: '' }, { status: 200, body: '{}' }, { status: 200, body: '{"x":1}' }, { status: 400, body: '{"error":"Bad","message":"m"}' }, { status: 500, body: '{"error":"Boom"}' }])
const headers = requestHeaders()
await exchange(`${method}${by}`, { [method]: body, headers, serviceAnswers: a, session: s.kind }, (side) => ({ method: 'POST', path: xrpcPath(`app.bsky.notification.${method}`), headers: { ...headers, 'content-type': 'application/json' }, body: JSON.stringify(body), token: s.token(side) }), () => ({ ...a, headers: { 'content-type': 'application/json' } }), { jsonBody: true })
}
/// After a crash: each account's preferences, as on the reference, which was
/// not killed (spec/PROXY.md, "Preferences").
export async function preferencesAfterCrash() {
for (const acct of accounts) {
const path = xrpcPath('app.bsky.actor.getPreferences')
await exchange('getPreferences after a crash', { getPreferences: {}, account: acct.n }, (side) => ({ path, token: tokenOf(side, acct) }), () => ({ status: 500, headers: {}, body: '' }))
}
}