chadtmiller.com/monolith
An atproto PDS
0
0
// CORS on every path but OAuth's (spec/PDS.md, "Browsers"), held to the
// reference.
import { isDeepStrictEqual } from 'node:util'
import { chance, pick } from '../lib/random.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { count, differ } from '../lib/report.mjs'
/// A DID no server here holds.
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
/// The requests an app in a browser makes, answered 200, 4xx and 404.
const CALLS = (acct) => [
['GET', '/xrpc/com.atproto.server.describeServer'],
['GET', `/xrpc/com.atproto.repo.describeRepo?repo=${encodeURIComponent(acct.did)}`],
['GET', `/xrpc/com.atproto.repo.getRecord?repo=${NOBODY}&collection=com.example.note&rkey=x`],
['GET', '/xrpc/com.example.cors.nothing'],
['POST', '/xrpc/com.atproto.server.createSession', '{}'],
['GET', '/xrpc/_health'],
['GET', '/cors/no/such/path'],
]
/// The paths a preflight is sent to: methods served, one not served,
/// `_health`, a path that is no NSID, and one outside `/xrpc/`.
const PREFLIGHTS = [
'/xrpc/com.atproto.server.createSession',
'/xrpc/com.atproto.repo.getRecord',
'/xrpc/com.atproto.sync.subscribeRepos',
'/xrpc/com.example.cors.nothing',
'/xrpc/_health',
'/xrpc/not%20an%20nsid',
'/cors/no/such/path',
]
/// What a request's answer shows of CORS: its status, every
/// `Access-Control-*` header, and for a preflight whether `Vary` names
/// `Access-Control-Request-Headers` and the body is empty.
async function ask(side, method, path, headers, body) {
const r = await fetch(`${side.url}${path}`, { method, headers, body })
const text = await r.text()
const cors = {}
r.headers.forEach((v, k) => {
if (k.startsWith('access-control-')) cors[k] = v
})
const out = { status: r.status, cors }
if (method === 'OPTIONS') {
out.varies = (r.headers.get('vary') ?? '').split(',').some((v) => v.trim().toLowerCase() === 'access-control-request-headers')
out.empty = text.length === 0
}
return out
}
/// One request an app in a browser would make, or its preflight, on both
/// sides.
export async function cors(acct) {
const headers = chance(0.8) ? { origin: pick(['https://bsky.app', 'https://app.example.com', 'http://localhost:5173']) } : {}
let method, path, body, kind
if (chance(0.5)) {
;[method, path, body] = pick(CALLS(acct))
if (body) headers['content-type'] = 'application/json'
kind = `cors: ${method}`
} else {
method = 'OPTIONS'
path = pick(PREFLIGHTS)
if (chance(0.8)) headers['access-control-request-method'] = pick(['GET', 'POST'])
if (chance(0.7)) headers['access-control-request-headers'] = pick(['content-type', 'authorization,dpop', 'content-type,atproto-accept-labelers,atproto-proxy', 'Content-Type'])
kind = 'cors: preflight'
}
const [a, b] = await Promise.all([ref, cand].map((side) => ask(side, method, path, headers, body)))
if (!isDeepStrictEqual(a, b)) await differ('CORS', { method, path, headers }, a, b)
count(kind, b.status < 400)
}