chadtmiller.com/monolith
An atproto PDS
0
0
// The harness's permission sets (spec/OAUTH-PERMISSION-SETS.md, "How it is
// checked"), published by one account on a PDS of their own that both sides
// resolve every NSID's lexicon from (`PDS_LEXICON_AUTHORITY_DID`); and a
// set's grant as scope strings, worked out as that page says, for the
// pages' consent list.
import { TestPds } from '@atproto/dev-env'
/// The `aud` a client's `include:` gives the sets' `inheritAud` methods.
export const SET_AUD = 'did:web:api.example.com#notes'
const AUD = SET_AUD.replace('#', '%23')
const LONG_TITLE = 'Notes, todos and items: a very long title that runs well past sixty characters for sure'
const LONG_DETAIL = `${'This set lets the app keep your notes, your todos and your items in step across every device you use, '.repeat(4)}and then some more words.`
/// The documents the authority publishes, by record key: each a lexicon
/// document, `id` its NSID but where said (spec/OAUTH-PERMISSION-SETS.md,
/// "Resolving a set", "What a set grants").
const DOCS = {
// Every kind of permission a set grants; titles and details in English
// (`en`, which the page shows over `title`), French and Japanese; markup
// that is to show as text.
'com.example.authFull': {
title: 'Example notes',
'title:lang': { ja: 'メモ', en: 'Notes and todos', fr: 'Notes et tâches' },
detail: 'Keep notes',
'detail:lang': { fr: 'Gardez vos notes & tâches <em>partout</em>.', en: 'Keep your notes & todos <em>everywhere</em>.' },
permissions: [
{ type: 'permission', resource: 'repo', collection: ['com.example.note'] },
{ type: 'permission', resource: 'repo', collection: ['com.example.todo', 'com.example.test.item', 'com.example.todo'], action: ['delete', 'create'] },
{ type: 'permission', resource: 'repo', collection: ['com.example.test.item'], action: ['update'] },
{ type: 'permission', resource: 'repo', collection: ['com.example.note'], action: ['delete', 'update', 'create'] },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.getNotes', 'com.example.addNote'], aud: '*' },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.syncNotes'], inheritAud: true },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.syncNotes', 'com.example.getNotes'], inheritAud: true },
],
},
// A long title and detail, shown whole; the title from its one `en-`
// key.
'com.example.test.authLong': {
title: 'Long',
'title:lang': { fr: 'Long', 'en-GB': LONG_TITLE },
detail: LONG_DETAIL,
permissions: [{ type: 'permission', resource: 'repo', collection: ['com.example.test.item'], action: ['create', 'update'] }],
},
// No title: shown by its NSID, its detail under it. Its namespace is
// `com.example.test.`, so the harness's other collections are outside.
'com.example.test.authUntitled': {
detail: 'Shown under the NSID: the set has no title.',
permissions: [
{ type: 'permission', resource: 'repo', collection: ['com.example.test.item'], action: ['create'] },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.test.ping'], inheritAud: true },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.test.pong'], aud: '*' },
],
},
// No title and no detail: shown by its NSID alone.
'com.example.test.authBare': {
permissions: [
{ type: 'permission', resource: 'repo', collection: ['com.example.test.zeta', 'com.example.test.Alpha'], action: ['update'] },
{ type: 'permission', resource: 'repo', collection: ['com.example.test.alpha'], action: ['delete'] },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.test.pong', 'com.example.test.Ping'], inheritAud: true },
],
},
// A title, its languages none the page shows, and no detail.
'com.example.authTitleOnly': {
title: 'Quick notes',
'title:lang': { fr: 'Notes rapides', de: 'Schnelle Notizen' },
permissions: [
{ type: 'permission', resource: 'repo', collection: ['com.example.note'], action: ['create'] },
{ type: 'permission', resource: 'repo', collection: ['com.example.todo'], action: ['create'] },
{ type: 'permission', resource: 'repo', collection: ['com.example.test.item'] },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.getNotes'], aud: '*' },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.syncNotes'], inheritAud: true },
],
},
// Each permission dropped for one reason, but the first and the last.
'com.example.authDropped': {
title: 'Mixed bag',
permissions: [
{ type: 'permission', resource: 'repo', collection: ['com.example.todo'], action: ['update'] },
{ type: 'permission', resource: 'repo', collection: ['com.other.note'] },
{ type: 'permission', resource: 'repo', collection: ['com.example.note', 'com.other.note'] },
{ type: 'permission', resource: 'repo', collection: ['COM.EXAMPLE.note'] },
{ type: 'permission', resource: 'repo', collection: ['*'] },
{ type: 'permission', resource: 'rpc', lxm: ['*'], aud: '*' },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.getThing'], aud: 'did:web:api.example.com#notes' },
{ type: 'permission', resource: 'blob', accept: ['image/*'] },
{ type: 'permission', resource: 'account', attr: 'email' },
{ type: 'permission', resource: 'identity', attr: 'handle' },
{ type: 'permission', resource: 'feed', collection: ['com.example.note'] },
{ type: 'permission', resource: 'repo', collection: ['com.example.note'], extra: 'x' },
{ type: 'permission', resource: 'repo', collection: ['com.example.note'], action: [] },
{ type: 'permission', resource: 'repo', collection: ['com.example.note'], action: ['create', 'bogus'] },
{ type: 'permission', resource: 'repo', collection: [] },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.getThing'], aud: '*', inheritAud: false },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.getThing'], aud: '*', inheritAud: true },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.getThing'] },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.getThing'], inheritAud: false },
{ type: 'permission', resource: 'rpc', lxm: ['com.example.getThing'], inheritAud: true },
],
},
// A title, no detail, and none of its permissions kept.
'com.example.authNone': {
title: 'Nothing at all',
permissions: [
{ type: 'permission', resource: 'blob', accept: ['*/*'] },
{ type: 'permission', resource: 'repo', collection: ['org.example.note'] },
],
},
// A document that is not a set.
'com.example.authRecord': {
defs: { main: { type: 'record', key: 'tid', record: { type: 'object', properties: { text: { type: 'string' } } } } },
},
// A document whose `id` is not its NSID.
'com.example.authWrongId': { id: 'com.example.authOther', title: 'Wrong id', permissions: [{ type: 'permission', resource: 'repo', collection: ['com.example.note'] }] },
// A `title:lang` whose key is not a language tag.
'com.example.authBadLang': { title: 'Bad language', 'title:lang': { 'not a language!': 'x' }, permissions: [{ type: 'permission', resource: 'repo', collection: ['com.example.note'] }] },
// A permission with a field whose value is an object: the whole set
// fails, as the reference fails it (spec/OAUTH-PERMISSION-SETS.md, "Where
// the reference departs from the specs").
'com.example.authObjectField': { title: 'Object field', permissions: [{ type: 'permission', resource: 'repo', collection: ['com.example.note'], extra: { a: 1 } }] },
// Space type declarations, for the pages' space rows (spec/OAUTH-PAGES.md,
// "<Space heading>"): one titled, one named by its camel-cased NSID.
'com.example.workspace': { defs: { main: { type: 'space', key: 'any', title: 'Workspace', collections: ['com.example.note', 'com.example.tile'] } } },
'com.example.forum.forumBoard': { defs: { main: { type: 'space', key: 'any', collections: ['com.example.forum.post', 'com.example.forum.reply'] } } },
// A set granting `space` permissions beside a `repo` one, shown on the
// server alone, as the reference drops them.
'com.example.forum.access': {
title: 'Forum access',
detail: 'Post and read in your forums.',
permissions: [
{ type: 'permission', resource: 'repo', collection: ['com.example.forum.profile'] },
{ type: 'permission', resource: 'space', spaceType: 'com.example.forum.forumBoard', action: ['read', 'create'] },
{ type: 'permission', resource: 'space', spaceType: 'com.example.forum.forumBoard', authority: '*', skey: 'main', action: ['read_self'], manage: ['delete'] },
],
},
}
/// The record each key holds.
function recordOf(rkey) {
const { id = rkey, defs, ...main } = DOCS[rkey]
return { $type: 'com.atproto.lexicon.schema', lexicon: 1, id, defs: defs ?? { main: { type: 'permission-set', ...main } } }
}
/// The sets by role, each its NSID.
export const SETS = {
full: 'com.example.authFull',
long: 'com.example.test.authLong',
untitled: 'com.example.test.authUntitled',
bare: 'com.example.test.authBare',
titleOnly: 'com.example.authTitleOnly',
dropped: 'com.example.authDropped',
none: 'com.example.authNone',
record: 'com.example.authRecord',
wrongId: 'com.example.authWrongId',
badLang: 'com.example.authBadLang',
objectField: 'com.example.authObjectField',
missing: 'com.example.authMissing',
forum: 'com.example.forum.access',
}
/// The space types the authority declares.
export const SPACE_TYPES = { workspace: 'com.example.workspace', board: 'com.example.forum.forumBoard' }
/// `include:` tokens of the sets that resolve.
export const inc = (nsid, aud = false) => `include:${nsid}${aud ? `?aud=${AUD}` : ''}`
/// `include:` tokens that do not parse, dropped at PAR
/// (spec/OAUTH-PERMISSION-SETS.md, "The include: scope").
export const MALFORMED = [
`include:${SETS.full}?aud=*`,
`include:${SETS.full}?aud=did:web:api.example.com`,
`include:${SETS.full}?foo=bar`,
`include:${SETS.full}?aud=${AUD}&aud=${AUD}`,
'include:not-an-nsid',
'include:com.example',
'include:',
]
/// The authority: a PDS of its own on the run's PLC directory, its one
/// account publishing every document. Answers `{pds, did}`.
export async function hostSets(plcUrl) {
const pds = await TestPds.create({ didPlcUrl: plcUrl, hostname: 'localhost', inviteRequired: false })
const agent = pds.getAgent()
await agent.createAccount({ email: 'lex-authority@example.com', handle: 'lex-authority.test', password: 'lex-authority' })
const did = agent.session.did
for (const rkey of Object.keys(DOCS)) await agent.com.atproto.repo.createRecord({ repo: did, collection: 'com.atproto.lexicon.schema', rkey, record: recordOf(rkey), validate: false })
return { pds, did }
}
// ------------------------------------------------- a set's grant, in words
const NSID = /^[a-zA-Z](?:[a-zA-Z0-9-]{0,62})?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,62})?)+\.[a-zA-Z][a-zA-Z0-9]{0,62}$/
const ACTIONS = ['create', 'update', 'delete']
const SPACE_ACTIONS = ['read_self', 'read', 'create', 'update', 'delete']
const scalarArray = (v) => Array.isArray(v) && v.length > 0 && v.every((x) => typeof x === 'string')
const DID = /^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/
const RKEY = (k) => /^[a-zA-Z0-9_~.:-]{1,512}$/.test(k) && k !== '.' && k !== '..'
/// A `space` permission of a set as a scope string, as spec/OAUTH-SCOPES.md
/// writes a `space:` token again ("Spaces", "The token's scope"), or null
/// when it is dropped (spec/OAUTH-PERMISSION-SETS.md, "What a set grants").
function spaceOf(p, inside) {
const keys = Object.keys(p).filter((k) => k !== 'type' && k !== 'resource')
if (keys.some((k) => !['spaceType', 'authority', 'skey', 'collection', 'action', 'manage'].includes(k))) return null
if (typeof p.spaceType !== 'string' || !inside(p.spaceType)) return null
const authority = p.authority ?? 'self'
if (typeof authority !== 'string' || !(authority === '*' || authority === 'self' || DID.test(authority))) return null
const skey = p.skey ?? '*'
if (typeof skey !== 'string' || !(skey === '*' || RKEY(skey))) return null
const many = (name, ok) => !(name in p) || (scalarArray(p[name]) && p[name].every(ok))
if (!many('collection', (c) => c === '*' || NSID.test(c))) return null
if (!many('action', (a) => SPACE_ACTIONS.includes(a))) return null
if (!many('manage', (m) => ACTIONS.includes(m))) return null
const q = new URLSearchParams()
if (authority !== 'self') q.append('authority', authority)
if (skey !== '*') q.append('skey', skey)
if (p.collection) for (const c of p.collection.includes('*') ? ['*'] : [...new Set(p.collection)].sort()) q.append('collection', c)
const actions = 'action' in p ? SPACE_ACTIONS.filter((a) => p.action.includes(a)) : SPACE_ACTIONS.slice(1)
if (actions.join() !== SPACE_ACTIONS.slice(1).join()) for (const a of actions) q.append('action', a)
if (p.manage) for (const m of ACTIONS.filter((m) => p.manage.includes(m))) q.append('manage', m)
const back = (s) => s.replace(/%3A/g, ':').replace(/%2F/g, '/').replace(/%2B/g, '+').replace(/%2C/g, ',').replace(/%40/g, '@').replace(/%25/g, '%')
const query = back(q.toString())
return `space:${back(encodeURIComponent(p.spaceType))}${query ? `?${query}` : ''}`
}
/// `include:`'s parts, `{nsid, aud}`, or null if it is not one.
export function includeOf(token) {
const m = /^include(?::([^?]*))?(?:\?(.*))?$/.exec(token)
if (!m) return null
const q = new URLSearchParams(m[2] ?? '')
const nsid = m[1] ? decodeURIComponent(m[1]) : q.get('nsid')
return nsid ? { nsid, aud: q.get('aud') } : null
}
/// What the set `main` (a document's `defs.main`), of `nsid`, grants with
/// the `include:`'s `aud`, as scope strings in order
/// (spec/OAUTH-PERMISSION-SETS.md, "What a set grants").
export function grantOf(nsid, main, aud) {
const prefix = nsid.slice(0, nsid.lastIndexOf('.') + 1)
const inside = (x) => x !== '*' && NSID.test(x) && x.startsWith(prefix) && x.length > prefix.length
// Percent-encoded but for letters, digits, `-_.!~*'()`, `:` and `/`.
const encode = (a) => encodeURIComponent(a).replace(/%3A/gi, ':').replace(/%2F/gi, '/')
const out = []
for (const p of main?.permissions ?? []) {
if (!p || p.type !== 'permission') continue
const keys = Object.keys(p).filter((k) => k !== 'type' && k !== 'resource')
if (p.resource === 'repo') {
if (keys.some((k) => !['collection', 'action'].includes(k))) continue
if (!scalarArray(p.collection) || !p.collection.every(inside)) continue
if ('action' in p && (!scalarArray(p.action) || !p.action.every((a) => ACTIONS.includes(a)))) continue
const cs = p.collection.length > 1 ? [...new Set(p.collection)].sort() : p.collection
const as = 'action' in p ? ACTIONS.filter((a) => p.action.includes(a)) : ACTIONS
const q = [...(cs.length > 1 ? cs.map((c) => `collection=${c}`) : []), ...(as.length === 3 ? [] : as.map((a) => `action=${a}`))]
out.push(`repo${cs.length === 1 ? `:${cs[0]}` : ''}${q.length ? `?${q.join('&')}` : ''}`)
} else if (p.resource === 'rpc') {
if (keys.some((k) => !['lxm', 'aud', 'inheritAud'].includes(k))) continue
if (!scalarArray(p.lxm) || !p.lxm.every(inside)) continue
let to
if ('inheritAud' in p) {
if (p.inheritAud !== true || 'aud' in p || !aud) continue
to = aud
} else if (p.aud === '*') to = '*'
else continue
const ls = [...new Set(p.lxm)].sort()
out.push(`rpc${ls.length === 1 ? `:${ls[0]}?` : `?${ls.map((l) => `lxm=${l}`).join('&')}&`}aud=${encode(to)}`)
} else if (p.resource === 'space') {
const s = spaceOf(p, inside)
if (s) out.push(s)
}
}
return out
}
/// A set's text in the page's language, English (spec/OAUTH-PAGES.md):
/// `<field>:lang`'s `en`, else its first key beginning `en-`, else `<field>`.
export function textOf(main, field) {
const dict = main?.[`${field}:lang`]
if (dict && typeof dict === 'object') {
if (typeof dict.en === 'string') return dict.en
const k = Object.keys(dict).find((x) => x.startsWith('en-'))
if (k) return dict[k]
}
return main?.[field]
}