chadtmiller.com/monolith
An atproto PDS
0
0
// Accounts: createAccount and the DID it registers with the PLC directory,
// sessions by handle, email or DID, writes to another account, and calls
// through commands that leave out the account (spec/ACCOUNTS.md,
// spec/COMMANDS.md). Each is held to the reference.
import { readFileSync } from 'node:fs'
import { isDeepStrictEqual } from 'node:util'
import { COLLECTIONS, RKEYS, below, chance, goodRecord, pick, rand } from '../lib/random.mjs'
import { cand, ref } from '../lib/processes.mjs'
import { checkDidDoc, fail, plcLog } from '../lib/plc.mjs'
import { allow, count, differ } from '../lib/report.mjs'
import { own } from '../lib/server.mjs'
import { accounts, addAccount, didOf } from '../lib/state.mjs'
import { METHODS, commandLine, runCli, viaCommand, viaTool } from '../lib/via.mjs'
import { both, normalize, shown, xrpc, xrpcHttp } from '../lib/xrpc.mjs'
import { syncHeads } from './records.mjs'
import { isP256DidKey } from '../lib/kem.mjs'
import { checkRepo } from './repository.mjs'
const CREATE = 'com.atproto.server.createAccount'
const SESSION = 'com.atproto.server.createSession'
/// A DID no server here holds.
const NOBODY = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
const RESERVED = readFileSync(new URL('../../spec/data/reserved-handles.txt', import.meta.url), 'utf8').split('\n').map((l) => l.trim()).filter(Boolean)
const reserved = new Set(RESERVED)
/// Reserved labels that are otherwise a handle's front part: one label of 3
/// to 18 characters.
export const RESERVABLE = RESERVED.filter((w) => /^[a-z0-9][a-z0-9-]{1,16}[a-z0-9]$/.test(w))
export const DISALLOWED_TLDS = ['.alt', '.arpa', '.example', '.internal', '.invalid', '.local', '.localhost', '.onion']
let serial = 0
/// A handle's front part no account has had in this run, and not reserved.
export function freshFront() {
for (;;) {
const front = `${pick(['ac', 'usr', 'pq', 'zz', 'm-o'])}${++serial}${pick(['', 'x', 'q9'])}`
if (!reserved.has(front)) return front
}
}
export const mixCase = (s) => [...s].map((c) => (chance(0.5) ? c.toUpperCase() : c)).join('')
export const EMOJI = '\u{1F642}'
const E_ACUTE = '\u00e9'
/// Emails at the edges of what step 3 of createAccount accepts, each with
/// `f`, a handle's front part, to make it the run's own.
export const edgeEmail = (f) =>
pick([
`${f}@b.c`, `${f}@b.c1`, `${f}+b@x.io`, `${f}@sub.x.io`, `${f}@x-y.io`, `\u00fc${f}@x.io`, `${f}@\u00fc.io`,
`${f}!#$%&'*+/=?^_\`{|}~@x.io`, `${f}${'a'.repeat(64 - f.length)}@x.io`, `${f}@${'l'.repeat(63)}.io`,
])
/// Emails step 3 refuses, at the edges of what it accepts.
export const EDGE_BAD_EMAILS = [
'a@b.123', 'a@-x.io', 'a@[1.2.3.4]', 'a@1.2.3.4', 'a.@x.io', '.a@x.io', 'a..b@x.io', '"a"@x.io', 'a@x.io.', 'a@x',
'a b@x.io', 'a@x_y.io', `${'a'.repeat(65)}@x.io`, `a@${'l'.repeat(64)}.io`,
]
/// A new account's handle, email and password: sometimes an email at the
/// edge of what is accepted; sometimes a password at the limit of 256 UTF-16
/// units, none, or an empty one, which is the same as none.
export function newDetails(withPassword) {
const front = freshFront()
const r = rand()
const password = withPassword || r >= 0.2 ? (chance(0.1) ? pick([EMOJI.repeat(128), E_ACUTE.repeat(256)]) : `pw-${front}`) : r < 0.1 ? undefined : ''
return { handle: `${front}.test`, email: chance(0.3) ? edgeEmail(front) : `${front}@example.com`, password }
}
/// createAccount's input for `d`, sometimes in mixed case.
function inputOf(d, mixed) {
const body = { handle: mixed && chance(0.4) ? mixCase(d.handle) : d.handle, email: mixed && chance(0.4) ? mixCase(d.email) : d.email }
if (d.password !== undefined) body.password = d.password
return body
}
/// Note the account both sides made from `body`, answered `a` and `b`.
export const made = (body, a, b) =>
addAccount(
{ handle: a.body.handle, email: body.email.toLowerCase(), password: body.password },
{ reference: { did: a.body.did, token: a.body.accessJwt, refresh: a.body.refreshJwt }, server: { did: b.body.did, token: b.body.accessJwt, refresh: b.body.refreshJwt } },
)
/// createAccount with `body` on both sides, compared with the new DID named
/// as the next account's; if both make it, it is checked as a new account.
/// Answers the account, or null. `http` sends it over XRPC only. `body` may
/// be a function of the side, for what differs between them, such as an
/// invite code.
export async function sendCreate(kind, body, http = false, statuses = {}) {
const send = http ? xrpcHttp : xrpc
const on = typeof body === 'function' ? body : () => body
const [a, b] = await Promise.all([ref, cand].map((side) => send(side, CREATE, { body: on(side) })))
Object.assign(statuses, { reference: a.status, server: b.status })
const name = `<did:${accounts.length + 1}>`
const [na, nb] = [normalize(ref, a, CREATE, [[a.body?.did, name]]), normalize(cand, b, CREATE, [[b.body?.did, name]])]
if (!isDeepStrictEqual(na, nb)) await differ(CREATE, on(ref), na, nb)
count(kind, a.status < 400)
// An account only one side made is not kept (a compatibility run goes on
// past the difference, lib/areas.mjs).
if (a.status !== 200 || b.status !== 200) return null
const acct = made(on(ref), a, b)
await checkNewAccount(acct, [a, b], on(ref))
return acct
}
/// A new account's createAccount input, as `createAccount` makes it.
export const newAccountInput = (withPassword = false) => inputOf(newDetails(withPassword), true)
/// A new account, on each side: the `didDoc` answered is the PLC directory's
/// document for the DID; the directory's log is one genesis operation, with
/// the side's rotation keys, the account's handle and the side's URL, whose
/// signing key is then the one its repository is verified against; and
/// getSession with the new token is the same on both sides
/// (spec/ACCOUNTS.md, "createAccount"). The reference is held to all of it
/// too, which checks the checks. Monolith's operation also has the
/// account's KEM key, a P-256 did:key other than the signing key
/// (spec/SPACES.md, "The KEM key"), which the `latest` reference has not;
/// another implementation may have one, held to the same (spec/COMPAT.md).
async function checkNewAccount(acct, answers, body) {
const request = shown({ body })
for (const [side, res] of [[ref, answers[0]], [cand, answers[1]]]) {
const did = res.body.did
await checkDidDoc(side, did, res.body.didDoc, 'createAccount didDoc', request)
const log = await plcLog(did)
if (log.status !== 200 || !Array.isArray(log.body) || log.body.length !== 1) {
await fail(side, 'PLC log', request, 'one genesis operation', log)
continue
}
const { sig, ...op } = log.body[0]
const key = op.verificationMethods?.atproto
const kem = op.verificationMethods?.atproto_kem
const verificationMethods = { atproto: typeof key === 'string' && key.startsWith('did:key:') ? key : '<the signing key, a did:key>' }
if (side === cand && (own() || kem !== undefined)) verificationMethods.atproto_kem = isP256DidKey(kem) && kem !== key ? kem : '<the KEM key, a P-256 did:key other than the signing key>'
if (side === cand && !own() && kem !== undefined) allow('a KEM key (atproto_kem) in the genesis operation, as Monolith\'s (spec/SPACES.md)')
const want = {
type: 'plc_operation',
verificationMethods,
rotationKeys: [side.recoveryKey, side.rotationKey],
alsoKnownAs: [`at://${acct.handle}`],
services: { atproto_pds: { type: 'AtprotoPersonalDataServer', endpoint: side.publicUrl } },
prev: null,
}
if (typeof sig !== 'string' || !isDeepStrictEqual(op, want)) await fail(side, 'PLC genesis operation', request, want, { ...op, sig })
acct.sides[side.name].key = key
if (side === cand) acct.sides[side.name].kem = kem
}
await both('getSession of a new account', 'com.atproto.server.getSession', { token: acct })
await syncHeads(acct)
await checkRepo(acct)
}
/// The run's first accounts, each with a password.
export async function createFirstAccounts() {
for (let i = 2 + below(2); i > 0; i--) await createAccount({ withPassword: true })
}
/// Emails a new account may have although an account has had them: those
/// only accounts without a password had, which keep no email.
const freeEmails = () => accounts.filter((a) => !a.password && !accounts.some((b) => b.password && b.email === a.email)).map((a) => a.email)
/// createAccount that both sides must make: mixed-case handles and emails,
/// accounts with no password or an empty one, and sometimes the email of an
/// account without a password (spec/ACCOUNTS.md, "createAccount").
export async function createAccount({ withPassword = false, password } = {}) {
const d = newDetails(withPassword)
// A first account's password, made to fit the server's own rules
// (spec/COMPAT.md, "Password rules"): no draw, and on Monolith the same.
if (password && typeof d.password === 'string') d.password = password(d.password)
const free = freeEmails()
if (free.length && chance(0.2)) d.email = pick(free)
const body = inputOf(d, true)
const statuses = {}
const acct = await sendCreate('createAccount', body, false, statuses)
if (!acct && statuses.reference !== 200) await differ(CREATE, body, 'an account', 'none', 'the reference refuses an account the harness means to make')
return acct
}
/// Faults in createAccount's input, each refused alone, grouped by the field
/// they touch: `[name, apply, http]`, where `http` marks input no command
/// can send, as it is not of its flag's type or required.
const FAULTS = {
handle: [
['handle syntax', (b, f) => void (b.handle = pick([`-${f}.test`, `${f}..test`, `${f}_x.test`, `${f} x.test`, f, `${f}.test.`, `${f}.1test`]))],
['handle missing', (b) => void delete b.handle, true],
['disallowed TLD', (b, f) => void (b.handle = `${f}${pick(DISALLOWED_TLDS)}`)],
['unsupported domain', (b, f) => void (b.handle = `${f}${pick(['.com', '.social', '.testing', '.bsky.app', '.test.com'])}`)],
['dot in front part', (b, f) => void (b.handle = `${pick(['a', 'x1', f])}.${f}.test`)],
['too short', (b) => void (b.handle = `${pick(['a', 'ab', 'x9', 'q'])}.test`)],
['too long', (b, f) => void (b.handle = `${f}${'z'.repeat(19 - f.length + below(8))}.test`)],
['reserved', (b) => {
const w = pick(RESERVABLE)
b.handle = `${chance(0.3) ? mixCase(w) : w}.test`
}],
['handle taken', (b) => void (b.handle = mixCase(pick(accounts).handle))],
],
password: [
['password too long', (b) => void (b.password = pick(['p'.repeat(257 + below(100)), EMOJI.repeat(129), E_ACUTE.repeat(257)]))],
['password not a string', (b) => void (b.password = pick([5, true, {}])), true],
],
email: [
['no email', (b) => void delete b.email],
['bad email', (b, f) => void (b.email = pick(['not-an-email', `${f}@`, '@example.com', `${f}.example.com`, ...EDGE_BAD_EMAILS]))],
['email taken', (b) => void (b.email = mixCase(pick(accounts.filter((a) => a.password)).email))],
['email not a string', (b) => void (b.email = pick([5, true, ['x']])), true],
],
did: [
['did given', (b) => void (b.did = pick([NOBODY, 'did:web:elsewhere.example.com']))],
['did syntax', (b) => void (b.did = pick(['not a did', 'did:plc', 'DID:plc:abc']))],
],
invite: [['invite code given', (b, f) => void (b.inviteCode = pick([`code-${f}`, 'localhost-abcde-fghij']))]],
other: [['a field of the wrong type', (b) => void (b[pick(['recoveryKey', 'verificationCode', 'verificationPhone'])] = pick([5, false, {}])), true]],
}
/// createAccount with one fault, or two or three in different fields,
/// which tests the order the checks are made in. Each side must refuse it
/// as the reference does (spec/ACCOUNTS.md, "createAccount").
export async function createAccountRefused() {
const front = freshFront()
const body = { handle: `${front}.test`, email: `${front}@example.com`, password: `pw-${front}` }
if (chance(0.3)) body.handle = mixCase(body.handle)
const groups = Object.keys(FAULTS)
const chosen = []
for (let n = chance(0.6) ? 1 : 2 + below(2); n > 0; n--) chosen.push(groups.splice(below(groups.length), 1)[0])
const faults = chosen.map((g) => pick(FAULTS[g]))
for (const [, apply] of faults) apply(body, front)
const names = faults.map(([name]) => name)
const acct = await sendCreate(faults.length === 1 ? `createAccount refused: ${names[0]}` : 'createAccount refused: several faults', body, faults.some(([, , http]) => http))
if (acct) await differ(CREATE, { faults: names, body }, 'refused', `<did:${acct.n}>`, 'both sides make an account the spec refuses')
}
/// Two createAccounts at once on each side, with the same handle and email
/// in different case: each side makes one account at most, and the same
/// number as the other (spec/ACCOUNTS.md, "createAccount").
export async function accountRace() {
const d = newDetails(false)
const bodies = [inputOf(d, false), { ...inputOf(d, false), handle: mixCase(d.handle), email: mixCase(d.email) }]
const answers = await Promise.all([ref, cand].map((side) => Promise.all(bodies.map((body) => xrpc(side, CREATE, { body })))))
const [won, ours] = answers.map((rs) => rs.map((r, i) => [r, i]).filter(([r]) => r.status === 200))
const request = { bodies, sent: 'at once' }
if (won.length > 1) await differ(CREATE, request, 'one account at most', `${won.length} accounts`, 'the reference fails the check it is held to')
if (ours.length > 1) await differ(CREATE, request, 'one account at most', `${ours.length} accounts`)
if (won.length !== ours.length) await differ(CREATE, request, `${won.length} account(s)`, `${ours.length} account(s)`, 'the accounts made differ')
count('createAccount race', won.length === 1)
if (!won.length) return
const [[a, i]] = won
const [[b]] = ours
const name = `<did:${accounts.length + 1}>`
const [na, nb] = [normalize(ref, a, CREATE, [[a.body.did, name]]), normalize(cand, b, CREATE, [[b.body.did, name]])]
if (!isDeepStrictEqual(na, nb)) await differ(CREATE, request, na, nb, 'the account that won the race')
await checkNewAccount(made(bodies[i], a, b), [a, b], bodies[i])
}
/// createSession by handle or email, either in mixed case, or by DID; with
/// the account's password, a wrong one, or for an account without one any;
/// or for an identifier no account has (spec/ACCOUNTS.md, "Sessions").
/// Sometimes the account carries on with the new session's tokens.
export async function createSession(acct) {
let kind, request
if (rand() < 0.75) {
const by = pick(['handle', 'email', 'did'])
const wrong = chance(0.25)
const password = wrong ? pick(['wrong', '', `${acct.password ?? ''}x`]) : acct.password ?? pick(['', 'x'])
const named = by === 'did' ? null : chance(0.5) ? mixCase(acct[by]) : acct[by]
request = (side) => ({ body: { identifier: named ?? didOf(side, acct), password } })
kind = `createSession by ${by}${wrong ? ', wrong password' : ''}${acct.password ? '' : ', no password'}`
} else {
const front = freshFront()
request = { body: { identifier: pick([`${front}.test`, `${front}@example.com`, NOBODY]), password: acct.password || 'x' } }
kind = 'createSession, no such account'
}
const [a, b] = await both(kind, SESSION, request)
if (a.status === 200 && b.status === 200 && chance(0.3)) {
acct.sides.reference = { ...acct.sides.reference, token: a.body.accessJwt, refresh: a.body.refreshJwt }
acct.sides.server = { ...acct.sides.server, token: b.body.accessJwt, refresh: b.body.refreshJwt }
}
}
const WRITE_METHODS = ['com.atproto.repo.createRecord', 'com.atproto.repo.putRecord', 'com.atproto.repo.deleteRecord', 'com.atproto.repo.applyWrites']
/// A write with the account's token to another account's repository, by its
/// handle or DID, with every write method, sometimes with bad input or a
/// record of the wrong `$type`; or to a repository no account has. Input
/// errors come first, then the repository (spec/ACCOUNTS.md, "Writes to
/// another account").
export async function crossWrites(acct) {
const others = accounts.filter((x) => x !== acct)
const nobody = rand() < 0.15
const other = pick(others)
const byDid = chance(0.5)
const target = nobody ? pick([NOBODY, `${freshFront()}.test`]) : null
const repo = (side) => target ?? (byDid ? didOf(side, other) : other.handle)
const nsid = pick(WRITE_METHODS)
const collection = pick(COLLECTIONS)
const r = rand()
const fault = r < 0.3 ? 'bad input' : r < 0.55 && nsid !== 'com.atproto.repo.deleteRecord' ? 'bad $type' : null
const where = fault === 'bad input' ? pick(nsid === 'com.atproto.repo.deleteRecord' ? ['collection', 'rkey'] : ['collection', 'rkey', 'record']) : null
const value = goodRecord(collection)
if (fault === 'bad $type') value.$type = pick(COLLECTIONS.filter((c) => c !== collection))
if (where === 'record') value.ratio = 1.5
const w = {
collection: where === 'collection' ? pick(['not an nsid', 'com.example']) : collection,
rkey: where === 'rkey' ? pick(['a/b', '..', 'a b']) : pick(RKEYS),
}
let body
if (nsid === 'com.atproto.repo.createRecord') body = { ...w, record: value }
else if (nsid === 'com.atproto.repo.putRecord') body = { ...w, record: value }
else if (nsid === 'com.atproto.repo.deleteRecord') body = w
else {
const action = pick(fault === 'bad $type' || where === 'record' ? ['create', 'update'] : ['create', 'update', 'delete'])
body = { writes: [{ $type: `com.atproto.repo.applyWrites#${action}`, ...w, ...(action === 'delete' ? {} : { value }) }] }
}
const kind = nobody ? 'write to a repository no account has' : `write to another account by ${byDid ? 'DID' : 'handle'}${fault ? `, ${fault}` : ''}`
await both(kind, nsid, (side) => ({ body: { repo: repo(side), ...body }, token: acct }))
}
/// Methods that name an account by a required `repo` or `did`, with their
/// other arguments.
const NAMING = [
['com.atproto.repo.describeRepo', 'repo', () => ({})],
['com.atproto.repo.listRecords', 'repo', () => ({ collection: pick(COLLECTIONS) })],
['com.atproto.repo.getRecord', 'repo', () => ({ collection: pick(COLLECTIONS), rkey: pick(RKEYS) })],
['com.atproto.sync.getLatestCommit', 'did', () => ({})],
['com.atproto.repo.createRecord', 'repo', () => {
const collection = pick(COLLECTIONS)
return { collection, record: goodRecord(collection) }
}],
['com.atproto.repo.deleteRecord', 'repo', () => ({ collection: pick(COLLECTIONS), rkey: pick(RKEYS) })],
]
/// With --commands: a tool or command called without the `repo` or `did`
/// that names an account. With the account's token, a query names the
/// token's account: it answers as the server's own XRPC does when named it,
/// by DID, or for a `repo` by handle too. With no token, the argument is as
/// required as its lexicon says: a tool answers as the reference does over
/// XRPC without it, and a command is a usage error, exit status 2.
export async function withoutAccount(acct) {
const queries = NAMING.filter(([nsid]) => METHODS[nsid].kind === 'query')
const [nsid, arg, rest] = pick(chance(0.5) ? queries : NAMING)
const m = METHODS[nsid]
const args = rest()
const at = m.kind === 'query' ? 'params' : 'body'
if (m.kind === 'query' && chance(0.5)) {
// A `did` is the account's DID; a `repo` its handle or DID.
const byDid = arg === 'did' || chance(0.5)
const named = { [at]: { ...args, [arg]: byDid ? didOf(cand, acct) : acct.handle } }
const via = chance(0.5) ? 'tool' : 'command'
const b = await (via === 'tool' ? viaTool : viaCommand)(nsid, { [at]: args, token: acct.sides.server.token })
if (!b) return
// Held to the server's own XRPC answer naming the account, which the
// other steps hold to the reference's.
const a = await xrpcHttp(cand, nsid, named)
const [na, nb] = [normalize(cand, a, nsid), normalize(cand, b, nsid)]
if (!isDeepStrictEqual(na, nb)) await differ(`${nsid} by ${via}, without ${arg}`, { args, token: `<token of did:${acct.n}>`, xrpc: { [at]: { ...args, [arg]: byDid ? `<did:${acct.n}>` : acct.handle } } }, na, nb, `with a token, an omitted ${arg} is the token's account: the server's XRPC answer naming it, then the tool's or command's`)
return count(`${via} without ${arg}, with a token`, a.status < 400)
}
if (chance(0.5)) {
const b = await viaTool(nsid, { [at]: args })
const a = await xrpcHttp(ref, nsid, { [at]: args })
const [na, nb] = [normalize(ref, a, nsid), normalize(cand, b, nsid)]
if (!isDeepStrictEqual(na, nb)) await differ(`tool ${m.tool}, without ${arg} or a token`, args, na, nb, `the reference's answer over XRPC without ${arg}`)
return count(`tool without ${arg} or a token`, false)
}
const { argv, stdin } = commandLine(m, args)
const r = await runCli(argv, { stdin })
if (r.code !== 2) await differ(`command pds ${m.group} ${m.command}, without ${arg} or a token`, { argv: ['pds', ...argv], stdin }, 'a usage error: exit status 2', { code: r.code, stdout: r.stdout.toString().slice(0, 300) })
count(`command without ${arg} or a token`, false)
}
/// After a crash: every account's session still holds, and its password
/// still logs in.
export async function sessionsSurvive() {
for (const acct of accounts) await both('getSession after a crash', 'com.atproto.server.getSession', { token: acct })
const acct = pick(accounts)
await both('createSession after a crash', SESSION, { body: { identifier: acct.handle, password: acct.password ?? '' } })
}