~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

consent: permission sets shown as the reference's page shows them

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:consent/permission-sets
.changeset/consent-permission-sets.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: minor
---
# Consent shows permission sets as the reference does
The consent page gives every `include:` scope a row of its own, as the reference's page does: also for a set with no title, and also beside `transition:generic`. A row's heading is the set's title, or its NSID when it has none. Under the heading is the set's detail, or else the NSID when the set has a title. A closed `Details` disclosure in the row lists what the set grants: its methods and the services they reach, and its collections with the actions asked of each. A set's grant is no longer folded into the "Your data in …" and "Other services" rows. The "From <authority>" line is gone, and titles and details are shown in full.
.claude/skills/ui/SKILL.md+3−2
@@ -35,7 +35,8 @@ just look email-code # the code view (the answer given by look itse
just look choose # two remembered accounts, one with a long handle
just look consent # loopback client, atproto transition:generic, the long handle
just look consent --scope 'atproto repo:com.example.foo?action=create rpc:com.example.bar?aud=* blob:image/* account:email?action=manage identity:handle'
just look consent --details # Technical details open
just look consent --details # Technical details and every set's Details open
just look consent --scope 'atproto include:com.example.authFull?aud=did:web:api.example.com%23notes include:com.example.test.authUntitled' # the harness's permission sets (harness/lib/sets.mjs)
just look ended # consent answered 400: "This sign-in has ended…"
just look busy # the sign-in held on its way: the button busy, the rest disabled
just look error # the error page
@@ -68,7 +69,7 @@ For every view you touch, look at each of these that applies:
- **Busy**: each button that calls the API, pressed, with its call held.
- **Phone** and **dark**: the defaults draw desktop light and phone dark.
Look at phone light and desktop dark too when you change a colour.
- **Open**: `Technical details`.
- **Open**: `Technical details`, and each permission set's `Details`.
## House rules
harness/checks/pages.mjs+123−60
@@ -33,7 +33,7 @@ import { accounts, didOf } from '../lib/state.mjs'
import { strip } from '../lib/xrpc.mjs'
import { issuer } from '../lib/server.mjs'
import { CLIENTS, exchange, handleOf, newRequest, norm, sides } from './oauth.mjs'
import { SETS, authorityOf, grantOf, inc, includeOf, textOf } from '../lib/sets.mjs'
import { SETS, grantOf, inc, includeOf, textOf } from '../lib/sets.mjs'
import { setEmailFactor, signInCodes } from './email.mjs'
import { createAccount } from './accounts.mjs'
import { addLink, newClient, passkeysAble, passkeysOf, redeem, serverRequest, whoOf } from './passkeys.mjs'
@@ -43,8 +43,8 @@ const AXE = readFileSync(createRequire(import.meta.url).resolve('axe-core/axe.mi
/// The loopback clients a flow draws from: oauth.mjs's, some asking for
/// what spec/OAUTH-PAGES.md's consent list merges and covers, and some
/// asking for the harness's permission sets (lib/sets.mjs): titled and
/// not, with a detail and without, in other languages, long, and granting
/// nothing.
/// not, with a detail and without, in other languages, long, granting
/// nothing, and towards audiences each said its own way.
const PAGE_CLIENTS = [
...CLIENTS.slice(1),
{ scope: 'atproto repo:com.example.foo?action=create&action=delete rpc:com.example.bar?aud=did:web:svc.test%23x blob:video/* blob:application/pdf account:status?action=manage account:repo identity:* transition:chat.bsky' },
@@ -56,6 +56,7 @@ const PAGE_CLIENTS = [
{ scope: `atproto ${inc(SETS.untitled, true)} repo:app.bsky.feed.post rpc:com.example.bar?aud=did:web:svc.test%23x ${inc(SETS.none)} ${inc(SETS.titleOnly, true)}` },
{ scope: `atproto ${inc(SETS.long)} ${inc(SETS.dropped, true)} ${inc(SETS.full)} ${inc(SETS.untitled)} blob:image/*` },
{ scope: `atproto transition:generic ${inc(SETS.full)} ${inc(SETS.untitled, true)} transition:email` },
{ scope: `atproto ${inc(SETS.bare)} include:${SETS.full}?aud=did:web:api.bsky.app%23bsky_appview include:${SETS.titleOnly}?aud=did:web:api.bsky.chat%23bsky_chat include:${SETS.bare}?aud=did:plc:aaaaaaaaaaaaaaaaaaaaaaaa%23svc` },
].map((c) => ({ redirects: ['http://127.0.0.1/callback'], ...c }))
// ------------------------------------------------------------ the names
@@ -195,53 +196,68 @@ function servicesOf(rpcs) {
return [...new Set(hosts), ...(auds.some((a) => a !== '*' && !a.startsWith('did:web:')) ? ['a service'] : []), ...(auds.includes('*') ? ['any service'] : [])]
}
/// A text cut to `n` characters (code points) and `…`.
const cut = (s, n) => ([...s].length > n ? `${[...s].slice(0, n).join('')}…` : s)
/// A text's length in Unicode code points.
const length = (s) => [...s].length
/// A titled set's sentence when it has no detail: `<Set clauses>.`
function setSentence(grant) {
/// What a set's `Details` holds for its grant (spec/OAUTH-PAGES.md, "What
/// it grants"): `{summary, sentence, tables}`, each table `{head, rows}`
/// and each row `{cells, spans}`, a cell's text and its `rowspan`.
function grantDetails(grant) {
const ps = grant.map(permission)
const repos = ps.filter((p) => p.resource === 'repo')
const rpcs = ps.filter((p) => p.resource === 'rpc')
if (!repos.length && !rpcs.length) return 'Asks for nothing this server grants.'
const parts = dataClauses(askedOf(repos), null).map(([app, clauses]) => `${join(clauses)} in ${app}`)
if (rpcs.length) parts.push(`act as you on ${join(servicesOf(rpcs))}`)
return `${capital(parts.join('; '))}.`
const sorted = (xs) => [...xs].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
const calls = new Map()
for (const p of ps.filter((p) => p.resource === 'rpc')) {
const aud = p.q.get('aud')
if (!calls.has(aud)) calls.set(aud, new Set())
for (const m of values(p, 'lxm')) calls.get(aud).add(m)
}
const towards = (aud) =>
aud === '*' ? 'Any service'
: aud.startsWith('did:web:api.bsky.app#') ? 'Bluesky App services'
: aud.startsWith('did:web:api.bsky.chat#') ? 'Bluesky Chat services'
: aud.startsWith('did:web:') && aud.includes('#') ? `A service controlled by ${aud.slice('did:web:'.length, aud.indexOf('#'))}`
: aud
const callRows = sorted(calls.keys()).flatMap((aud) => {
const ms = sorted(calls.get(aud))
return ms.map((m, i) => (i === 0 ? { cells: [m, towards(aud)], spans: [1, ms.length] } : { cells: [m], spans: [1] }))
})
const asked = askedOf(ps.filter((p) => p.resource === 'repo'))
const dataRows = sorted(asked.keys()).map((c) => ({ cells: [c, ...ACTIONS.map(([a]) => (asked.get(c).has(a) ? 'Yes' : ''))], spans: [1, 1, 1, 1] }))
const tables = [
...(callRows.length ? [{ head: ['Call', 'Towards'], rows: callRows }] : []),
...(dataRows.length ? [{ head: ['Data', 'Create', 'Update', 'Delete'], rows: dataRows }] : []),
]
// In `<code>`: methods, collections, and an audience said by no words.
const codes = [...callRows.flatMap(({ cells }) => cells.filter((c, i) => i === 0 || (i === 1 && calls.has(c)))), ...dataRows.map(({ cells }) => cells[0])]
return {
details: {
summary: 'Details',
sentence: tables.length ? 'The application requests the permissions necessary to perform the following actions on your behalf:' : 'Asks for nothing this server grants.',
tables,
},
codes,
}
}
/// Each `include:` of the scope's `tokens` with the set `sets` (the page's
/// `permissionSets`) has for it: `{token, nsid, main, grant}`, or null for
/// a token that is not one.
const includesOf = (tokens, sets) => tokens.map((token) => {
const i = includeOf(token)
if (!i) return null
const main = sets?.[i.nsid]
return { token, nsid: i.nsid, main, grant: grantOf(i.nsid, main, i.aud) }
})
/// Whether a set has a title the page names it by.
const titled = (main) => typeof textOf(main, 'title') === 'string' && textOf(main, 'title') !== ''
/// The rows the consent list shows for the scope's `tokens`, in order, as
/// spec/OAUTH-PAGES.md merges and words them, the sets it includes being
/// `sets` (the page's `permissionSets`): each `{heading, from, sentence,
/// codes}`, `from` a set row's `From <authority>` (else null), with the
/// texts it shows in `<code>`.
/// `sets` (the page's `permissionSets`): each `{heading, sentence, codes,
/// details}`, with the texts it shows in `<code>`, and for a set's row
/// what its `Details` holds (else null); and whether every set's title
/// and detail is short enough for "Seeing it all".
export function consentRows(tokens, sets = {}) {
const has = (t) => tokens.includes(t)
const generic = has('transition:generic')
const incs = includesOf(tokens, sets)
// An untitled set's grant is read as if the client had asked for it.
const asIfAsked = tokens.flatMap((t, i) => (!incs[i] ? [t] : titled(incs[i].main) ? [] : incs[i].grant))
const parsed = asIfAsked.map((t) => [t, permission(t)])
const named = new Set(['atproto', 'transition:generic', 'transition:email', 'transition:chat.bsky', ...incs.filter(Boolean).map((x) => x.token)])
const parsed = tokens.map((t) => [t, permission(t)])
const named = new Set(['atproto', 'transition:generic', 'transition:email', 'transition:chat.bsky', ...tokens.filter((t) => includeOf(t))])
const of = (resource) => {
const xs = parsed.filter(([t, p]) => p?.resource === resource && !named.has(t))
for (const [t] of xs) named.add(t)
return xs.map(([, p]) => p)
}
const row = (heading, sentence, codes = []) => ({ heading, from: null, sentence, codes })
const row = (heading, sentence, codes = []) => ({ heading, sentence, codes, details: null })
const rows = []
let short = true
if (generic) rows.push(row('Full access', 'Read and change all your data, upload files and act as you on other services, as an app password can.'))
const ids = of('identity')
@@ -255,12 +271,18 @@ export function consentRows(tokens, sets = {}) {
if (has('transition:chat.bsky')) rows.push(row('Direct messages', 'Read and send your Bluesky direct messages.'))
if (!generic) {
for (const x of incs) {
if (!x || !titled(x.main)) continue
const detail = textOf(x.main, 'detail')
rows.push({ heading: cut(textOf(x.main, 'title'), 60), from: `From ${authorityOf(x.nsid)}`, sentence: typeof detail === 'string' && detail !== '' ? cut(detail, 140) : setSentence(x.grant), codes: [] })
for (const token of tokens) {
const i = includeOf(token)
if (!i) continue
const main = sets?.[i.nsid]
const text = (field) => {
const t = textOf(main, field)
return typeof t === 'string' && t !== '' ? t : null
}
const [title, detail] = [text('title'), text('detail')]
if ((title && length(title) > 60) || (detail && length(detail) > 140)) short = false
const { details, codes } = grantDetails(grantOf(i.nsid, main, i.aud))
rows.push({ heading: title ?? i.nsid, sentence: detail ?? (title ? i.nsid : ''), codes, details })
}
const repos = of('repo')
@@ -284,15 +306,16 @@ export function consentRows(tokens, sets = {}) {
for (const t of tokens) if (!named.has(t)) rows.push(row('Permission', t, [t]))
rows.push(row('Who you are', 'See which account is yours.'))
return rows
return { rows, short }
}
/// `Technical details` for the scope's `tokens`: each token, and under an
/// `include:` the scope strings its set grants, `[{token, grant}]`.
export const technicalDetails = (tokens, sets = {}) => {
const incs = includesOf(tokens, sets)
return tokens.map((token, i) => ({ token, grant: incs[i]?.grant ?? [] }))
}
export const technicalDetails = (tokens, sets = {}) =>
tokens.map((token) => {
const i = includeOf(token)
return { token, grant: i ? grantOf(i.nsid, sets?.[i.nsid], i.aud) : [] }
})
// ------------------------------------------------------------ the browser
@@ -503,29 +526,53 @@ async function checkView(w, view, ctx = {}) {
/// The consent view's list, `Technical details`, and what is in the window
/// as it appears, for the scope the page was given and the sets it
/// includes (`permissionSets`). A set row's `From <authority>` is the one
/// element of its row, other than the heading, whose text is that alone;
/// the sentence is the rest of the row (spec/OAUTH-PAGES.md, "Consent").
/// includes (`permissionSets`). A row's sentence is its text but its
/// heading and its `Details`; a set's `Details` is read open, after its
/// being closed as the view appears is noted (spec/OAUTH-PAGES.md,
/// "Consent").
async function checkConsent(w, ctx) {
const { page } = w
const { scope, sets } = await page.evaluate(() => ({ scope: window.__authorizeData?.scope ?? '', sets: window.__authorizeData?.permissionSets ?? {} }))
const tokens = scope.split(' ').filter(Boolean)
const want = consentRows(tokens, sets)
const { rows: want, short } = consentRows(tokens, sets)
const rowDetails = 'main ul > li details'
const closed = await page.evaluate((sel) => {
const ds = [...document.querySelectorAll(sel)]
const was = ds.map((d) => !d.open)
for (const d of ds) d.open = true
return was
}, rowDetails)
await page.waitForTimeout(50)
const got = await page.evaluate(() => {
const text = (el) => el.textContent.replace(/\s+/g, ' ').trim()
const cell = (c) => text(c) || [...c.querySelectorAll('[role="img"][aria-label]')].map((e) => e.getAttribute('aria-label')).join(' ')
const items = [...document.querySelectorAll('main ul > li')].filter((li) => li.querySelector('h2'))
const caption = (el) => /^From \S+$/.test(el.textContent.trim())
return items.map((li) => {
const h = li.querySelector('h2')
const rest = li.cloneNode(true)
rest.querySelector('h2').remove()
const froms = [...rest.querySelectorAll('*')].filter((el) => caption(el) && ![...el.children].some(caption))
for (const el of froms) el.remove()
const from = froms.length === 0 ? null : froms.length === 1 ? froms[0].textContent.trim() : froms.map((el) => el.textContent.trim())
return { heading: h.textContent.trim(), from, sentence: rest.textContent.replace(/\s+/g, ' ').trim(), codes: [...li.querySelectorAll('code')].map((c) => c.textContent.trim()) }
for (const d of rest.querySelectorAll('details')) d.remove()
const ds = [...li.querySelectorAll('details')].map((d) => {
const summary = d.querySelector('summary')
const body = d.cloneNode(true)
for (const x of body.querySelectorAll('summary, table')) x.remove()
return {
summary: summary ? text(summary) : null,
sentence: text(body),
tables: [...d.querySelectorAll('table')].map((t) => ({
head: t.tHead?.rows[0] ? [...t.tHead.rows[0].cells].map((c) => (c.tagName === 'TH' ? text(c) : { td: text(c) })) : null,
rows: [...t.tBodies].flatMap((b) => [...b.rows]).map((r) => ({ cells: [...r.cells].map(cell), spans: [...r.cells].map((c) => c.rowSpan) })),
})),
}
})
return { heading: text(h), sentence: text(rest), codes: [...li.querySelectorAll('code')].map((c) => c.textContent.trim()), details: ds.length === 0 ? null : ds.length === 1 ? ds[0] : ds }
})
})
const shape = (xs) => xs.map(({ heading, from, sentence, codes }) => ({ heading, from, sentence, codes: [...codes].sort() }))
await page.evaluate((sel) => { for (const d of document.querySelectorAll(sel)) d.open = false }, rowDetails)
await page.waitForTimeout(50)
const shape = (xs) => xs.map(({ heading, sentence, codes, details }) => ({ heading, sentence, codes: [...codes].sort(), details }))
if (!isDeepStrictEqual(shape(got), shape(want))) await held('the consent list', shape(want), shape(got))
if (closed.some((c) => !c)) await held("each set's Details closed as the consent view appears", closed.map(() => true), closed)
const details = page.locator('details').filter({ has: page.locator('summary', { hasText: 'Technical details' }) })
if ((await details.count()) !== 1) return held('Technical details', 'one <details> whose summary is "Technical details"', await shown(w))
// A list of the tokens, each in <code>, and under an `include:` a list of
@@ -548,8 +595,10 @@ async function checkConsent(w, ctx) {
else if (!isDeepStrictEqual(listed.items, tech)) await held('Technical details, a list of the tokens and under each include: its grant', tech, listed.items)
if (ctx.loopback && !(await has(page.getByText('An app on your device', { exact: true })))) await held('the client on the consent view', 'An app on your device', await shown(w))
// Seeing it all, from the top of the page: the actions in the window
// whatever the scope, and with six rows or fewer, nothing to scroll.
const seen = await page.evaluate(([names, rows]) => {
// whatever the scope, and with six rows or fewer, no set's title or
// detail long, nothing to scroll.
const fits = want.length <= 6 && short
const seen = await page.evaluate(([names, fits]) => {
window.scrollTo(0, 0)
const inside = (el) => {
const r = el.getBoundingClientRect()
@@ -557,9 +606,9 @@ async function checkConsent(w, ctx) {
}
const buttons = [...document.querySelectorAll('main button')]
const outside = names.filter((n) => buttons.some((b) => (b.getAttribute('aria-label') ?? b.textContent.trim()) === n && !inside(b)))
const tall = rows <= 6 && document.documentElement.scrollHeight > window.innerHeight
const tall = fits && document.documentElement.scrollHeight > window.innerHeight
return { outside, tall, scrollHeight: document.documentElement.scrollHeight, innerHeight: window.innerHeight }
}, [[SERVER.allow, SERVER.deny, SERVER.back, SERVER.another], want.length])
}, [[SERVER.allow, SERVER.deny, SERVER.back, SERVER.another], fits])
if (seen.outside.length) await held(`the consent view's actions in the window${w.phone ? ' (360 by 740)' : ' (1200 by 900)'}`, 'Allow, Deny and Back or Another account within the window', { ...seen, rows: want.length })
if (seen.tall) await held(`the consent view with ${want.length} rows${w.phone ? ' (360 by 740)' : ' (1200 by 900)'}`, 'no taller than the window', { ...seen, rows: want.length })
}
@@ -864,11 +913,25 @@ const closeAll = async (ws) => {
for (const w of Object.values(ws)) await w.page.close()
}
/// The page clients dealt as a shuffled deck, each once before any again,
/// so that a run of a few dozen flows asks for every one.
const deck = []
function nextClient() {
if (!deck.length) {
deck.push(...PAGE_CLIENTS)
for (let i = deck.length - 1; i > 0; i--) {
const j = below(i + 1)
;[deck[i], deck[j]] = [deck[j], deck[i]]
}
}
return deck.pop()
}
/// A request for `acct` on both sides, with `login_hint` the handle of
/// `hint`, or none; in English, as the pages are, and with no `prompt`:
/// `create` asks for a sign-up the server's pages have not.
async function request(acct, hint) {
return newRequest(acct, { client: pick(PAGE_CLIENTS), whole: chance(0.5), kind: 'PAR (pages)', extra: () => ({ login_hint: hint ? handleOf(hint) : undefined, ui_locales: undefined, prompt: undefined }) })
return newRequest(acct, { client: nextClient(), whole: chance(0.5), kind: 'PAR (pages)', extra: () => ({ login_hint: hint ? handleOf(hint) : undefined, ui_locales: undefined, prompt: undefined }) })
}
/// The devices kept between flows, up to three, each `{reference, server,
harness/lib/sets.mjs+14−8
@@ -35,24 +35,32 @@ const DOCS = {
{ type: 'permission', resource: 'rpc', lxm: ['com.example.syncNotes', 'com.example.getNotes'], inheritAud: true },
],
},
// A long title and detail, shown cut; the title from its one `en-` key;
// an authority of three labels, `test.example.com`.
// 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: its grant is shown as if asked for directly. Its namespace
// is `com.example.test.`, so the harness's other collections are outside.
// 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: 'Never shown: the set has no title.',
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',
@@ -124,6 +132,7 @@ 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',
@@ -222,6 +231,3 @@ export function textOf(main, field) {
}
return main?.[field]
}
/// An NSID's authority: its segments but the last, reversed.
export const authorityOf = (nsid) => nsid.split('.').slice(0, -1).reverse().join('.')
harness/look.mjs+8−1
@@ -7,6 +7,9 @@
// node look.mjs <state> [--scope '<scope>'] [--hint] [--details] [--phone | --desktop] [--light | --dark]
// node look.mjs email <kind> [--phone | --desktop] [--light | --dark]
//
// A `--scope` with `include:` tokens has them resolved from the harness's
// permission sets (lib/sets.mjs), hosted on a PDS of their own.
//
// States: sign-in, wrong-password, rate-limited, email-code, choose,
// consent, ended, busy, error, add-passkey, passkey-added, no-passkey.
// Without --phone or --desktop it draws both,
@@ -35,6 +38,7 @@ import { join, resolve } from 'node:path'
import { TestPlc } from '@atproto/dev-env'
import { Secp256k1Keypair } from '@atproto/crypto'
import { chromium } from 'playwright'
import { hostSets } from './lib/sets.mjs'
import { partsOf, startSmtp } from './lib/smtp.mjs'
const STATES = ['sign-in', 'wrong-password', 'rate-limited', 'email-code', 'choose', 'consent', 'ended', 'busy', 'error', 'add-passkey', 'passkey-added', 'no-passkey', 'email']
@@ -79,6 +83,7 @@ const rotation = await Secp256k1Keypair.create({ exportable: true })
const dataDir = mkdtempSync(join(tmpdir(), 'pds-look-'))
const smtp = state === 'email' ? await startSmtp({ user: 'look', password: 'look-pass', from: 'pds@localhost' }) : undefined
const log = join(dataDir, '..', `pds-look-${port}.log`)
const sets = /(^| )include[:?]/.test(value('--scope') ?? '') ? await hostSets(plc.url) : undefined
const server = spawn(join(root, 'target/release/pds'), ['serve'], {
env: {
...process.env,
@@ -94,12 +99,14 @@ const server = spawn(join(root, 'target/release/pds'), ['serve'], {
PDS_RATE_LIMITS_ENABLED: 'false',
PDS_DEV_MAIL_DIR: mkdtempSync(join(tmpdir(), 'pds-look-mail-')),
...(smtp ? { PDS_EMAIL_SMTP_URL: smtp.url, PDS_EMAIL_FROM: smtp.from } : {}),
...(sets ? { PDS_LEXICON_AUTHORITY_DID: sets.did, PDS_DISABLE_SSRF_PROTECTION: 'true' } : {}),
},
stdio: ['ignore', openSync(log, 'a'), openSync(log, 'a')],
})
const stop = async (code) => {
server.kill()
smtp?.close()
await sets?.pds.close()
await plc.close()
process.exit(code)
}
@@ -298,7 +305,7 @@ async function reach(ctx, page) {
await page.route('**/~api/consent', (r) => r.fulfill({ status: 400, contentType: 'application/json', body: '{"error":"invalid_request","error_description":"gone"}' }))
await button(page, 'Allow').click()
}
if (flag('--details')) await page.locator('details summary').first().click()
if (flag('--details')) for (const s of await page.locator('details summary').all()) await s.click()
}
const sizes = flag('--phone') ? ['phone'] : flag('--desktop') ? ['desktop'] : ['desktop', 'phone']
spec/OAUTH-PAGES.md+47−43
@@ -233,12 +233,13 @@ The view says who is asking and for which account:
into one row, and what a broader token covers is not said again. Each
row has a heading (`<h2>`) and a sentence, in plain words for someone
who knows nothing of atproto: no NSID, method or DID shows outside
`Technical details`. Where the scope includes a permission set
(`OAUTH-PERMISSION-SETS.md`), the set's own title and detail, written by
the app's author, say what it asks; everything else is said in words
that come from the scope alone, so they work for any app's lexicons.
The rows, in this order, the riskiest first, each only when the scope
has a token of it:
`Technical details` and a permission set's row. A permission set
(`OAUTH-PERMISSION-SETS.md`) the scope includes has a row of its own,
which shows the set as the reference's page does: its own title and
detail, written by the app's author, and what it grants. Everything
else is said in words that come from the scope alone, so they work for
any app's lexicons. The rows, in this order, the riskiest first, each
only when the scope has a token of it:
| Row | Heading | Sentence | From |
| --- | --- | --- | --- |
@@ -246,42 +247,40 @@ The view says who is asking and for which account:
| 2 | `Identity` | `Change your handle, and take over your account's identity, which could move your account elsewhere.` with `identity:*`; else `Change your handle.` | `identity:*`, `identity:handle` |
| 3 | `Account` | `<Account clauses>.` | `account:…`, `transition:email` |
| 4 | `Direct messages` | `Read and send your Bluesky direct messages.` | `transition:chat.bsky` |
| 5 | the set's title | the set's detail, or else `<Set clauses>.`; above it, quieter, `From <authority>` | each `include:` token whose set has a title, a row of its own, in the scope's order, unless the scope has `transition:generic` |
| 5 | the set's title, or else its NSID | the set's detail; or else, for a set with a title, its NSID; or else none. Then **What it grants** (below) | each `include:` token, a row of its own, in the scope's order |
| 6 | `All your data` | `<Actions> all your data.` | `repo:` tokens of collection `*`, unless the scope has `transition:generic` |
| 7 | `Your data in <app>`, one row for each app, in the order the scope first names it | `<Data clauses>.` | the other `repo:` collections, and those of the sets with no title, unless the scope has `transition:generic` |
| 7 | `Your data in <app>`, one row for each app, in the order the scope first names it | `<Data clauses>.` | the other `repo:` collections, unless the scope has `transition:generic` |
| 8 | `Uploads` | `Upload <kinds>.` | `blob:…`, unless the scope has `transition:generic` |
| 9 | `Other services` | `Act as you on <services>.` | `rpc:…`, and those of the sets with no title, unless the scope has `transition:generic` |
| 9 | `Other services` | `Act as you on <services>.` | `rpc:…`, unless the scope has `transition:generic` |
| 10 | `Permission` | the token, in `<code>` | each other token the server keeps but an `include:`, a row of its own, in the scope's order |
| 11 | `Who you are` | `See which account is yours.` | `atproto`, always |
A set's grant here is what its permissions grant with the `include:`'s
A set's grant is what its permissions grant with the `include:`'s
audience (`OAUTH-PERMISSION-SETS.md`, "What a set grants"); the page works
it out from `__authorizeData.permissionSets`, as the server does. A set
with no title is not named: its grant joins rows 7 and 9 as if the client
had asked for it directly. For a titled set:
it out from `__authorizeData.permissionSets`, as the server does. It is
said in the set's row alone: the other rows come from the scope's other
tokens, and `transition:generic` hides no set's row. In a set's row:
- **The title and detail** are `title:lang`'s `en`, or else its first key
that begins `en-`, or else `title`; likewise `detail`. A set has a title
when that gives one. Each is shown as plain text, never markup, a title
of more than 60 characters (Unicode code points) as its first 60 and
`…`, a detail of more than 140 as its first 140 and `…`.
*Note:* so that six rows still fit on a phone ("Seeing it all", below).
- **`From <authority>`** is an element of its own, between the heading and
the sentence. `<authority>` is the set's NSID's authority
(`atproto/nsid.md`): `com.example.calendar.basePermissions` is from
`calendar.example.com`, the domain whose DNS names the repository the
set was resolved from.
- **`<Set clauses>`**, for a set with no detail: for each app its
collections are in, in the order its grant's scope strings first name
them, that app's `<Data clauses>` (below) joined as a list, with
` in <app>` after them, so each app is named once; then, for its `rpc`
permissions, `act as you on <services>`; all joined with `; `. So a set
granting `repo:blue.flashes.feed.post?action=create&action=delete`,
`repo:blue.flashes.actor.profile?action=update` and
`rpc:blue.flashes.feed.getFeed?aud=*` reads `Add and remove posts and
change profiles in flashes.blue; act as you on any service.` A set
that grants nothing reads `Asks for nothing this server grants.`
(a detail) when that gives a string that is not empty. Each is shown
whole, as plain text, never markup; an NSID in their place is shown as
it is written, as plain text too.
- **What it grants** is a disclosure (`<details>`) after the sentence,
closed when the view appears, its summary `Details`. It holds the
sentence `The application requests the permissions necessary to perform
the following actions on your behalf:`, then the grant's tables below
(`<table>`, each with a header row of `<th>`), each only when the set
grants something of its kind. For a set that grants nothing, it holds
the sentence `Asks for nothing this server grants.` alone.
| Table | Header | Its rows (`<tr>` in `<tbody>`) |
| --- | --- | --- |
| calls | `Call`, `Towards` | each method of the grant's `rpc` permissions, once for each audience it is asked towards: the audiences sorted, and each audience's methods sorted. `Call` is the method, in `<code>`. `Towards` is in the first row of each audience alone, its cell spanning that audience's rows (`rowspan`): `Any service` for `*`; `Bluesky App services` for an audience beginning `did:web:api.bsky.app#`; `Bluesky Chat services` for one beginning `did:web:api.bsky.chat#`; `A service controlled by <host>` for any other `did:web:<host>#…`; or else the audience, in `<code>` |
| data | `Data`, `Create`, `Update`, `Delete` | each collection of the grant's `repo` permissions, once, sorted. `Data` is the collection, in `<code>`. Each action's cell holds a check (Lucide's `check`, `role="img"`, its accessible name `Yes`) when any `repo` permission of the grant asks that action of the collection, and is empty otherwise |
Sorted is in the order of Unicode code points. A table's cells hold
nothing but what this says.
In those sentences, a list of words is joined as `a`, `a and b`, or `a,
b and c`, and a sentence's first letter is a capital:
@@ -328,9 +327,11 @@ b and c`, and a sentence's first letter is a capital:
**Seeing it all.** Allow, Deny and Back (or Another account) are always
in view: at 360 by 740 and at 1200 by 900 CSS pixels, whatever the scope,
they are within the window when the view appears, without scrolling,
and the list scrolls behind them. When the list has six rows or fewer
and `Technical details` is closed, the whole view fits in the window at
both sizes, with nothing to scroll.
and the list scrolls behind them. When the list has six rows or fewer,
no set's title is longer than 60 characters (Unicode code points) nor
its detail longer than 140, and `Technical details` and every set's
`Details` are closed, the whole view fits in the window at both sizes,
with nothing to scroll.
What the `consent` and `reject` answers lead to:
@@ -468,9 +469,12 @@ which the harness keeps beside its steps. The reference's first view,
- The texts of the alerts, of **Email code**, of the passkey page's views
and of the error page.
- The consent list: its rows, in order, each heading and sentence word
for word, and nothing in `<code>` but a `Permission` row's token, for
the request's scope, with the clients and scopes of
`harness/checks/oauth.mjs` and more that merge and cover one another:
for word, and nothing in `<code>` but a `Permission` row's token and
what a set's tables put there; each set's `Details` closed, its
summary, its sentence, and its tables cell for cell, with each cell's
`rowspan`. For the request's scope, with the clients and scopes of
`harness/checks/oauth.mjs` and more, each asked for once before any is
asked for again, that merge and cover one another:
actions and collections of several `repo:` tokens of more than one app
with and without `repo:*`, camel-cased and plural-ending names, `blob:`
types under and beside `image/*`, `rpc:` services by `did:web`, by
@@ -478,11 +482,11 @@ which the harness keeps beside its steps. The reference's first view,
`transition:generic` over them, and the harness's permission sets
(`OAUTH-PERMISSION-SETS.md`, "How it is checked"): titled and not, with
and without a detail, in English and other languages, with a long title
and detail, and with a grant of nothing.
and detail, with a grant of nothing, and beside `transition:generic`.
- Seeing it all: on each consent view, Allow, Deny and Back (or Another
account) within the window; and with six rows or fewer, the
document's `scrollHeight` no taller than the window. Every flow's
device is 360 by 740 or 1200 by 900.
account) within the window; and with six rows or fewer, no set's title
or detail longer than above, the document's `scrollHeight` no taller
than the window. Every flow's device is 360 by 740 or 1200 by 900.
- `Technical details`, holding each token of the scope, and under each
`include:` the scope strings its set grants.
- Focus when each view appears.
web/src/lib/atoms/Icon.svelte+8−3
@@ -1,7 +1,9 @@
<script lang="ts" module>
// Lucide icons, drawn from their nodes: one icon wherever people act and go.
// Lucide icons, drawn from their nodes: one icon wherever people act and
// go, and a table's check, which has a `label` as its accessible name.
import {
ArrowLeft,
Check,
ChevronRight,
ExternalLink,
Globe,
@@ -13,6 +15,7 @@
const icons = {
'arrow-left': ArrowLeft,
check: Check,
'chevron-right': ChevronRight,
'device-desktop': Monitor,
globe: Globe,
@@ -26,7 +29,7 @@
</script>
<script lang="ts">
let { name, size = 16 }: { name: IconName; size?: number } = $props();
let { name, size = 16, label }: { name: IconName; size?: number; label?: string } = $props();
</script>
<svg
@@ -39,7 +42,9 @@
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
role={label ? 'img' : undefined}
aria-label={label}
aria-hidden={label ? undefined : 'true'}
focusable="false"
>{#each icons[name] as [tag, attrs], i (i)}<svelte:element this={tag} {...attrs} />{/each}</svg
>
web/src/lib/molecules/Grant.sveltenew+117−0
@@ -0,0 +1,117 @@
<script lang="ts">
import Icon from '#lib/atoms/Icon.svelte';
import type { Grant } from '#lib/scopes';
import { words } from '#lib/words';
// What a permission set grants, behind its `Details` disclosure: the
// calls it may make, where to, and the data it may change.
let { grant }: { grant: Grant } = $props();
// An NSID's or DID's runs, each ending at a `.`, `:` or `#`, where it may wrap.
const runs = (name: string): string[] => name.split(/(?<=[.:#])/);
</script>
{#snippet code(name: string)}<code>{#each runs(name) as run, i (i)}{run}<wbr />{/each}</code>{/snippet}
<details class="details">
<summary>{words.setDetails}</summary>
<div class="body">
{#if grant.calls.length || grant.data.length}
<p>{words.setRequests}</p>
{#if grant.calls.length}
<table>
<thead><tr><th>{words.call}</th><th>{words.towards}</th></tr></thead>
<tbody>
{#each grant.calls as { aud, towards, methods } (aud)}
{#each methods as method, i (method)}
<tr>
<td>{@render code(method)}</td>
{#if i === 0}<td rowspan={methods.length}>{#if typeof towards === 'string'}{towards}{:else}{@render code(towards.code)}{/if}</td>{/if}
</tr>
{/each}
{/each}
</tbody>
</table>
{/if}
{#if grant.data.length}
<table>
<thead>
<tr><th>{words.data}</th>{#each words.actions as action (action)}<th class="action">{action}</th>{/each}</tr>
</thead>
<tbody>
{#each grant.data as { collection, actions } (collection)}
<tr>
<td>{@render code(collection)}</td>
{#each actions as asked, i (i)}<td class="action">{#if asked}<Icon name="check" size={14} label={words.yes} />{/if}</td>{/each}
</tr>
{/each}
</tbody>
</table>
{/if}
{:else}
<p>{words.setGrantsNothing}</p>
{/if}
</div>
</details>
<style>
.details {
font-size: var(--text-sm);
}
summary {
width: fit-content;
color: var(--mute);
font-weight: var(--weight-medium);
cursor: pointer;
border-radius: var(--radius-sm);
}
summary:hover {
color: var(--fg);
}
.body {
display: flex;
flex-direction: column;
gap: var(--space-2);
margin-top: var(--space-2);
padding: var(--space-2-5) var(--space-3);
border-radius: var(--radius-md);
background: var(--soft);
color: var(--mute);
font-size: var(--text-xs);
line-height: var(--leading-snug);
}
table {
width: 100%;
border-collapse: collapse;
}
th,
td {
padding: var(--space-1) var(--space-1-5);
border-bottom: var(--border) solid var(--line);
text-align: left;
vertical-align: top;
overflow-wrap: anywhere;
}
th {
font-weight: var(--weight-medium);
}
.action {
width: 1%;
text-align: center;
vertical-align: middle;
white-space: nowrap;
overflow-wrap: normal;
}
code {
color: var(--fg);
overflow-wrap: anywhere;
}
</style>
web/src/lib/molecules/Permission.svelte+5−11
@@ -1,15 +1,16 @@
<script lang="ts">
import Grant from '#lib/molecules/Grant.svelte';
import type { Item } from '#lib/scopes';
// What one kind of thing a scope asks for: its heading, whose it is when
// a permission set says, and its sentence.
// What one kind of thing a scope asks for: its heading, its sentence, and
// for a permission set, what it grants.
let { item }: { item: Item } = $props();
</script>
<li class="permission">
<h2>{item.heading}</h2>
{#if item.from}<p class="from">{item.from}</p>{/if}
<p class="sentence">{#each item.sentence as part, i (i)}{#if typeof part === 'string'}{part}{:else}<code>{part.code}</code>{/if}{/each}</p>
{#if item.sentence.length}<p class="sentence">{#each item.sentence as part, i (i)}{#if typeof part === 'string'}{part}{:else}<code>{part.code}</code>{/if}{/each}</p>{/if}
{#if item.grant}<Grant grant={item.grant} />{/if}
</li>
<style>
@@ -26,13 +27,6 @@
overflow-wrap: anywhere;
}
.from {
color: var(--faint);
font-size: var(--text-sm);
line-height: var(--leading-tight);
overflow-wrap: anywhere;
}
.sentence {
color: var(--mute);
font-size: var(--text-sm);
web/src/lib/scopes.ts+61−40
@@ -9,8 +9,18 @@
// A run of a sentence: text, or a token shown as code (a Permission row's).
export type Part = string | { code: string };
// A row: its heading and sentence, and for a permission set's, whose it is.
export type Item = { heading: string; from?: string; sentence: Part[] };
// What a permission set grants, as its row's Details shows it: the calls,
// by audience (sorted), each audience's methods sorted and where they go
// said; and the data, by collection (sorted), with whether each of
// create, update and delete is asked.
export type Grant = {
calls: { aud: string; towards: Part; methods: string[] }[];
data: { collection: string; actions: boolean[] }[];
};
// A row: its heading and sentence (maybe none), and for a permission set's,
// what it grants.
export type Item = { heading: string; sentence: Part[]; grant?: Grant };
const FULL_ACCESS =
'Read and change all your data, upload files and act as you on other services, as an app password can.';
@@ -50,10 +60,6 @@ const ACTIONS: [string, string][] = [
];
const ALL_ACTIONS = ACTIONS.map(([a]) => a);
// A titled set's row: its title and detail cut to these many characters.
const TITLE_MAX = 60;
const DETAIL_MAX = 140;
const NOTHING_GRANTED = 'Asks for nothing this server grants.';
type Token = { resource: string; positional?: string; params: Map<string, string[]> };
@@ -336,35 +342,54 @@ function textOf(doc: Record<string, unknown> | null, field: string): string | un
return typeof text === 'string' && text ? text : undefined;
}
// The first `max` characters of a text and `…`, when it is longer.
function cut(text: string, max: number): string {
const chars = Array.from(text);
return chars.length > max ? `${chars.slice(0, max).join('')}…` : text;
// Sorted by Unicode code point.
const sorted = (xs: Iterable<string>): string[] =>
[...xs].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
// Where a call goes, in words, or else its audience as code.
function towardsOf(aud: string): Part {
if (aud === '*') return 'Any service';
if (aud.startsWith('did:web:api.bsky.app#')) return 'Bluesky App services';
if (aud.startsWith('did:web:api.bsky.chat#')) return 'Bluesky Chat services';
const hash = aud.indexOf('#');
if (aud.startsWith('did:web:') && hash >= 0)
return `A service controlled by ${aud.slice('did:web:'.length, hash)}`;
return { code: aud };
}
// An NSID's authority: its segments but the last, reversed.
const authorityOf = (nsid: string): string => nsid.split('.').slice(0, -1).reverse().join('.');
// <Set clauses>: each app's <Data clauses>, ` in <app>` after each, apps and
// collections in the order the grant's scope strings first name them; then
// `act as you on <services>` for its `rpc` permissions.
function setClauses(grant: string[]): string {
const tokens = grant.map(parse).filter((t): t is Token => t !== null);
const asked = askedOf(tokens.filter((t) => t.resource === 'repo'));
const clauses = [...clausesByApp(asked)].map(([app, own]) => `${joined(own)} in ${app}`);
const rpcs = tokens.filter((t) => t.resource === 'rpc');
const auds = rpcs.map((t) => t.params.get('aud')?.[0] ?? '').filter(Boolean);
if (auds.length) clauses.push(`act as you on ${joined(servicesOf(auds))}`);
return clauses.length ? said(clauses.join('; ')) : NOTHING_GRANTED;
// A set's grant as its Details' tables: every method once for each
// audience, and every action any `repo` permission asks of each collection.
function grantTables(kept: Kept[]): Grant {
const calls = new Map<string, Set<string>>();
const asked = new Map<string, Set<string>>();
const add = (into: Map<string, Set<string>>, key: string, xs: string[]) =>
into.set(key, new Set([...(into.get(key) ?? []), ...xs]));
for (const k of kept) {
if (k.resource === 'rpc') add(calls, k.aud, k.methods);
else for (const c of k.collections) add(asked, c, k.actions);
}
return {
calls: sorted(calls.keys()).map((aud) => ({
aud,
towards: towardsOf(aud),
methods: sorted(calls.get(aud) ?? [])
})),
data: sorted(asked.keys()).map((collection) => ({
collection,
actions: ALL_ACTIONS.map((a) => asked.get(collection)?.has(a) ?? false)
}))
};
}
// A titled set's row: its title, whose it is, and its detail or else what it grants.
function setRow(set: PermissionSet, title: string): Item {
const detail = textOf(set.doc, 'detail');
// A set's row: its title or else its NSID; its detail, or else for a set
// with a title its NSID, or else no sentence; and what it grants.
function setRow(set: PermissionSet): Item {
const title = textOf(set.doc, 'title');
const detail = textOf(set.doc, 'detail') ?? (title ? set.nsid : undefined);
return {
heading: cut(title, TITLE_MAX),
from: `From ${authorityOf(set.nsid)}`,
sentence: [detail ? cut(detail, DETAIL_MAX) : setClauses(set.kept.map(written))]
heading: title ?? set.nsid,
sentence: detail ? [detail] : [],
grant: grantTables(set.kept)
};
}
@@ -380,16 +405,15 @@ export const detailsOf = (
tokensOf(scope).map((token) => ({ token, grant: grantOf(token, sets) ?? [] }));
// The rows of what a scope asks for, in the order spec/OAUTH-PAGES.md gives.
// A titled set has a row of its own; an untitled one's grant is read as if
// the scope asked for it in the `include:`'s place. An `include:` is never
// a Permission row.
// Each set has a row of its own, whatever else the scope asks; an
// `include:` is never a Permission row.
export function rowsOf(scope: string, sets?: Record<string, unknown>): Item[] {
const tokens = [...new Set(tokensOf(scope))];
const has = (t: string) => tokens.includes(t);
const generic = has('transition:generic');
const of = new Map<Resource, Token[]>(RESOURCES.map((r) => [r, []]));
const others: string[] = [];
const titled: Item[] = [];
const included: Item[] = [];
const take = (token: string) => {
const t = parse(token);
const kind = RESOURCES.find((r) => r === t?.resource);
@@ -399,11 +423,8 @@ export function rowsOf(scope: string, sets?: Record<string, unknown>): Item[] {
for (const token of tokens) {
if (Object.hasOwn(NAMED, token)) continue;
const set = setOf(token, sets);
const title = set && textOf(set.doc, 'title');
if (!set) {
if (parse(token)?.resource !== 'include') take(token);
} else if (!title) set.kept.map(written).forEach(take);
else if (!generic) titled.push(setRow(set, title));
if (set) included.push(setRow(set));
else if (parse(token)?.resource !== 'include') take(token);
}
const kind = (r: Resource) => of.get(r) ?? [];
const rows: (Item | null)[] = [
@@ -413,7 +434,7 @@ export function rowsOf(scope: string, sets?: Record<string, unknown>): Item[] {
has('transition:chat.bsky')
? { heading: 'Direct messages', sentence: ['Read and send your Bluesky direct messages.'] }
: null,
...titled,
...included,
...(!generic ? dataRows(kind('repo')) : []),
!generic && kind('blob').length ? uploadsRow(kind('blob')) : null,
!generic && kind('rpc').length ? servicesRow(kind('rpc')) : null,
web/src/lib/words.ts+10−1
web/AGENTS.md+1−1