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

consent: spaces in plain words, from the page's spaces and spaceHandles

Merged chadtmiller.com asked to merge into main from chadtmiller.com/monolith:consent/spaces
.changeset/consent-spaces.mdnew+7−0
@@ -0,0 +1,7 @@
---
default: minor
---
# Consent shows space permissions in plain words
The consent page now says what an app asks of spaces, in the same plain words as its other rows, rather than listing each `space:` token as it is written. Each space an app asks for has a row of its own, named by whose spaces they are and the type's title: "Your Workspace spaces", "@bob.test's Board spaces", "Every space you're in". Its sentence says what the app may do there: read everything, or only what you've written; add, change or remove which kinds of records; make new spaces, change who's in them or delete them. A permission set's `Details` lists its spaces the same way. To say this, the authorization page's `__authorizeData` now carries `spaces`, each space type's declaration, and `spaceHandles`, the verified handles of the accounts that own the spaces asked for, when the scope asks for any space, as the reference's spaces alpha does.
.claude/skills/ui/SKILL.md+1−0
@@ -37,6 +37,7 @@ just look consent # loopback client, atproto transition:generic,
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 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 consent --scope 'atproto space:com.example.workspace space:*?authority=*&action=read_self include:com.example.forum.access' # spaces, with the harness's declarations
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
crates/pds-server/src/oauth/page.rs+62−5
@@ -448,9 +448,11 @@ pub(super) async fn authorize(
// declarations").
let scope = &loaded.request.scope;
let sets = svc.oauth.sets.resolve_all(&svc, scope).await;
if let Ok(s) = &sets
&& svc.oauth.sets.resolve_spaces(&svc, scope, s).await.is_err()
{
let spaces = match &sets {
Ok(s) => svc.oauth.sets.resolve_spaces(&svc, scope, s).await.map(Some),
Err(_) => Ok(None),
};
let Ok(spaces) = spaces else {
let mut tx = Tx::new(&svc);
let ended = tx.change(|st, _| match st.requests.get(id) {
Some(r) => {
@@ -466,9 +468,26 @@ pub(super) async fn authorize(
Some((r, back)) => redirect_to(&r.response_mode, &r.redirect_uri, &back),
None => bad_page("Unknown or ended request"),
};
}
};
let mut r = match sets {
Ok(sets) => authorization_page(&svc, request_uri, &client, &loaded, &sets, &device.id),
Ok(sets) => {
// With a `space` permission, the declarations and the
// handles of the scope's spaces' owners that verify
// (`spec/OAUTH-SCOPES.md`, "On the authorization page").
let spaces = match spaces {
Some(spaces) if super::sets::has_space(scope, &sets) => {
let mut handles = Map::new();
for did in super::space_scope::authorities(scope.iter().map(String::as_str)) {
if let Some(h) = verified_handle(&svc, &did).await {
handles.insert(did, json!(h));
}
}
Some((spaces, handles))
}
_ => None,
};
authorization_page(&svc, request_uri, &client, &loaded, &sets, spaces, &device.id)
}
Err((nsid, _)) => error_page(400, "invalid_scope", &format!("Permission set {nsid} could not be resolved")),
};
device_cookie(&svc, &mut r, &device);
@@ -490,6 +509,35 @@ pub(super) fn csrf_cookie(svc: &Service, r: &mut Response) {
}
}
/// The handle of `did` when it verifies (`spec/OAUTH-SCOPES.md`, "On the
/// authorization page"): the DID's document's first `at://` name, a valid
/// handle, that resolves to `did` as `spec/IDENTITY.md` resolves an
/// external one, by DNS and HTTPS, even an account's here, lowercased for
/// that alone; as the document writes it, its case kept. None when any
/// step fails.
async fn verified_handle(svc: &Service, did: &str) -> Option<String> {
let doc = crate::proxy::resolve_did(svc, did).await.ok()?;
let name = doc["alsoKnownAs"]
.as_array()?
.iter()
.filter_map(Json::as_str)
.find(|u| u.starts_with("at://"))?;
let given = name.strip_prefix("at://")?;
let handle = given.to_lowercase();
if !pds_repo::data::valid_handle(&handle) {
return None;
}
let verified = crate::identity::handle_resolves_to(svc, &handle, did).await;
verified.then(|| given.to_string())
}
/// A page's space type declarations, by NSID, and its owners' verified
/// handles, by DID (`spaceHandles`).
type PageSpaces = (
std::collections::HashMap<String, std::sync::Arc<Json>>,
Map<String, Json>,
);
/// The authorization page of a request loaded on device `device`, which it
/// gives a new passkey challenge (`spec/PASSKEYS.md`, "The page's options").
fn authorization_page(
@@ -498,6 +546,7 @@ fn authorization_page(
client: &client::Client,
loaded: &Loaded,
sets: &std::collections::HashMap<String, std::sync::Arc<Json>>,
spaces: Option<PageSpaces>,
device: &str,
) -> Response {
let r = &loaded.request;
@@ -507,6 +556,14 @@ fn authorization_page(
"clientTrusted": false, "clientFirstParty": false, "scope": r.scope.join(" "),
"permissionSets": sets.iter().map(|(nsid, main)| (nsid.clone(), (**main).clone())).collect::<Map<String, Json>>(),
});
if let Some((spaces, handles)) = spaces {
data["spaces"] = spaces
.into_iter()
.map(|(nsid, main)| (nsid, (*main).clone()))
.collect::<Map<String, Json>>()
.into();
data["spaceHandles"] = handles.into();
}
// A public client's request always has its kept prompt; a confidential one's may have none.
if let Some(p) = &r.prompt {
data["promptMode"] = json!(p);
crates/pds-server/src/oauth/sets.rs+40−0
@@ -609,6 +609,15 @@ pub(crate) fn space_types(scope: &[String], sets: &HashMap<String, Arc<Json>>) -
super::space_scope::types(granted(scope, sets).iter().map(|t| t.as_ref()))
}
/// Whether a scope, with what its sets `sets` grant, has a `space`
/// permission: whether the authorization page gives `spaces` and
/// `spaceHandles` (`spec/OAUTH-SCOPES.md`, "On the authorization page").
pub(crate) fn has_space(scope: &[String], sets: &HashMap<String, Arc<Json>>) -> bool {
granted(scope, sets)
.iter()
.any(|t| super::space_scope::SpacePermission::of(t).is_some())
}
/// A scope expanded for the account `did` (`granted`), each `space:` string
/// then rewritten (`super::space_scope::rewritten`).
pub(crate) fn expand(scope: &[String], e: &Expansion, did: &str) -> Vec<String> {
@@ -778,6 +787,37 @@ mod tests {
);
}
/// When the authorization page has `spaces` and `spaceHandles`, and the
/// DIDs whose handles it verifies: a `space:` token's, or a set's
/// `space` permission's, makes both; only the scope's own tokens name
/// the DIDs, each once.
#[test]
fn on_the_page() {
const SET: &str = "com.example.forum.access";
let main = json!({ "type": "permission-set", "permissions": [
{ "type": "permission", "resource": "space", "spaceType": "com.example.forum.board", "authority": "did:plc:set" },
] });
let sets = HashMap::from([(SET.to_string(), Arc::new(main))]);
let scope = |s: &str| s.split(' ').map(str::to_string).collect::<Vec<_>>();
let dids =
|s: &[String]| super::super::space_scope::authorities(s.iter().map(String::as_str));
// No space permission: neither key.
let none = scope("atproto repo:* include:com.example.other.set space:forum");
assert!(!has_space(&none, &sets));
// One of `*` alone is one.
assert!(has_space(&scope("atproto space:*?authority=*"), &sets));
// A set's grant alone: the keys, but no DID to verify.
let set = scope("atproto include:com.example.forum.access");
assert!(has_space(&set, &sets));
assert!(dids(&set).is_empty());
// The scope's DIDs, each once, in order; `self` and `*` none.
let own = scope(
"atproto include:com.example.forum.access space:a.b.c?authority=did:plc:b space:*?authority=did:web:a.com space:a.b.c?authority=did:plc:b&action=read space:a.b.c space:*?authority=* space:a.b.c?authority=me",
);
assert!(has_space(&own, &sets));
assert_eq!(dids(&own), ["did:plc:b", "did:web:a.com"]);
}
/// The `space` rows of `spec/OAUTH-PERMISSION-SETS.md`, "As scope
/// strings", and each reason a `space` permission is dropped, alone; then
/// its types resolved and its strings rewritten in the expansion.
crates/pds-server/src/oauth/space_scope.rs+13−0
@@ -291,6 +291,19 @@ pub(crate) fn types<'a>(scope: impl IntoIterator<Item = &'a str>) -> Vec<String>
out
}
/// The DIDs `space:` tokens name as their `authority`, each once, in the
/// order first named: whose handles the authorization page verifies
/// (`spec/OAUTH-SCOPES.md`, "On the authorization page").
pub(crate) fn authorities<'a>(scope: impl IntoIterator<Item = &'a str>) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for p in scope.into_iter().filter_map(SpacePermission::of) {
if p.authority.starts_with("did:") && !out.contains(&p.authority) {
out.push(p.authority);
}
}
out
}
/// A token of a session's scope, as its tokens keep it
/// (`spec/OAUTH-SCOPES.md`, "The token's scope"): a `space:` token with no
/// collection gets its declaration's, and one of authority `self` gets
harness/checks/pages.mjs+149−18
@@ -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, grantOf, inc, includeOf, textOf } from '../lib/sets.mjs'
import { SETS, SPACE_TYPES, 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'
@@ -51,7 +51,7 @@ const PAGE_CLIENTS = [
{ scope: 'atproto repo:app.bsky.feed.post?action=create&action=delete repo:app.bsky.feed.like repo:com.example.foo?action=update repo:*?action=create blob:image/png blob:image/* blob:text/plain rpc:app.bsky.feed.getTimeline?aud=did:web:api.bsky.app%23bsky_appview rpc:app.bsky.actor.getProfile?aud=did:web:api.bsky.app%23bsky_appview rpc:app.bsky.actor.getProfile?aud=* rpc:*?aud=did:web:svc.test%23x account:email identity:handle' },
{ scope: 'atproto repo:* repo:app.bsky.feed.post account:email?action=manage account:status account:repo?action=manage blob:*/* blob:image/*' },
{ scope: 'atproto transition:generic transition:email transition:chat.bsky repo:app.bsky.feed.post repo:* rpc:*?aud=did:web:api.bsky.app%23bsky_appview blob:image/* account:email?action=manage account:status?action=manage account:repo identity:handle identity:*' },
{ scope: 'atproto repo:app.bsky.graph.listItem repo:com.example.notes?action=update repo:app.bsky.graph.follow?action=create repo:com.example.status repo:app.bsky.feed.post?action=create&action=delete rpc:com.example.ping?aud=did:plc:aaaaaaaaaaaaaaaaaaaaaaaa%23svc rpc:com.example.pong?aud=did:plc:bbbbbbbbbbbbbbbbbbbbbbbb%23svc rpc:com.example.ping?aud=did:web:api.example.com%23a rpc:com.example.pong?aud=did:web:api.example.com%23b blob:application/json blob:text/plain blob:image/png' },
{ scope: 'atproto repo:app.bsky.graph.listItem repo:com.example.notes?action=update repo:app.bsky.graph.follow?action=create repo:com.example.status repo:app.bsky.feed.post?action=create&action=delete repo:com.example.diaryEntry?action=create repo:com.example.inbox rpc:com.example.ping?aud=did:plc:aaaaaaaaaaaaaaaaaaaaaaaa%23svc rpc:com.example.pong?aud=did:plc:bbbbbbbbbbbbbbbbbbbbbbbb%23svc rpc:com.example.ping?aud=did:web:api.example.com%23a rpc:com.example.pong?aud=did:web:api.example.com%23b blob:application/json blob:text/plain blob:image/png' },
{ scope: `atproto ${inc(SETS.full, true)} ${inc(SETS.titleOnly)} repo:com.example.foo?action=create identity:handle` },
{ 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/*` },
@@ -142,10 +142,14 @@ const ACCOUNT = {
const KIND = { image: 'images', video: 'videos', audio: 'audio', text: 'text' }
/// The domain an NSID's namespace is rooted at: its first two segments, reversed.
const appOf = (nsid) => nsid.split('.').slice(0, 2).reverse().join('.')
/// An NSID's last segment as a plain thing: words, lower case, plural.
/// An NSID's last segment as a plain thing: words, lower case, its last
/// made plural (spec/OAUTH-PAGES.md, "<Data clauses>").
const thingOf = (nsid) => {
const words = nsid.split('.').at(-1).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase()
return words.endsWith('s') ? words : `${words}s`
if (words.endsWith('s')) return words
if (/[b-df-hj-np-tv-z]y$/.test(words)) return `${words.slice(0, -1)}ies`
if (/(x|z|ch|sh)$/.test(words)) return `${words}es`
return `${words}s`
}
/// A permission's resource, positional parameter and query, from either
@@ -199,10 +203,76 @@ function servicesOf(rpcs) {
/// A text's length in Unicode code points.
const length = (s) => [...s].length
/// A space type's name (spec/OAUTH-PAGES.md, "<Space heading>"): its
/// declaration's title, or else its NSID's last segment in words.
function spaceName(type, spaces) {
const t = textOf(spaces?.[type], 'title')
if (typeof t === 'string' && t !== '') return t
const w = type.split('.').at(-1).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase()
return capital(w)
}
/// The spaces `space` permissions `ps` name, merged by type, authority and
/// key, as spec/OAUTH-PAGES.md says them ("<Space heading>", "<Space
/// clauses>"), with `spaces` and `handles` the page's `spaces` and
/// `spaceHandles`: each `{heading, sentence, codes}`, in the order first
/// named.
function spaceRows(ps, spaces, handles) {
const groups = new Map()
for (const p of ps) {
const type = values(p, 'spaceType')[0]
const authority = p.q.get('authority') ?? 'self'
const skey = p.q.get('skey') ?? '*'
const key = JSON.stringify([type, authority, skey])
if (!groups.has(key)) groups.set(key, { type, authority, skey, read: false, readSelf: false, writes: new Map(), manage: new Set() })
const g = groups.get(key)
const given = p.q.getAll('action')
const actions = given.length ? given : ['read', 'create', 'update', 'delete']
if (actions.includes('read')) g.read = true
if (actions.includes('read_self')) g.readSelf = true
let colls = p.q.getAll('collection')
if (!colls.length && type !== '*') colls = Array.isArray(spaces?.[type]?.collections) ? spaces[type].collections : []
const writes = actions.filter((a) => ACTIONS.some(([x]) => x === a))
if (writes.length) {
for (const c of colls) {
if (!g.writes.has(c)) g.writes.set(c, new Set())
for (const a of writes) g.writes.get(c).add(a)
}
}
for (const m of p.q.getAll('manage')) g.manage.add(m)
}
return [...groups.values()].map((g) => {
const did = g.authority.startsWith('did:')
const owner = did ? (handles?.[g.authority] ? `@${handles[g.authority]}` : g.authority) : null
const name = g.type === '*' ? null : spaceName(g.type, spaces)
let heading = g.type === '*'
? (g.authority === 'self' ? 'All your spaces' : g.authority === '*' ? "Every space you're in" : `All of ${owner}'s spaces`)
: (g.authority === 'self' ? `Your ${name} spaces` : g.authority === '*' ? `Everyone's ${name} spaces` : `${owner}'s ${name} spaces`)
if (g.skey !== '*') heading += ` named “${g.skey}”`
const clauses = []
if (g.read) clauses.push('read everything in them')
else if (g.readSelf) clauses.push("see what you've written in them")
const star = g.writes.get('*')
const byActions = new Map()
for (const [c, acts] of g.writes) {
if (c !== '*' && star && [...acts].every((a) => star.has(a))) continue
const k = ACTIONS.filter(([a]) => acts.has(a)).map(([a]) => a).join(',')
if (!byActions.has(k)) byActions.set(k, [])
byActions.get(k).push(c === '*' ? 'anything' : thingOf(c))
}
for (const [k, things] of byActions) clauses.push(`${verbs(new Set(k.split(',')))} ${join(things)}`)
const manage = [['create', 'make new ones'], ['update', "change who's in them"], ['delete', 'delete them']].filter(([m]) => g.manage.has(m)).map(([, w]) => w)
if (manage.length) clauses.push(join(manage))
const sentence = clauses.length ? `${capital(clauses.join('; '))}.` : 'Asks for nothing this server grants.'
return { heading, sentence, codes: did && !handles?.[g.authority] ? [g.authority] : [] }
})
}
/// 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) {
/// it grants"): `{summary, sentence, tables, spaces}`, each table `{head,
/// rows}` and each row `{cells, spans}`, a cell's text and its `rowspan`;
/// each space `{heading, sentence}`.
function grantDetails(grant, spaces, handles) {
const ps = grant.map(permission)
const sorted = (xs) => [...xs].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0))
const calls = new Map()
@@ -227,13 +297,16 @@ function grantDetails(grant) {
...(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])]
const spaceList = spaceRows(ps.filter((p) => p.resource === 'space'), spaces, handles)
// In `<code>`: methods, collections, an audience said by no words, and a
// space's owner with no handle.
const codes = [...callRows.flatMap(({ cells }) => cells.filter((c, i) => i === 0 || (i === 1 && calls.has(c)))), ...dataRows.map(({ cells }) => cells[0]), ...spaceList.flatMap((s) => s.codes)]
return {
details: {
summary: 'Details',
sentence: grant.length ? 'The application requests the permissions necessary to perform the following actions on your behalf:' : 'Asks for nothing this server grants.',
tables,
spaces: spaceList.map(({ heading, sentence }) => ({ heading, sentence })),
},
codes,
}
@@ -241,11 +314,13 @@ function grantDetails(grant) {
/// 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, 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 = {}) {
/// `sets` (the page's `permissionSets`), its space types' declarations
/// `spaces` and owners' handles `handles` (the page's `spaces` and
/// `spaceHandles`): 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 = {}, spaces = {}, handles = {}) {
const has = (t) => tokens.includes(t)
const generic = has('transition:generic')
const parsed = tokens.map((t) => [t, permission(t)])
@@ -271,6 +346,8 @@ export function consentRows(tokens, sets = {}) {
if (has('transition:chat.bsky')) rows.push(row('Direct messages', 'Read and send your Bluesky direct messages.'))
for (const s of spaceRows(of('space'), spaces, handles)) rows.push(row(s.heading, s.sentence, s.codes))
for (const token of tokens) {
const i = includeOf(token)
if (!i) continue
@@ -281,7 +358,7 @@ export function consentRows(tokens, sets = {}) {
}
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))
const { details, codes } = grantDetails(grantOf(i.nsid, main, i.aud), spaces, handles)
rows.push({ heading: title ?? i.nsid, sentence: detail ?? (title ? i.nsid : ''), codes, details })
}
@@ -532,9 +609,9 @@ async function checkView(w, view, ctx = {}) {
/// "Consent").
async function checkConsent(w, ctx) {
const { page } = w
const { scope, sets } = await page.evaluate(() => ({ scope: window.__authorizeData?.scope ?? '', sets: window.__authorizeData?.permissionSets ?? {} }))
const { scope, sets, spaces, handles } = await page.evaluate(() => ({ scope: window.__authorizeData?.scope ?? '', sets: window.__authorizeData?.permissionSets ?? {}, spaces: window.__authorizeData?.spaces ?? {}, handles: window.__authorizeData?.spaceHandles ?? {} }))
const tokens = scope.split(' ').filter(Boolean)
const { rows: want, short } = consentRows(tokens, sets)
const { rows: want, short } = consentRows(tokens, sets, spaces, handles)
const rowDetails = 'main ul > li details'
const closed = await page.evaluate((sel) => {
const ds = [...document.querySelectorAll(sel)]
@@ -555,10 +632,15 @@ async function checkConsent(w, ctx) {
const ds = [...li.querySelectorAll('details')].map((d) => {
const summary = d.querySelector('summary')
const body = d.cloneNode(true)
for (const h3 of body.querySelectorAll('h3')) {
if (h3.nextElementSibling?.tagName === 'P') h3.nextElementSibling.remove()
h3.remove()
}
for (const x of body.querySelectorAll('summary, table')) x.remove()
return {
summary: summary ? text(summary) : null,
sentence: text(body),
spaces: [...d.querySelectorAll('h3')].map((h3) => ({ heading: text(h3), sentence: h3.nextElementSibling?.tagName === 'P' ? text(h3.nextElementSibling) : null })),
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) })),
@@ -1095,6 +1177,47 @@ async function alertsFlow() {
await dev.ctx.close()
}
/// The clients whose consent views show spaces, `other` the DID of an
/// account of the server, whose handle verifies (spec/OAUTH-PAGES.md, "How
/// it is checked"): a bare type merged with one managing it, another's,
/// every space of each authority, the set granting spaces, a type with a
/// key, collections of another app and `*`, a DID with no handle, and
/// writes with no collection to write.
harness/checks/pages.mjslines 1180 to 1185
review.knotless.dev

other is an account of the server, but its handle doesn't verify here: no handle in the run resolves by DNS or HTTPS (spec/OAUTH-PAGES.md, "How it is checked"), so it shows as its DID. The comment should say that, not "whose handle verifies".

function spaceClients(other) {
const W = SPACE_TYPES.workspace
const B = SPACE_TYPES.board
const nobody = 'did:plc:aaaaaaaaaaaaaaaaaaaaaaaa'
return [
`atproto space:${W} space:${W}?manage=create&manage=update space:${B}?authority=${other}&action=read space:*?authority=*&action=read_self repo:com.example.profile`,
`atproto include:${SETS.forum} space:${B}?action=create&collection=com.example.zz.thing&collection=*&collection=com.example.forum.post space:${W}?skey=main&action=read_self space:*?authority=${nobody}&action=read`,
`atproto space:*?action=create space:*?authority=${other}&manage=delete space:${B}?authority=*&action=update&action=delete space?spaceType=${W}&collection=com.example.zz.thing&action=create&action=read_self transition:generic`,
]
}
/// A consent view asking for `scope`'s spaces, on the server alone, as the
/// reference keeps no `space:` permission: signed in on a new device, its
/// view held to the spec, and no further (spec/OAUTH-PAGES.md, "Consent",
/// "How it is checked").
async function spacesFlow(scope) {
const acct = pick(accountsToSignIn())
const req = await newRequest(acct, { client: { scope, redirects: ['http://127.0.0.1/callback'] }, whole: true, kind: 'PAR (pages, spaces)', extra: () => ({ login_hint: undefined, ui_locales: undefined, prompt: undefined }) })
if (!req) return
current = { flow: 'a consent with spaces', step: run.step, scope }
const dev = await device(cand, chance(0.5))
const w = await open(dev, req.redirect)
await w.page.goto(pageOf(cand, req))
if ((await viewOf(w)) !== 'signIn') return held('the first view on a new device', 'Sign in', await shown(w))
await textbox(w, SERVER.identifier).fill(handleOf(acct))
await textbox(w, SERVER.password).fill(acct.password)
const answered = w.page.waitForResponse((r) => r.url().includes('/~api/sign-in'))
await button(w, SERVER.signIn).click()
await answered
if ((await viewOf(w)) !== 'consent') return held('the view after a sign-in', 'Allow access', await shown(w))
await checkView(w, 'consent', { appeared: true, loopback: true })
count('pages: a consent with spaces', true)
await dev.ctx.close()
}
/// A sign-in held on its way, once a run: the button busy, every button
/// disabled, until it is answered (spec/OAUTH-PAGES.md, "Every page").
let busyChecked = false
@@ -1248,7 +1371,13 @@ async function passkeySignInView(w, client, remember, extra = {}) {
// A tab reused from a flow that landed at the client lands again only by this one.
w.landed = null
w.location = null
const res = await w.page.goto(req.page)
// The tab's last landing at the client, whose redirect URI nothing serves,
// may still be on its way to the browser's error page.
const res = await w.page.goto(req.page).catch(async (e) => {
if (!/interrupted by another navigation/.test(String(e))) throw e
await w.page.waitForLoadState().catch(() => {})
return w.page.goto(req.page)
})
await checkDocument(w, res)
if ((await viewOf(w)) !== 'signIn') return void (await held('the first view on a device with no account', SERVER.headings.signIn, await shown(w)))
await checkView(w, 'signIn', { first: true, appeared: true })
@@ -1533,6 +1662,8 @@ export async function pagesRun() {
browser = await chromium.launch()
await errorFlow()
await alertsFlow()
const other = accountsToSignIn()[0]
if (other) for (const scope of spaceClients(didOf(cand, other))) await spacesFlow(scope)
for (run.step = 1; run.step <= PAGES_STEPS; run.step++) {
const r = below(100)
if (r < 60) await signInFlow(holdOnce)
harness/lib/sets.mjs+19−0
@@ -119,6 +119,21 @@ const DOCS = {
// 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.
@@ -141,8 +156,12 @@ export const SETS = {
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}` : ''}`
harness/spaces/scopes.mjs+16−5
@@ -200,16 +200,22 @@ async function signIn(side, acct, scope) {
const again = await request(page, { jar, headers: { ...NAVIGATE, 'sec-fetch-site': 'cross-site' } })
return { view: { par: 201, page: loaded.status, to: to && `${to.origin}${to.pathname}`, error: to?.searchParams.get('error') ?? null, state: to?.searchParams.get('state') ?? null, again: again.status } }
}
// The page's `spaces` and `spaceHandles` (spec/OAUTH-SCOPES.md, "On the
// authorization page"), each `{}` when not there.
const m = /window\["__authorizeData"\]\s*=\s*JSON\.parse\(("(?:[^"\\]|\\.)*")\)/.exec(loaded.buf.toString('utf8'))
let d = {}
try { d = m ? JSON.parse(JSON.parse(m[1])) : {} } catch {}
const shown = { par: 201, page: 200, data: { spaces: d.spaces ?? {}, spaceHandles: d.spaceHandles ?? {} } }
const api = (endpoint, input) => request(`${origin}/@atproto/oauth-provider/~api${endpoint}`, { method: 'POST', jar, body: JSON.stringify(input), headers: { origin, referer: page, 'sec-fetch-mode': 'same-origin', 'sec-fetch-site': 'same-origin', 'sec-fetch-dest': 'empty', 'x-csrf-token': jar.get('csrf-token'), 'content-type': 'application/json' } })
const si = await api('/sign-in', { locale: 'en', identifier: acct.sides[side.name].handle ?? acct.handle, password: acct.password, remember: true })
if (si.status !== 200) return { view: { par: 201, page: 200, signIn: si.status, error: si.json?.error ?? null } }
if (si.status !== 200) return { view: { ...shown, signIn: si.status, error: si.json?.error ?? null } }
const c = await api('/consent', { did: acct.sides[side.name].did })
if (c.status !== 200) return { view: { par: 201, page: 200, signIn: 200, consent: c.status, error: c.json?.error ?? null } }
if (c.status !== 200) return { view: { ...shown, signIn: 200, consent: c.status, error: c.json?.error ?? null } }
const back = await request(new URL(c.json.url, origin).href, { jar, headers: { ...NAVIGATE, 'sec-fetch-site': 'same-origin', referer: page } })
const code = back.headers.location ? new URL(back.headers.location).searchParams.get('code') : null
const t = await dpop.send(`${origin}/oauth/token`, { method: 'POST', ...form({ grant_type: 'authorization_code', client_id: clientId, redirect_uri: REDIRECT, code: code ?? '', code_verifier: verifier }) })
if (t.status !== 200) return { view: { par: 201, page: 200, signIn: 200, consent: 200, token: t.status, error: t.json?.error ?? null } }
return { view: { par: 201, page: 200, signIn: 200, consent: 200, token: 200, scope: t.json.scope }, session: { dpop, access: t.json.access_token, origin } }
if (t.status !== 200) return { view: { ...shown, signIn: 200, consent: 200, token: t.status, error: t.json?.error ?? null } }
return { view: { ...shown, signIn: 200, consent: 200, token: 200, scope: t.json.scope }, session: { dpop, access: t.json.access_token, origin } }
}
/// An XRPC call with an OAuth session's access token and a proof: `params`
@@ -313,11 +319,16 @@ export async function checkSpaceScopes(h) {
const views = sides.map((side) => {
const v = { ...signed[side.name].view }
if (v.scope !== undefined) v.scope = named(side, v.scope)
if (v.data) {
let s = named(side, JSON.stringify(v.data))
for (const a of accounts) if (a.sides[side.name].handle) s = s.split(a.sides[side.name].handle).join(`<handle:${a.n}>`)
v.data = JSON.parse(s)
}
return v
})
const request = { client: named(ref, scopeOf(ref)) }
const cites = /include:/.test(scopeOf(ref)) ? '; spec/OAUTH-PERMISSION-SETS.md, "What a set grants", "The token\'s scope"' : ''
if (!isDeepStrictEqual(views[0], views[1])) await differ(`space scopes: a sign-in asking for ${what} (spec/OAUTH-SCOPES.md, "Spaces", "Space type declarations", "The token's scope"${cites})`, request, views[0], views[1])
if (!isDeepStrictEqual(views[0], views[1])) await differ(`space scopes: a sign-in asking for ${what} (spec/OAUTH-SCOPES.md, "Spaces", "Space type declarations", "On the authorization page", "The token's scope"${cites})`, request, views[0], views[1])
count(`space scopes: sign-in, ${what}`)
if (!signed.reference.session) continue
const sessions = { reference: signed.reference.session, server: signed.server.session }
harness/look.mjs+4−3
@@ -7,8 +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.
// A `--scope` with `include:` or `space:` tokens has them resolved from the
// harness's permission sets and space type declarations (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.
@@ -83,7 +84,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 sets = /(^| )(include|space)[:?]/.test(value('--scope') ?? '') ? await hostSets(plc.url) : undefined
const server = spawn(join(root, 'target/release/pds'), ['serve'], {
env: {
...process.env,
spec/OAUTH-PAGES.md+99−28
@@ -233,13 +233,15 @@ 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` and a permission set's row. A permission set
`Technical details` and a permission set's row, but a space's owner
whose handle does not verify (below). 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:
else is said in words that come from the scope alone, and the space
types' declarations, 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 |
| --- | --- | --- | --- |
@@ -247,13 +249,23 @@ 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, 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, 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:…`, 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 |
| 5 | `<Space heading>` | `<Space clauses>.` | the scope's `space:` tokens, a row for each space they name (below), in the order the scope first names it |
| 6 | 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 |
| 7 | `All your data` | `<Actions> all your data.` | `repo:` tokens of collection `*`, unless the scope has `transition:generic` |
| 8 | `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` |
| 9 | `Uploads` | `Upload <kinds>.` | `blob:…`, unless the scope has `transition:generic` |
| 10 | `Other services` | `Act as you on <services>.` | `rpc:…`, unless the scope has `transition:generic` |
| 11 | `Permission` | the token, in `<code>` | each other token the server keeps but an `include:` or a `space:`, a row of its own, in the scope's order |
| 12 | `Who you are` | `See which account is yours.` | `atproto`, always |
A space here is a `space` permission's `spaceType`, `authority` and
`skey`, each as given or by its default (`OAUTH-SCOPES.md`, "Spaces"):
the tokens naming the same three are one row, which says all they ask
between them. These rows come from the scope and from
`__authorizeData.spaces` and `spaceHandles` (`OAUTH-SCOPES.md`, "On the
authorization page"), not from the token's rewritten scope; and
`transition:generic`, which allows nothing of a space, hides none of
them.
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
@@ -273,6 +285,10 @@ tokens, and `transition:generic` hides no set's row. In a set's row:
(`<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.
After the tables, each space of the grant's `space` permissions, in the
order the grant first names it, as a heading (`<h3>`), its
`<Space heading>`, and a paragraph (`<p>`) after it, its `<Space
clauses>.`, as row 5 says them.
| Table | Header | Its rows (`<tr>` in `<tbody>`) |
| --- | --- | --- |
@@ -306,9 +322,12 @@ b and c`, and a sentence's first letter is a capital:
- **`<Data clauses>`**: an app's collections that have the same actions
make one clause, `<Actions> <things>`, in the order the scope first
names them, joined with `; `. A thing is the NSID's last segment, its
camel case split into lower-case words, with an `s` after it unless it
ends in one (`post` `posts`, `listItem` `list items`, `notes` `notes`),
and the things are joined as a list. So
camel case split into lower-case words, its last word made plural: as
it is when it ends in `s`; `ies` in place of a final `y` after a letter
other than `a`, `e`, `i`, `o` and `u`; `es` after a final `x`, `z`, `ch`
or `sh`; else `s` after it (`post` `posts`, `listItem` `list items`,
`notes` `notes`, `reply` `replies`, `day` `days`, `box` `boxes`), and
the things are joined as a list. So
`repo:app.bsky.feed.post?action=create&action=delete
repo:app.bsky.feed.like repo:app.bsky.graph.follow?action=create`
reads `Your data in bsky.app: Add and remove posts; add, change and
@@ -323,6 +342,43 @@ b and c`, and a sentence's first letter is a capital:
(`api.bsky.app` for `did:web:api.bsky.app#bsky_appview`), then `a
service` once for any other DID, then `any service` for `*`; joined as
a list. Which methods are asked is in `Technical details`.
- **`<Space heading>`**: whose spaces, and of which type, by the space's
`spaceType` and `authority`; then, for an `skey` that is not `*`,
` named “<skey>”`:
| `spaceType` | `authority` `self` | a DID | `*` |
| --- | --- | --- | --- |
| a type | `Your <Name> spaces` | `<Owner>'s <Name> spaces` | `Everyone's <Name> spaces` |
| `*` | `All your spaces` | `All of <Owner>'s spaces` | `Every space you're in` |
`<Name>` is the type's declaration's title (`title:lang`'s `en`, or else
its first key that begins `en-`, or else `title`), or else the type's
NSID's last segment, its camel case split into words, its first letter
a capital and the rest lower case (`forumBoard` `Forum board`).
`<Owner>` is `@<handle>` when `spaceHandles` has the DID, or else the
DID, in `<code>`.
- **`<Space clauses>`**: what the space's tokens ask between them, as
clauses in this order, joined with `; `:
1. `read everything in them`, when any asks `read`; or else `see what
you've written in them`, when any asks `read_self`;
2. the writes: each collection a token names, or for a token that names
none, of a `spaceType` that is not `*`, each of its declaration's
`collections`, with each of that token's actions that is `create`,
`update` or `delete`. Collections with the same actions make one
clause, `<Actions> <things>`, in the order first named, as `<Data
clauses>` make them but whatever app each is of; `*`'s thing is
`anything`, and a collection other than `*` whose actions `*` has too
is not said again;
3. its `manage` operations, as `make new ones` (`create`), `change who's
in them` (`update`) and `delete them` (`delete`), in that order,
joined as a list.
A space that asks none of these reads `Asks for nothing this server
grants.` So `space:com.example.workspace` with a declaration titled
`Workspace` of `[com.example.note, com.example.tile]`, and
`space:com.example.workspace?manage=create&manage=update`, read `Your
Workspace spaces: Read everything in them; add, change and remove notes
and tiles; make new ones and change who's in them.`
**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,
@@ -469,20 +525,35 @@ 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 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
`did:plc` and `*`, every account attribute at both actions,
`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, with a grant of nothing, and beside `transition:generic`.
for word, and nothing in `<code>` but a `Permission` row's token, what
a set's tables put there and a space's owner with no handle; each set's
`Details` closed, its summary, its sentence, its tables cell for cell,
with each cell's `rowspan`, and its spaces. 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 `did:plc` and `*`, every account attribute at both
actions, `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, with a grant of nothing, and beside
`transition:generic`.
- The consent list for `space:` scopes, and a set granting `space`
permissions, on the server alone, as the reference keeps no `space:`
permission and its token answers would differ: the harness's lexicon
authority publishes two space type declarations, one titled and one
not, and a set granting a `space` permission beside a `repo` one; a
flow for each of a few clients, once a run, signs in on the server's
page and holds its consent view to this page, and goes no further.
Their spaces: a bare type and one with `manage`, merged; another
account's and a DID with no document, each shown as its DID; each type,
with a key, and `*` of each authority; collections of another app, `*`,
and a type `*` asking for writes it has no collection for; and
`read_self` alone. An owner shown by a handle that verifies is not
checked: no handle of the run resolves by DNS or HTTPS
(`OAUTH-SCOPES.md`, "On the authorization page").
- Seeing it all: on each consent view, Allow, Deny and Back (or Another
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
spec/OAUTH-PERMISSION-SETS.md+3−1
spec/OAUTH-SCOPES.md+27−9
spec/OAUTH.md+4−1
web/src/lib/molecules/Grant.svelte+21−0
web/src/lib/molecules/Permission.svelte+1−1
web/src/lib/data.ts+6−0
web/src/lib/scopes.ts+172−31
web/src/views/Consent.svelte+3−1