chadtmiller.com/monolith
An atproto PDS
0
0
// The spaces test vectors in spec/interop/spaces, and the STAR fixtures in
// spec/interop/star: `check` holds every vector to the reference library
// (the pinned alpha's @atproto/space and @atproto/star) and to lib/spec.mjs,
// written from spec/SPACES.md, so each vector is one the reference and the
// page agree on. `make` writes the spaces vectors again; ECDSA signatures are
// randomized, so remaking changes the HTTP signature vectors' bytes, not
// what they test.
//
// cd harness/spaces && npm ci # once
// node vectors.mjs check # what compare.mjs runs first
// node vectors.mjs make # after the reference moves
import crypto from 'node:crypto'
import { readFileSync, writeFileSync } from 'node:fs'
import { base58btc } from 'multiformats/bases/base58'
import { P256Keypair, Secp256k1Keypair } from '@atproto/crypto'
import { parseCid } from '@atproto/lex-data'
import * as space from '@atproto/space'
import { readStar as refReadStar } from '@atproto/star'
import * as S from './lib/spec.mjs'
const DIR = new URL('../../spec/interop/spaces/', import.meta.url)
const STAR_DIR = new URL('../../spec/interop/star/', import.meta.url)
const load = (dir, f) => JSON.parse(readFileSync(new URL(f, dir), 'utf8'))
const save = (f, v) => writeFileSync(new URL(f, DIR), `${JSON.stringify(v, null, 2)}\n`)
const seed = (s) => crypto.createHash('sha256').update(`spec-pds spaces vectors: ${s}`).digest()
const b64 = (b) => Buffer.from(b).toString('base64')
const collect = async (gen) => { const out = []; for await (const c of gen) out.push(Buffer.from(c)); return Buffer.concat(out) }
const throws = async (f) => { try { await f(); return false } catch { return true } }
// ---- making ---------------------------------------------------------------------------
async function makeKem() {
const valid = []
// RFC 9180 §A.3.1, DHKEM(P-256, HKDF-SHA256): the key share is pkEm, the author's key skRm; its shared_secret is DHKEM's, our kem_secret.
const rfc = { pkEm: '04a92719c6195d5085104f469a8b9814d5838ff72b60501e2c4466e5e67b325ac98536d7b61a1af4b78e5b7f951c0900be863c403ce65c9bfcb9382657222d18c4', skRm: 'f3ce7fdae57e1a310d87f1ebbde6f328be0a99cdbcadf4d6589cf29de4b8ffd2', sharedSecret: 'c0d26aeab536609a572b07695d933b589dcf363ff9d93c93adea537aeabb8cb8' }
// HPKE's test vector for DHKEM(P-256, HKDF-SHA256), HKDF-SHA256, Export-only, base mode (cfrg/draft-irtf-cfrg-hpke test-vectors.json at 5f503c5): its first export, empty context, L 32.
const cfrg = { enc: '04d804370b7e24b94749eb1dc8df6d4d4a5d75f9effad01739ebcad5c54a40d57aaa8b4190fc124dbde2e4f1e1d1b012a3bc4038157dc29b55533a932306d8d38d', skRm: '62c3868357a464f8461d03aa0182c7cebcde841036aea7230ddc7339f1088346', info: '4f6465206f6e2061204772656369616e2055726e', exported: '8cf837d5bf1994f0fac3ee1faa671d07e9a38b7f6153bdbb8a66b90159ef7d13' }
const cases = [
{ comment: 'RFC 9180 A.3.1 (DHKEM(P-256, HKDF-SHA256)): key_share is its pkEm, author_private_key its skRm, kem_secret its shared_secret', author: S.unhex(rfc.skRm), share: S.didKeyOf(S.unhex(rfc.pkEm)), kem: rfc.sharedSecret },
{ comment: 'HPKE\'s own test vector for this ciphersuite (Export-only AEAD, base mode): key_share is its enc, author_private_key its skRm, info its info, shared_secret its first exported_value (empty context, L 32); the reference library takes only the info atproto-mac', author: S.unhex(cfrg.skRm), share: S.didKeyOf(S.unhex(cfrg.enc)), info: S.unhex(cfrg.info), exported: cfrg.exported },
]
for (let n = 1; n <= 3; n++) cases.push({ comment: `generated ${n}`, author: seed(`kem author ${n}`), share: S.p256(seed(`kem ephemeral ${n}`)).did })
for (const c of cases) {
const ref = await P256Keypair.import(c.author)
const a = S.p256(c.author)
const dh = a.ecdh.computeSecret(S.p256Point(c.share))
const kem = S.kemSecret(dh, S.p256Point(c.share), a.uncompressed)
if (c.kem && S.hex(kem) !== c.kem) throw new Error(`${c.comment}: kem_secret is not the RFC's`)
const secret = c.info ? S.decapsulate(c.author, c.share, c.info) : space.decapsulate(ref, c.share)
if (c.exported && S.hex(secret) !== c.exported) throw new Error(`${c.comment}: the export is not HPKE's`)
valid.push({ comment: c.comment, author_private_key: S.hex(c.author), author_kem_key: ref.did(), key_share: c.share, info: S.hex(c.info ?? S.MAC_INFO), dh: S.hex(dh), kem_secret: S.hex(kem), shared_secret: S.hex(secret) })
}
const author = S.hex(seed('kem author 1'))
const k256 = await Secp256k1Keypair.import(seed('a k256 key'))
const onCurve = S.p256(seed('kem ephemeral 1')).did
const invalid = [
{ comment: 'a secp256k1 did:key', key_share: k256.did() },
{ comment: 'not a did:key', key_share: 'did:web:example.com' },
{ comment: 'a did:key that does not parse (bad base58)', key_share: 'did:key:zDna0OIl' },
{ comment: 'a P-256 did:key cut short', key_share: onCurve.slice(0, -4) },
{ comment: 'a P-256 did:key whose x has no point on the curve', key_share: badPointDidKey() },
].map((c) => ({ ...c, author_private_key: author }))
return { description: 'The KEM shared secret (spec/SPACES.md, "The shared secret"): for each valid case, decapsulating key_share with author_private_key, with `info` (hex; 61747072...: atproto-mac, but for HPKE\'s own vector), gives shared_secret; dh is the ECDH x-coordinate and kem_secret DHKEM\'s shared secret, the step before the key schedule. Each invalid key_share must be refused.', valid, invalid }
}
function badPointDidKey() {
// An x with no y on P-256: find one deterministically.
for (let i = 0; ; i++) {
const x = seed(`bad x ${i}`)
try { crypto.ECDH.convertKey(Buffer.concat([Buffer.from([2]), x]), 'prime256v1', undefined, undefined, 'uncompressed') } catch {
return `did:key:${base58btc.encode(Buffer.concat([Buffer.from([0x80, 0x24, 2]), x]))}`
}
}
}
async function makeLtHash() {
const cid = (s) => S.cidString(S.cidBytes(S.encode({ $type: 'com.example.note', text: s })))
const e = (p, s) => `${p}/${cid(s)}`
const recs = [e('com.example.note/3kabcdefghi22', 'one'), e('com.example.note/self', 'two'), e('app.bsky.feed.post/3l2xyz7ab4c2k', 'three')]
const cases = [
{ comment: 'empty: sha256 of 2048 zero bytes', add: [], remove: [] },
{ comment: 'the reference library\'s own snapshot vector', add: ['one', 'two'], remove: [] },
{ comment: 'order does not matter', add: ['two', 'one'], remove: [] },
{ comment: 'one record element', add: [recs[0]], remove: [] },
{ comment: 'three record elements', add: recs, remove: [] },
{ comment: 'add then remove one', add: recs, remove: [recs[1]] },
{ comment: 'removing everything added is empty', add: recs, remove: recs },
{ comment: 'removing what was never added wraps lanes below zero', add: [], remove: [recs[2]] },
{ comment: 'the same element twice counts twice', add: [recs[0], recs[0]], remove: [] },
{ comment: 'non-ASCII bytes are hashed as UTF-8', add: ['é', '日本'], remove: [] },
].map((c) => {
const h = new space.LtHash()
for (const x of c.add) h.add(x)
for (const x of c.remove) h.remove(x)
return { ...c, digest: S.hex(h.digest()) }
})
const one = new space.LtHash().add('a')
return { description: 'LtHash (spec/SPACES.md, "The set hash, records and commits"): each case adds its `add` elements and removes its `remove` elements, as UTF-8 strings, from the empty state; `digest` is sha256 of the 2048-byte state. `state_of_a` is the whole state after adding the one element "a", 1024 little-endian uint16 lanes as hex, to find where an implementation goes wrong.', cases, state_of_a: S.hex(one.state()) }
}
const SPACE = 'at://did:plc:3jpt2mvvsumj2r7eqk4gzzjz/space/com.example.forum/general'
const REPO = 'did:plc:ewvi7nxzyoun6zhxrhs64oiz'
async function makeMac() {
const author = S.p256(seed('mac author'))
const shareKey = (n) => S.p256(seed(`mac ephemeral ${n}`))
const secretFor = (n) => S.decapsulate(author.d, shareKey(n).did)
const cases = (profile, items) => items.map(({ comment, label, alg, value, header }, n) => {
const keyShare = shareKey(n).did
const request = S.formatMacRequest(profile, keyShare, { label, alg })
const parsed = space.parseMacRequest(request, profile)
const secret = secretFor(n)
const headers = profile === S.COMMIT_PROFILE ? space.createCommitMacHeaders(value, { ...parsed, sharedSecret: secret }).headers : space.createRecordMacHeaders(value.uri, parseCid(value.cid), { ...parsed, sharedSecret: secret }).headers
const mac = Buffer.from(/=:([^:]*):$/.exec(headers.signature)[1], 'base64')
return { comment, author_private_key: S.hex(author.d), key_share: keyShare, shared_secret: S.hex(secret), ...(profile === S.COMMIT_PROFILE ? { commit: { ...value, data: S.hex(value.data) } } : value), accept_signature: request, header, base: S.macBase(profile, header, parsed.signatureParams), mac: S.hex(mac), response: headers }
})
const commits = [
{ comment: 'a commit', value: { ver: 1, repo: REPO, space: SPACE, rev: '3mzudodppwc2e', data: new space.LtHash().add('one').digest() } },
{ comment: 'the empty repo, asked with alg and another label', label: 'm1', alg: true, value: { ver: 1, repo: REPO, space: SPACE, rev: '3mzudofhpw32e', data: new space.LtHash().digest() } },
{ comment: 'a did:web repo and a 300-character skey', value: { ver: 1, repo: 'did:web:example.com', space: `at://did:web:example.com/space/com.example.group/${'k'.repeat(300)}`, rev: '3mzzzzzzzzz22', data: seed('some data') } },
].map((c) => ({ ...c, header: S.commitHeader(c.value) }))
const recordCid = S.cidString(S.cidBytes(S.encode({ $type: 'com.example.note', text: 'one' })))
const records = [
{ comment: 'a record', value: { uri: `${SPACE}/${REPO}/com.example.note/3kabcdefghi22`, cid: recordCid } },
{ comment: 'a record keyed self', value: { uri: `${SPACE}/${REPO}/com.atproto.space.policy/self`, cid: S.cidString(S.cidBytes(S.encode({ $type: 'com.atproto.space.policy' }))) } },
].map((c) => ({ ...c, header: S.recordHeader(c.value.uri, c.value.cid) }))
const share = shareKey(0).did
const k256 = (await Secp256k1Keypair.import(seed('a k256 key'))).did()
const C = S.COMMIT_PROFILE, R = S.RECORD_PROFILE
const req = (rest, label = 'mac', comps = `("${C}";sf)`) => `${label}=${comps};keyid="${share}";tag="${C}"${rest}`
const accept = [
['as the reference formats it', space.formatMacRequest(C, share), C],
['a record MAC asked for', space.formatMacRequest(R, share), R],
['another label', req('', 'anything'), C],
['alg hmac-sha256', req(';alg="hmac-sha256"'), C],
['tag before keyid, kept in that order', `mac=("${C}";sf);tag="${C}";keyid="${share}"`, C],
['sf written ?1, serialized as sf', `mac=("${C}";sf=?1);keyid="${share}";tag="${C}"`, C],
['keyid given twice: the last counts', `mac=("${C}";sf);keyid="x";keyid="${share}";tag="${C}"`, C],
['spaces around the header', ` ${req('')} `, C],
['another request tagged otherwise, passed over', `x=("foo");tag="other", ${req('')}`, C],
['a member that is no inner list, passed over', `foo, ${req('')}`, C],
['the label given twice: the last counts', `mac=("x");tag="x", ${req('')}`, C],
['only a record MAC asked for, on a method answering a commit: no MAC', space.formatMacRequest(R, share), C],
['the tag a token, not a string: no MAC', `mac=("${C}";sf);keyid="${share}";tag=${C}`, C],
['the tag in upper case: no MAC', `mac=("${C}";sf);keyid="${share}";tag="${C.toUpperCase()}"`, C],
['the member no inner list: no MAC', `mac="${C}";keyid="${share}";tag="${C}"`, C],
['empty: no MAC', '', C],
['two requests tagged with the profile', `a=("${C}";sf);keyid="${share}";tag="${C}", b=("${C}";sf);keyid="${share}";tag="${C}"`, C],
['no sf', req('', 'mac', `("${C}")`), C],
['sf false', req('', 'mac', `("${C}";sf=?0)`), C],
['another parameter on the component', req('', 'mac', `("${C}";sf;bs)`), C],
['the component a token', req('', 'mac', `(${C};sf)`), C],
['another component beside it', req('', 'mac', `("${C}";sf "@method")`), C],
['the record header covered, for a commit', req('', 'mac', `("${R}";sf)`), C],
['no components', req('', 'mac', '()'), C],
['alg another algorithm', req(';alg="ecdsa-p256-sha256"'), C],
['alg a token', req(';alg=hmac-sha256'), C],
['created', req(';created=1700000000'), C],
['nonce', req(';nonce="x"'), C],
['no keyid', `mac=("${C}";sf);tag="${C}"`, C],
['keyid a token', `mac=("${C}";sf);keyid=foo;tag="${C}"`, C],
['not a dictionary', `("${C}";sf)`, C],
['an upper-case parameter key, which no dictionary has', `mac=("${C}";sf);KEYID="${share}";tag="${C}"`, C],
['a secp256k1 key share: refused when decapsulated', req('').replace(share, k256), C],
['a key share that is no did:key: refused when decapsulated', req('').replace(share, 'did:web:example.com'), C],
].map(([comment, header, profile]) => ({ comment, header, profile, ...readAccept(header, profile) }))
return {
description: 'Commit and record MACs (spec/SPACES.md, "MACs"). For each commit and record: `key_share` asks with `accept_signature`; `shared_secret` is its secret with the author\'s KEM key; `header` is the covered header\'s value, `base` the signature base, `mac` HMAC-SHA256 of `base` under `shared_secret`, and `response` the headers a repo host answers. `accept_signature`: each Accept-Signature header read for `profile`, and what it yields: `request` {label, key_share, signature_params} (the Inner List as serialized), or null where it asks for no MAC; `refused` true where it must be refused, decapsulating the key share included.',
commit: cases(C, commits),
record: cases(R, records),
accept_signature: accept,
}
}
/// What the reference makes of an Accept-Signature header, decapsulation of
/// its key share included.
function readAccept(header, profile) {
try {
const r = space.parseMacRequest(header, profile)
if (!r) return { request: null, refused: false }
space.decapsulate(MAC_AUTHOR_REF, r.keyShare)
return { request: { label: r.label, key_share: r.keyShare, signature_params: r.signatureParams }, refused: false }
} catch { return { request: null, refused: true } }
}
const MAC_AUTHOR_REF = await P256Keypair.import(seed('mac author'))
const N = BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551')
const flipS = (sig) => { const s = BigInt(`0x${S.hex(sig.subarray(32))}`); return Buffer.concat([sig.subarray(0, 32), Buffer.from((N - s).toString(16).padStart(64, '0'), 'hex')]) }
const isLowS = (sig) => BigInt(`0x${S.hex(sig.subarray(32))}`) <= N / 2n
const toDer = (sig) => { const int = (b) => { let x = b; while (x.length > 1 && x[0] === 0 && !(x[1] & 0x80)) x = x.subarray(1); if (x[0] & 0x80) x = Buffer.concat([Buffer.from([0]), x]); return Buffer.concat([Buffer.from([2, x.length]), x]) }; const body = Buffer.concat([int(sig.subarray(0, 32)), int(sig.subarray(32))]); return Buffer.concat([Buffer.from([0x30, body.length]), body]) }
async function makeHttpSig() {
const key = S.p256(seed('credential key'))
const other = S.p256(seed('another credential key'))
const credential = 'eyJhbGciOiJFUzI1NksiLCJ0eXAiOiJhdHByb3RvLXNwYWNlLWNyZWRlbnRpYWwrand0Iiwia2lkIjoiI2F0cHJvdG8ifQ.eyJpc3MiOiJkaWQ6ZXhhbXBsZTphdXRob3JpdHkifQ.c2lnbmF0dXJl'
const aud = REPO
const sigOf = (h) => Buffer.from(/=:([^:]*):/.exec(h.signature)[1], 'base64')
const withSig = (h, sig) => ({ ...h, signature: `sig=:${sig.toString('base64')}:` })
const sign = (opts = {}, k = key) => S.signCredential(k, credential, aud, opts)
// Two signatures over the same base, one low-S and one high-S.
let plain = sign()
const low = isLowS(sigOf(plain)) ? sigOf(plain) : flipS(sigOf(plain))
const cases = [
['as the reference signs it (its own createSpaceSigHeaders)', (await space.createSpaceSigHeaders({ authorization: `Atproto-Space-Credential ${credential}`, audience: aud, keypair: await P256Keypair.import(key.d) })).headers],
['the label atproto-space-credential: a label carries no meaning', sign({ label: 'atproto-space-credential' })],
['another label', sign({ label: 'x1' })],
['a low-S signature', withSig(plain, low)],
['a high-S signature, which is accepted', withSig(plain, flipS(low))],
['unpadded base64 in Signature', (() => { const h = withSig(plain, low); return { ...h, signature: h.signature.replace(/=+:$/, ':') } })()],
['keyid equal to the credential key', sign({ extra: `;keyid="${key.did}"` })],
['alg given, ecdsa-p256-sha256', sign({ extra: ';alg="ecdsa-p256-sha256"' })],
['another parameter, created, signed as serialized', sign({ extra: ';created=1700000000' })],
['the scheme in lower case, signed as sent', sign({ scheme: 'atproto-space-credential' })],
['another signature beside it, before it in both fields', (() => { const h = sign(); return { ...h, 'signature-input': `other=("authorization");keyid="x", ${h['signature-input']}`, signature: `other=:AAAA:, ${h.signature}` } })()],
['components in the other order', (() => { const params = '("atproto-space-audience" "authorization");tag="atproto-space-credential"'; const base = `"atproto-space-audience": ${aud}\n"authorization": Atproto-Space-Credential ${credential}\n"@signature-params": ${params}`; return { authorization: `Atproto-Space-Credential ${credential}`, 'atproto-space-audience': aud, 'signature-input': `atproto-space-credential=${params}`, signature: `atproto-space-credential=:${crypto.sign('sha256', Buffer.from(base), { key: key.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64')}:` } })()],
['only authorization covered', (() => { const params = '("authorization");tag="atproto-space-credential"'; const base = `"authorization": Atproto-Space-Credential ${credential}\n"@signature-params": ${params}`; return { authorization: `Atproto-Space-Credential ${credential}`, 'atproto-space-audience': aud, 'signature-input': `atproto-space-credential=${params}`, signature: `atproto-space-credential=:${crypto.sign('sha256', Buffer.from(base), { key: key.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64')}:` } })()],
['no tag', (() => { const params = '("authorization" "atproto-space-audience")'; const base = S.signatureBase(`Atproto-Space-Credential ${credential}`, aud, params); return { authorization: `Atproto-Space-Credential ${credential}`, 'atproto-space-audience': aud, 'signature-input': `atproto-space-credential=${params}`, signature: `atproto-space-credential=:${crypto.sign('sha256', Buffer.from(base), { key: key.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64')}:` } })()],
['another tag', (() => { const params = '("authorization" "atproto-space-audience");tag="atproto-space"'; const base = S.signatureBase(`Atproto-Space-Credential ${credential}`, aud, params); return { authorization: `Atproto-Space-Credential ${credential}`, 'atproto-space-audience': aud, 'signature-input': `atproto-space-credential=${params}`, signature: `atproto-space-credential=:${crypto.sign('sha256', Buffer.from(base), { key: key.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64')}:` } })()],
['alg another algorithm', sign({ extra: ';alg="ecdsa-p384-sha384"' })],
['keyid another key', sign({ extra: `;keyid="${other.did}"` })],
['signed by another key', sign({}, other)],
['a DER signature', withSig(plain, toDer(low))],
['the audience changed after signing', { ...plain, 'atproto-space-audience': 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa' }],
['the authorization changed after signing', { ...plain, authorization: `Atproto-Space-Credential ${credential}x` }],
['no Signature field', (() => { const { signature: _, ...h } = plain; return h })()],
['Signature\'s member under another label than Signature-Input\'s', { ...plain, signature: plain.signature.replace(/^sig=/, 'other=') }],
['two signatures tagged atproto-space-credential', (() => { const a = sign(); const b = sign({ label: 'b' }); return { ...a, 'signature-input': `${a['signature-input']}, ${b['signature-input']}`, signature: `${a.signature}, ${b.signature}` } })()],
['the tag a token, not a string', (() => { const params = '("authorization" "atproto-space-audience");tag=atproto-space-credential'; const base = S.signatureBase(`Atproto-Space-Credential ${credential}`, aud, params); return { authorization: `Atproto-Space-Credential ${credential}`, 'atproto-space-audience': aud, 'signature-input': `sig=${params}`, signature: `sig=:${crypto.sign('sha256', Buffer.from(base), { key: key.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64')}:` } })()],
['keyid a token', sign({ extra: ';keyid=foo' })],
['a Signature member with parameters', { ...plain, signature: `${plain.signature};x=1` }],
['the old Atproto-Space label and no tag (October 1)', (() => { const params = '("authorization" "atproto-space-audience")'; const auth = `Atproto-Space ${credential}`; const base = S.signatureBase(auth, aud, params); return { authorization: auth, 'atproto-space-audience': aud, 'signature-input': `atproto-space=${params}`, signature: `atproto-space=:${crypto.sign('sha256', Buffer.from(base), { key: key.privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64')}:` } })()],
]
plain = undefined
const out = []
for (const [comment, headers] of cases) {
let base = null
try { base = S.verifyCredential(headers, key.did) } catch {}
out.push({ comment, headers, valid: base !== null, ...(base !== null ? { signature_base: base } : {}) })
}
const k256 = (await Secp256k1Keypair.import(seed('a k256 key'))).did()
out.push({ comment: 'a credential key that is not P-256', key_id: k256, headers: out[0].headers, valid: false })
return { description: 'The HTTP Message Signature of a request made with a space credential (spec/SPACES.md, "HTTP Message Signatures"). Verify each case\'s `headers` against `key_id` (the credential\'s cnf.kid; a case may name its own). A valid case\'s `signature_base` is the exact signed text, lines joined by LF. Only the signature is checked here: not the credential, nor that the audience is the right one.', key_id: key.did, credential, cases: out }
}
async function makeRepoStar() {
const author = S.p256(seed('star author'))
const keyShare = S.p256(seed('star ephemeral')).did
const secret = S.decapsulate(author.d, keyShare)
const request = S.parseMacRequest(S.formatMacRequest(S.COMMIT_PROFILE, keyShare), S.COMMIT_PROFILE)
const headersFor = (commit) => S.macHeaders(S.COMMIT_PROFILE, S.commitHeader(commit), request, secret)
const records = (list) => Promise.all(list.map(async ([path, value]) => { const [c, k] = path.split('/'); const r = await space.serializeRecord(c, k, value); return { path, value, drisl: S.hex(r.bytes), cid: r.cid.toString(), r } }))
const archive = async (list, rev) => {
const rs = (await records(list)).sort((a, b) => Buffer.compare(Buffer.from(a.path), Buffer.from(b.path)))
const data = space.RepoCommit.fromRecords(rs.map(({ r }) => ({ collection: r.collection, rkey: r.rkey, cid: r.cid }))).setHash.digest()
const commit = { ver: 1, repo: REPO, space: SPACE, rev, data }
const star = await collect(space.writeRepoStar(commit, rs.map(({ r }) => ({ collection: r.collection, rkey: r.rkey, bytes: r.bytes }))))
return { commit, rs, star, headers: headersFor(commit) }
}
const mac = { key_share: keyShare, shared_secret: S.hex(secret) }
const link = S.cidString(S.cidBytes(S.encode({ x: 1 })))
const sets = [
['the empty repo', [], '3mzudofhpw32e'],
['one record', [['com.example.note/3kabcdefghi22', { $type: 'com.example.note', text: 'hello' }]], '3mzudodppwc2e'],
['records sorted by key bytes: "." (0x2e) sorts before "/" (0x2f)', [
['com.example.x/2', { $type: 'com.example.x', n: 2 }],
['com.example.x.y/1', { $type: 'com.example.x.y', n: 1 }],
['com.example.x/10', { $type: 'com.example.x', n: 10 }],
['com.atproto.space.policy/self', { $type: 'com.atproto.space.policy', policy: { $type: 'com.atproto.memberspace.policy', publicRead: false } }],
], '3mzudoffoid2e'],
['a record with a link, bytes, nested values and non-ASCII text', [['com.example.rich/k~1', { $type: 'com.example.rich', link: { $link: link }, bytes: { $bytes: 'AAEC/w' }, nested: { list: [1, -2, true, null, 'é'] }, text: '日本語' }]], '3mzudofi3n32e'],
]
const toJsonValue = (v) => v
const valid = []
for (const [comment, list, rev] of sets) {
const lexList = list.map(([p, v]) => [p, lexify(v)])
const a = await archive(lexList, rev)
valid.push({ comment, space: SPACE, repo: REPO, records: a.rs.map(({ path, value, drisl, cid }) => ({ path, value: toJsonValue(list.find(([p]) => p === path)[1]), drisl, cid })), commit: { ...a.commit, data: S.hex(a.commit.data) }, star: S.hex(a.star), ...mac, headers: a.headers })
}
// Invalid archives, each made by hand from a valid one, with a MAC that
// verifies its commit unless the case is about the MAC.
const base = await archive([['com.example.note/a', lexify({ $type: 'com.example.note', n: 1 })], ['com.example.note/b', lexify({ $type: 'com.example.note', n: 2 })]], '3mzudoffoid2e')
const pairs = base.rs.map(({ path, r }) => ({ key: Buffer.from(path), value: Buffer.from(r.bytes) }))
const meta = (over = {}) => ({ $type: 'atproto-space-repo', ver: 1, repo: REPO, space: SPACE, rev: base.commit.rev, data: base.commit.data, ...over })
const bad = (comment, star, m = meta(), extra = {}) => ({ comment, space: SPACE, repo: REPO, star: S.hex(star), ...mac, headers: headersFor(m), ...extra })
const good = S.writeStar(meta(), pairs)
const dataFor = (ps) => { const h = new S.LtHash(); for (const p of ps) h.add(`${p.key}/${S.cidString(S.cidBytes(p.value))}`); return h.digest() }
const unsortedMeta = (() => { const m = meta(); const inner = Buffer.from(S.encode(m)); return inner })()
const invalid = [
bad('keys out of order', S.writeStar(meta(), [pairs[1], pairs[0]])),
bad('a duplicate key', (() => { const ps = [pairs[0], pairs[0]]; const m = meta({ data: dataFor(ps) }); return S.writeStar(m, ps) })(), meta({ data: dataFor([pairs[0], pairs[0]]) })),
bad('data that is not the digest of the records', S.writeStar(meta({ data: seed('wrong') }), pairs), meta({ data: seed('wrong') })),
{ ...bad('a MAC that checks, over a header naming another commit than the metadata', good), headers: headersFor(meta({ rev: '3mzzzzzzzzz22' })) },
{ ...bad('a MAC that does not check', good), headers: (() => { const h = headersFor(meta()); return { ...h, signature: `mac=:${Buffer.alloc(32, 1).toString('base64')}:` } })() },
{ ...bad('a MAC under another key share than the one asked with', good), key_share: S.p256(seed('another star ephemeral')).did },
bad('another $type', S.writeStar(meta({ $type: 'atproto-space-meta' }), pairs)),
bad('metadata without rev', (() => { const { rev: _, ...m } = meta(); return S.writeStar(m, pairs) })()),
bad('commit version 2', S.writeStar(meta({ ver: 2 }), pairs), meta({ ver: 2 })),
bad('the archive names another repo than the one requested', S.writeStar(meta({ repo: 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa' }), pairs), meta({ repo: 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa' })),
bad('no end byte', good.subarray(0, good.length - 1)),
bad('a byte after the end byte', Buffer.concat([good, Buffer.from([0])])),
bad('metadata whose map keys are not in DRISL order', (() => { const body = rawMap([['$type', 'atproto-space-repo'], ['ver', 1], ['repo', REPO], ['space', SPACE], ['rev', base.commit.rev], ['data', Buffer.from(base.commit.data)]]); return Buffer.concat([Buffer.from([0x2a, 0x6c, 1, 0]), varintOf(body.length), body, ...pairs.flatMap((p) => [Buffer.from([1]), varintOf(p.key.length), p.key, varintOf(p.value.length), p.value]), Buffer.from([0])]) })()),
bad('a key that is no record path', (() => { const ps = [{ key: Buffer.from('com.example.note'), value: pairs[0].value }]; return S.writeStar(meta({ data: dataFor(ps) }), ps) })(), meta({ data: dataFor([{ key: Buffer.from('com.example.note'), value: pairs[0].value }]) })),
bad('a key over 4096 bytes', (() => { const ps = [{ key: Buffer.from(`com.example.note/${'a'.repeat(4080)}`), value: pairs[0].value }]; return S.writeStar(meta({ data: dataFor(ps) }), ps) })(), meta({ data: dataFor([{ key: Buffer.from(`com.example.note/${'a'.repeat(4080)}`), value: pairs[0].value }]) })),
]
void unsortedMeta
// Archives a reader takes though no writer here makes them.
const extraMeta = meta({ note: 'another metadata field' })
const readable = [{ comment: 'a metadata field beside the commit\'s, which is ignored (STAR allows any)', space: SPACE, repo: REPO, star: S.hex(S.writeStar(extraMeta, pairs)), ...mac, headers: headersFor(extraMeta), records: base.rs.map(({ path, cid }) => ({ path, cid })) }]
return { description: 'Space repos as STAR archives, profile atproto-space-repo (spec/SPACES.md, "STAR"). Each valid case is the exact archive of its commit and records: serializing them must give `star` byte for byte, and reading `star` for its space and repo, asked with `key_share`, whose secret is `shared_secret`, and answered with the response `headers`, must give them back. Each readable case must be read the same way, to the records listed. Each invalid case must be refused whole when read the same way.', valid, readable, invalid }
}
/// JSON's {$link} and {$bytes} as the reference library takes them.
function lexify(v) {
if (Array.isArray(v)) return v.map(lexify)
if (v && typeof v === 'object') {
if (typeof v.$link === 'string' && Object.keys(v).length === 1) return parseCid(v.$link)
if (typeof v.$bytes === 'string' && Object.keys(v).length === 1) return new Uint8Array(Buffer.from(v.$bytes, 'base64'))
return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, lexify(x)]))
}
return v
}
const varintOf = (n) => { const o = []; do { let b = n & 0x7f; n >>>= 7; if (n) b |= 0x80; o.push(b) } while (n); return Buffer.from(o) }
/// A CBOR map with its entries in the order given (string and integer values, bytes).
function rawMap(entries) {
const head = (major, n) => (n < 24 ? Buffer.from([(major << 5) | n]) : n < 256 ? Buffer.from([(major << 5) | 24, n]) : Buffer.from([(major << 5) | 25, n >> 8, n & 0xff]))
const item = (v) => (typeof v === 'number' ? head(0, v) : Buffer.isBuffer(v) ? Buffer.concat([head(2, v.length), v]) : Buffer.concat([head(3, Buffer.byteLength(v)), Buffer.from(v)]))
return Buffer.concat([head(5, entries.length), ...entries.flatMap(([k, v]) => [item(k), item(v)])])
}
// ---- checking ---------------------------------------------------------------------------
let failures = 0
const ok = (cond, what) => { if (!cond) { failures++; console.error(`FAIL ${what}`) } }
async function checkKem(v) {
for (const c of v.valid) {
const ref = await P256Keypair.import(S.unhex(c.author_private_key))
const a = S.p256(S.unhex(c.author_private_key))
const info = S.unhex(c.info)
ok(ref.did() === c.author_kem_key && a.did === c.author_kem_key, `kem ${c.comment}: author_kem_key`)
const dh = a.ecdh.computeSecret(S.p256Point(c.key_share))
ok(S.hex(dh) === c.dh && S.hex(S.kemSecret(dh, S.p256Point(c.key_share), a.uncompressed)) === c.kem_secret, `kem ${c.comment}: the spec's dh and kem_secret`)
if (info.equals(S.MAC_INFO)) ok(S.hex(space.decapsulate(ref, c.key_share)) === c.shared_secret, `kem ${c.comment}: the reference's shared secret`)
ok(S.hex(S.decapsulate(S.unhex(c.author_private_key), c.key_share, info)) === c.shared_secret, `kem ${c.comment}: the spec's shared secret`)
}
for (const c of v.invalid) {
const ref = await P256Keypair.import(S.unhex(c.author_private_key))
ok(await throws(() => space.decapsulate(ref, c.key_share)), `kem invalid ${c.comment}: the reference refuses it`)
ok(await throws(() => S.decapsulate(S.unhex(c.author_private_key), c.key_share)), `kem invalid ${c.comment}: the spec refuses it`)
}
// Round trips, which the vectors cannot hold: the syncer's side against the host's.
for (const c of v.valid) {
const e = await space.encapsulate(c.author_kem_key)
ok(S.hex(S.decapsulate(S.unhex(c.author_private_key), e.keyShare)) === S.hex(e.sharedSecret), `kem ${c.comment}: the reference's encapsulation, decapsulated by the spec`)
const f = S.encapsulate(c.author_kem_key)
ok(S.hex(space.decapsulate(await P256Keypair.import(S.unhex(c.author_private_key)), f.keyShare)) === S.hex(f.sharedSecret), `kem ${c.comment}: the spec's encapsulation, decapsulated by the reference`)
}
return v.valid.length + v.invalid.length
}
async function checkLtHash(v) {
for (const c of v.cases) {
const r = new space.LtHash(); const s = new S.LtHash()
for (const x of c.add) { r.add(x); s.add(x) }
for (const x of c.remove) { r.remove(x); s.remove(x) }
ok(S.hex(r.digest()) === c.digest, `lthash ${c.comment}: the reference`)
ok(S.hex(s.digest()) === c.digest, `lthash ${c.comment}: the spec`)
}
ok(S.hex(new space.LtHash().add('a').state()) === v.state_of_a && S.hex(new S.LtHash().add('a').bytes()) === v.state_of_a, 'lthash state_of_a')
return v.cases.length + 1
}
async function checkMac(v) {
const author = async (c) => P256Keypair.import(S.unhex(c.author_private_key))
for (const [profile, list] of [[S.COMMIT_PROFILE, v.commit], [S.RECORD_PROFILE, v.record]]) {
for (const c of list) {
const what = `mac ${profile} ${c.comment}`
const secret = S.unhex(c.shared_secret)
ok(S.hex(space.decapsulate(await author(c), c.key_share)) === c.shared_secret && S.hex(S.decapsulate(S.unhex(c.author_private_key), c.key_share)) === c.shared_secret, `${what}: shared secret`)
const commit = c.commit && { ...c.commit, data: S.unhex(c.commit.data) }
ok((commit ? S.commitHeader(commit) : S.recordHeader(c.uri, c.cid)) === c.header, `${what}: the spec's header`)
const ref = space.parseMacRequest(c.accept_signature, profile)
const spec = S.parseMacRequest(c.accept_signature, profile)
ok(ref.signatureParams === spec.signatureParams && ref.label === spec.label && ref.keyShare === c.key_share && spec.keyShare === c.key_share, `${what}: both read the request alike`)
ok(S.macBase(profile, c.header, spec.signatureParams) === c.base, `${what}: the spec's base`)
ok(S.hex(S.hmac(secret, Buffer.from(c.base))) === c.mac, `${what}: the spec's mac`)
const refHeaders = commit ? space.createCommitMacHeaders(commit, { ...ref, sharedSecret: secret }).headers : space.createRecordMacHeaders(c.uri, parseCid(c.cid), { ...ref, sharedSecret: secret }).headers
ok(JSON.stringify(refHeaders) === JSON.stringify(c.response), `${what}: the reference's response headers`)
ok(JSON.stringify(S.macHeaders(profile, c.header, spec, secret)) === JSON.stringify(c.response), `${what}: the spec's response headers`)
const verify = { keyShare: c.key_share, sharedSecret: secret, headers: new Headers(c.response) }
ok(!(await throws(() => (commit ? space.verifyCommitMac(commit, verify) : space.verifyRecordMac(c.uri, parseCid(c.cid), verify)))), `${what}: the reference checks it`)
let dict = null
try { dict = S.verifyMac(profile, c.response, { keyShare: c.key_share, sharedSecret: secret }) } catch {}
ok(dict && (commit ? S.headerNamesCommit(dict, commit) : S.headerNamesRecord(dict, c.uri, c.cid)), `${what}: the spec checks it`)
}
}
const ref = await P256Keypair.import(Buffer.from(v.commit[0].author_private_key, 'hex'))
for (const c of v.accept_signature) {
const read = (parse, decap) => { try { const r = parse(c.header, c.profile); if (!r) return { request: null, refused: false }; decap(r.keyShare); return { request: { label: r.label, key_share: r.keyShare, signature_params: r.signatureParams }, refused: false } } catch { return { request: null, refused: true } } }
const r = read(space.parseMacRequest, (k) => space.decapsulate(ref, k))
const s = read(S.parseMacRequest, (k) => S.decapsulate(S.unhex(v.commit[0].author_private_key), k))
const want = JSON.stringify({ request: c.request, refused: c.refused })
ok(JSON.stringify(r) === want, `accept-signature ${c.comment}: the reference reads ${JSON.stringify(r)}`)
ok(JSON.stringify(s) === want, `accept-signature ${c.comment}: the spec reads ${JSON.stringify(s)}`)
}
return v.commit.length + v.record.length + v.accept_signature.length
}
async function checkHttpSig(v) {
for (const c of v.cases) {
const keyId = c.key_id ?? v.key_id
const ref = !(await throws(() => space.verifyCredentialSig(c.headers, keyId)))
let base = null
try { base = S.verifyCredential(c.headers, keyId) } catch {}
ok(ref === c.valid, `http signature ${c.comment}: the reference ${ref ? 'accepts' : 'refuses'} it`)
ok((base !== null) === c.valid, `http signature ${c.comment}: the spec ${base !== null ? 'accepts' : 'refuses'} it`)
if (c.valid) ok(base === c.signature_base, `http signature ${c.comment}: signature base`)
}
return v.cases.length
}
async function checkRepoStar(v) {
for (const c of v.valid) {
const commit = { ...c.commit, data: S.unhex(c.commit.data) }
const star = S.unhex(c.star)
const refStar = await collect(space.writeRepoStar(commit, c.records.map((r) => { const [collection, rkey] = r.path.split('/'); return { collection, rkey, bytes: S.unhex(r.drisl) } })))
ok(refStar.equals(star), `repo star ${c.comment}: the reference serializes it`)
const specStar = S.writeStar({ $type: 'atproto-space-repo', ...commit }, c.records.map((r) => ({ key: Buffer.from(r.path), value: S.unhex(r.drisl) })))
ok(specStar.equals(star), `repo star ${c.comment}: the spec serializes it`)
for (const r of c.records) ok(S.encode(S.decode(S.unhex(r.drisl))).equals(S.unhex(r.drisl)) && S.cidString(S.cidBytes(S.unhex(r.drisl))) === r.cid, `repo star ${c.comment}: record ${r.path}`)
const read = await space.verifyRepoStar([star], refParams(c))
const got = []
for await (const r of read.records) got.push(r)
ok(got.length === c.records.length, `repo star ${c.comment}: the reference reads it`)
let spec = null
try { spec = S.readRepoStar(star, specParams(c)) } catch (e) { console.error(e.message) }
ok(spec && spec.records.map((r) => `${r.path} ${r.cid}`).join() === c.records.map((r) => `${r.path} ${r.cid}`).join(), `repo star ${c.comment}: the spec reads it`)
}
for (const c of v.readable) {
const star = S.unhex(c.star)
const read = await space.verifyRepoStar([star], refParams(c))
const got = []
for await (const r of read.records) got.push(r)
ok(got.length === c.records.length, `repo star readable ${c.comment}: the reference reads it`)
let spec = null
try { spec = S.readRepoStar(star, specParams(c)) } catch (e) { console.error(e.message) }
ok(spec && spec.records.map((r) => `${r.path} ${r.cid}`).join() === c.records.map((r) => `${r.path} ${r.cid}`).join(), `repo star readable ${c.comment}: the spec reads it`)
}
for (const c of v.invalid) {
const star = S.unhex(c.star)
const refThrows = await throws(async () => { const read = await space.verifyRepoStar([star], refParams(c)); for await (const _ of read.records); })
ok(refThrows, `repo star invalid ${c.comment}: the reference refuses it`)
ok(await throws(() => S.readRepoStar(star, specParams(c))), `repo star invalid ${c.comment}: the spec refuses it`)
}
return v.valid.length + v.readable.length + v.invalid.length
}
const refParams = (c) => ({ space: c.space, repo: c.repo, keyShare: c.key_share, sharedSecret: S.unhex(c.shared_secret), headers: new Headers(c.headers) })
const specParams = (c) => ({ expect: c, keyShare: c.key_share, sharedSecret: S.unhex(c.shared_secret), headers: c.headers })
async function checkStarFixtures() {
let n = 0
for (const f of load(STAR_DIR, 'valid-star-fixtures.json')) {
n++
const star = S.unhex(f.star_hex)
const read = await refReadStar([star]).catch(() => null)
const pairs = []
if (read) for await (const p of read.pairs) pairs.push(p)
ok(read && pairs.length === f.decoded.pairs.length, `star ${f.comment}: the reference reads it`)
let spec = null
try { spec = S.readStar(star) } catch {}
ok(spec && spec.pairs.length === f.decoded.pairs.length && spec.pairs.every((p, i) => S.hex(p.key) === f.decoded.pairs[i].key_hex.toLowerCase() && S.hex(p.value) === f.decoded.pairs[i].value_hex.toLowerCase()), `star ${f.comment}: the spec reads it`)
}
for (const f of load(STAR_DIR, 'invalid-star-fixtures.json')) {
n++
ok(await throws(async () => { const r = await refReadStar([S.unhex(f.star_hex)]); for await (const _ of r.pairs); }), `star invalid ${f.comment}: the reference refuses it`)
ok(await throws(() => S.readStar(S.unhex(f.star_hex))), `star invalid ${f.comment}: the spec refuses it`)
}
return n
}
export const FILES = [
['kem.json', makeKem, checkKem],
['lthash.json', makeLtHash, checkLtHash],
['mac.json', makeMac, checkMac],
['http-signature.json', makeHttpSig, checkHttpSig],
['repo-star.json', makeRepoStar, checkRepoStar],
]
/// Check every vector; answers how many, or throws naming the first failures
/// (spec/SPACES.md, "Test vectors").
export async function checkVectors() {
failures = 0
let n = await checkStarFixtures()
for (const [f, , check] of FILES) n += await check(load(DIR, f))
if (failures) throw new Error(`${failures} vector check(s) failed`)
return n
}
if (import.meta.url === `file://${process.argv[1]}`) {
const cmd = process.argv[2]
if (cmd === 'make') {
for (const [f, make] of FILES) save(f, await make())
console.error('vectors written; checking them')
} else if (cmd !== 'check') {
console.error('usage: node vectors.mjs check|make')
process.exit(2)
}
const n = await checkVectors().catch((e) => { console.error(e.message); process.exit(1) })
console.error(`all ${n} vectors agree with the reference and the spec`)
}