~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0
677 lines · 28.1 KB Raw History
// What a scope asks for, in plain words (spec/OAUTH-PAGES.md, "Consent"):
// one row for each kind of thing asked, the riskiest first, its tokens
// merged and what a broader token covers not said again, with no NSID,
// method or DID shown. Tokens are read as atproto/permission.md writes
// them: `resource[:positional][?name=value&…]`. A permission set an
// `include:` token names is granted as spec/OAUTH-PERMISSION-SETS.md says
// ("What a set grants"), from the set documents the page is given.

// A run of a heading or sentence: text, or a token shown as code (a
// Permission row's, or a space's owner with no handle).
export type Part = string | { code: string };

// 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; the data, by collection (sorted), with whether each of create,
// update and delete is asked; and its spaces, in the order first named.
export type Grant = {
	calls: { aud: string; towards: Part; methods: string[] }[];
	data: { collection: string; actions: boolean[] }[];
	spaces: Space[];
};

// A row: its heading and sentence (maybe none), and for a permission set's,
// what it grants.
export type Item = { heading: Part[]; 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.';

// The tokens a row names by themselves.
const NAMED: Record<string, true> = {
	atproto: true,
	'transition:generic': true,
	'transition:email': true,
	'transition:chat.bsky': true
};

// The resources whose tokens are merged into rows of their own.
const RESOURCES = ['identity', 'account', 'repo', 'blob', 'rpc'] as const;
type Resource = (typeof RESOURCES)[number];

// `account:<attr>`: its clause, by attribute and action, in the order said.
const ACCOUNT: [string, Record<string, string>][] = [
	['email', { read: 'see your email address', manage: 'see and change your email address' }],
	['status', { read: 'see whether your account is active', manage: 'deactivate and reactivate your account' }],
	['repo', { read: 'see the state of your data', manage: 'import your data from elsewhere' }]
];

// An upload's kind, by its type's first part; any other is `files`.
const KINDS: Record<string, string> = {
	image: 'images',
	video: 'videos',
	audio: 'audio',
	text: 'text'
};

// A record action and its verb, in the order said.
const ACTIONS: [string, string][] = [
	['create', 'add'],
	['update', 'change'],
	['delete', 'remove']
];
const ALL_ACTIONS = ACTIONS.map(([a]) => a);


type Token = { resource: string; positional?: string; params: Map<string, string[]> };

function parse(token: string): Token | null {
	const q = token.indexOf('?');
	const head = q < 0 ? token : token.slice(0, q);
	const query = q < 0 ? '' : token.slice(q + 1);
	const c = head.indexOf(':');
	const params = new Map<string, string[]>();
	try {
		const positional = c < 0 ? undefined : decodeURIComponent(head.slice(c + 1));
		for (const pair of query.split('&')) {
			if (!pair) continue;
			const e = pair.indexOf('=');
			if (e < 0) return null;
			const name = decodeURIComponent(pair.slice(0, e));
			params.set(name, [...(params.get(name) ?? []), decodeURIComponent(pair.slice(e + 1))]);
		}
		return { resource: c < 0 ? head : head.slice(0, c), positional, params };
	} catch {
		return null;
	}
}

// The values of the parameter `name`: the positional one, then those given by name.
const values = (t: Token, name: string): string[] =>
	[...(t.positional ? [t.positional] : []), ...(t.params.get(name) ?? [])].filter(Boolean);

// A list joined as `a`, `a and b`, or `a, b and c`.
function joined(items: string[]): string {
	if (items.length < 2) return items.join('');
	return `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`;
}

// A sentence: its first letter a capital, and a full stop.
const said = (text: string): string => `${text.charAt(0).toUpperCase()}${text.slice(1)}.`;
const sentence = (text: string): Part[] => [said(text)];
// Clauses, each a sentence of its own, joined with a space.
const sentences = (clauses: string[]): string => clauses.map(said).join(' ');

// The verbs of a set of record actions, joined as a list.
const verbs = (actions: Set<string>): string =>
	joined(ACTIONS.filter(([a]) => actions.has(a)).map(([, verb]) => verb));

// The domain an NSID's namespace is rooted at: its first two segments, reversed.
const appOf = (nsid: string): string => nsid.split('.').slice(0, 2).reverse().join('.');

// An NSID's last segment as a plain thing: words, lower case, the last
// made plural (spec/OAUTH-PAGES.md, "<Data clauses>").
function thingOf(nsid: string): string {
	const last = nsid.split('.').pop() ?? nsid;
	const words = last.replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase();
	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`;
}

function identityRow(tokens: Token[]): Item {
	const all = tokens.some((t) => values(t, 'attr').includes('*'));
	return {
		heading: ['Identity'],
		sentence: [
			all
				? "Change your handle, and take over your account's identity, which could move your account elsewhere."
				: 'Change your handle.'
		]
	};
}

// Each attribute once, at the strongest action asked of it.
function accountRow(tokens: Token[], email: boolean): Item | null {
	const asked = new Map<string, string>(email ? [['email', 'read']] : []);
	for (const t of tokens) {
		const action = t.params.get('action')?.[0] ?? 'read';
		for (const attr of values(t, 'attr'))
			if (asked.get(attr) !== 'manage') asked.set(attr, action === 'manage' ? 'manage' : 'read');
	}
	const clauses = ACCOUNT.filter(([attr]) => asked.has(attr)).map(
		([attr, said]) => said[asked.get(attr) ?? 'read']
	);
	return clauses.length ? { heading: ['Account'], sentence: sentence(joined(clauses)) } : null;
}

// The collections asked and every action asked of each, from `repo:` tokens
// (all three when a token gives none), in the order first named.
function askedOf(tokens: Token[]): Map<string, Set<string>> {
	const asked = new Map<string, Set<string>>();
	for (const t of tokens) {
		const given = t.params.get('action') ?? ALL_ACTIONS;
		for (const c of values(t, 'collection')) {
			const set = asked.get(c) ?? new Set<string>();
			for (const a of given) set.add(a);
			asked.set(c, set);
		}
	}
	return asked;
}

// Each app's <Data clauses>, apps as first named: its collections with the
// same actions in one clause, `<Actions> <things>`.
function clausesByApp(asked: Map<string, Set<string>>): Map<string, string[]> {
	const apps = new Map<string, Map<string, string[]>>();
	for (const [c, actions] of asked) {
		const groups = apps.get(appOf(c)) ?? new Map<string, string[]>();
		const key = ALL_ACTIONS.filter((a) => actions.has(a)).join(',');
		groups.set(key, [...(groups.get(key) ?? []), thingOf(c)]);
		apps.set(appOf(c), groups);
	}
	return new Map(
		[...apps].map(([app, groups]) => [
			app,
			[...groups].map(([key, things]) => `${verbs(new Set(key.split(',')))} ${joined(things)}`)
		])
	);
}

// `*`'s actions as All your data; then, for each app as first named, its
// collections that `*` does not cover, those with the same actions in one
// clause.
function dataRows(tokens: Token[]): Item[] {
	const asked = askedOf(tokens);
	const star = asked.get('*');
	const rows: Item[] = star
		? [{ heading: ['All your data'], sentence: sentence(`${verbs(star)} all your data`) }]
		: [];
	const rest = new Map(
		[...asked].filter(
			([c, actions]) => c !== '*' && !(star && [...actions].every((a) => star.has(a)))
		)
	);
	for (const [app, clauses] of clausesByApp(rest))
		rows.push({ heading: [`Your data in ${app}`], sentence: [sentences(clauses)] });
	return rows;
}

// Each kind of upload once, as first given but `files` last; `*/*` says all.
function uploadsRow(tokens: Token[]): Item {
	const types = tokens.flatMap((t) => values(t, 'accept'));
	const families = new Set(types.map((t) => KINDS[t.split('/')[0]] ?? 'files'));
	const kinds = types.includes('*/*')
		? ['any file']
		: [...[...families].filter((k) => k !== 'files'), ...(families.has('files') ? ['files'] : [])];
	return { heading: ['Uploads'], sentence: sentence(`Upload ${joined(kinds)}`) };
}

// Each service of these audiences once: the did:web ones by their hosts,
// as first named; then `a service` for any other DID; then `any service`
// for `*`.
function servicesOf(auds: string[]): string[] {
	const web = auds.filter((a) => a.startsWith('did:web:'));
	return [
		...new Set(web.map((a) => a.slice('did:web:'.length).split('#')[0])),
		...(auds.some((a) => a !== '*' && !a.startsWith('did:web:')) ? ['a service'] : []),
		...(auds.includes('*') ? ['any service'] : [])
	];
}

function servicesRow(tokens: Token[]): Item {
	const auds = tokens.map((t) => t.params.get('aud')?.[0] ?? '').filter(Boolean);
	return {
		heading: ['Other services'],
		sentence: sentence(`Act as you on ${joined(servicesOf(auds))}`)
	};
}

// ---------------------------------------------------- permission sets

// An NSID, as atproto/nsid.md writes one.
const NSID =
	/^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(\.[a-zA-Z]([a-zA-Z0-9]{0,62})?)$/;
const isNsid = (v: unknown): v is string =>
	typeof v === 'string' && v.length <= 317 && v.lastIndexOf('.') <= 253 && NSID.test(v);

// A DID with a `#` service fragment.
const SERVICE = /^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]#\S+$/;

type Include = { nsid: string; aud?: string };

// An `include:` token: an `nsid`, positional or as a parameter, and at most
// an `aud`, a DID with a service fragment; no other parameter.
function parseInclude(token: string): Include | null {
	const t = parse(token);
	if (!t || t.resource !== 'include') return null;
	if ([...t.params.keys()].some((name) => name !== 'nsid' && name !== 'aud')) return null;
	const nsids = values(t, 'nsid');
	const auds = t.params.get('aud') ?? [];
	if (nsids.length !== 1 || !isNsid(nsids[0]) || auds.length > 1) return null;
	if (auds.length && !SERVICE.test(auds[0])) return null;
	return { nsid: nsids[0], aud: auds[0] };
}

const isObject = (v: unknown): v is Record<string, unknown> =>
	typeof v === 'object' && v !== null && !Array.isArray(v);

// A permission a set grants, as kept: a `space` one as its scope string.
type Kept =
	| { resource: 'repo'; collections: string[]; actions: string[] }
	| { resource: 'rpc'; methods: string[]; aud: string }
	| { resource: 'space'; token: string };

// A `space` permission's parameters (spec/OAUTH-SCOPES.md, "Spaces",
// "Which parse"): whether each takes many values, and the values it allows.
const SPACE_ACTIONS = ['read_self', 'read', ...ALL_ACTIONS];
const DEFAULT_SPACE_ACTIONS = SPACE_ACTIONS.slice(1);
const SPACE: Record<string, { many: boolean; allows: (v: string) => boolean }> = {
	spaceType: { many: false, allows: (v) => v === '*' || isNsid(v) },
	authority: {
		many: false,
		allows: (v) =>
			v === '*' ||
			v === 'self' ||
			(v.length <= 2048 && /^did:[a-z]+:[a-zA-Z0-9._:%-]*[a-zA-Z0-9._-]$/.test(v))
	},
	skey: {
		many: false,
		allows: (v) => v === '*' || (/^[a-zA-Z0-9._:~-]{1,512}$/.test(v) && v !== '.' && v !== '..')
	},
	collection: { many: true, allows: (v) => v === '*' || isNsid(v) },
	action: { many: true, allows: (v) => SPACE_ACTIONS.includes(v) },
	manage: { many: true, allows: (v) => ALL_ACTIONS.includes(v) }
};

// `%3A`, `%2F`, `%2B`, `%2C`, `%40` and `%25` turned back to what they encode.
const decoded = (s: string): string =>
	s
		.replace(/%3A/g, ':')
		.replace(/%2F/g, '/')
		.replace(/%2B/g, '+')
		.replace(/%2C/g, ',')
		.replace(/%40/g, '@')
		.replace(/%25/g, '%');

// A `space` permission of a set as its scope string, its defaults left out,
// as spec/OAUTH-SCOPES.md writes a `space:` token again ("The token's
// scope"); null when it is dropped. Its type is in the set's namespace
// (`inside`), its collections under any.
function spaceOf(p: Record<string, unknown>, inside: (n: string) => boolean): string | null {
	const given = new Map<string, string[]>();
	for (const [k, v] of Object.entries(p)) {
		if (k === 'type' || k === 'resource') continue;
		const param = Object.hasOwn(SPACE, k) ? SPACE[k] : undefined;
		if (!param) return null;
		const vs = !param.many
			? typeof v === 'string'
				? [v]
				: null
			: Array.isArray(v) && v.length > 0 && v.every((x) => typeof x === 'string')
				? (v as string[])
				: null;
		if (!vs || !vs.every(param.allows)) return null;
		given.set(k, vs);
	}
	const spaceType = given.get('spaceType')?.[0];
	if (!spaceType || !inside(spaceType)) return null;
	const q = new URLSearchParams();
	const authority = given.get('authority')?.[0] ?? 'self';
	const skey = given.get('skey')?.[0] ?? '*';
	if (authority !== 'self') q.append('authority', authority);
	if (skey !== '*') q.append('skey', skey);
	const collections = given.get('collection') ?? [];
	for (const c of collections.includes('*') ? ['*'] : sorted(new Set(collections)))
		q.append('collection', c);
	const asked = given.get('action') ?? DEFAULT_SPACE_ACTIONS;
	const actions = SPACE_ACTIONS.filter((a) => asked.includes(a));
	if (actions.join() !== DEFAULT_SPACE_ACTIONS.join())
		for (const a of actions) q.append('action', a);
	const manage = given.get('manage') ?? [];
	for (const m of ALL_ACTIONS.filter((m) => manage.includes(m))) q.append('manage', m);
	const query = decoded(q.toString());
	return `space:${decoded(encodeURIComponent(spaceType))}${query ? `?${query}` : ''}`;
}

// What a permission grants in the set whose namespace is `prefix`, with the
// `include:`'s audience `inherited`; null when it is dropped.
function keep(p: unknown, prefix: string, inherited: string | undefined): Kept | null {
	if (!isObject(p)) return null;
	const has = (name: string) => Object.hasOwn(p, name);
	const takes = (names: string[]) =>
		Object.keys(p).every((k) => k === 'type' || k === 'resource' || names.includes(k));
	const inside = (n: string) => n.startsWith(prefix) && n.length > prefix.length;
	// One or more NSIDs, each once, each in the set's namespace.
	const names = (v: unknown): string[] | null =>
		Array.isArray(v) && v.length > 0 && v.every((n) => isNsid(n) && inside(n))
			? [...new Set(v as string[])]
			: null;
	if (p.resource === 'repo') {
		const collections = names(p.collection);
		if (!takes(['collection', 'action']) || !collections) return null;
		if (!has('action')) return { resource: 'repo', collections, actions: ALL_ACTIONS };
		const given = p.action;
		if (!Array.isArray(given) || !given.length) return null;
		if (!given.every((a) => typeof a === 'string' && ALL_ACTIONS.includes(a))) return null;
		return { resource: 'repo', collections, actions: ALL_ACTIONS.filter((a) => given.includes(a)) };
	}
	if (p.resource === 'rpc') {
		const methods = names(p.lxm);
		if (!takes(['lxm', 'aud', 'inheritAud']) || !methods) return null;
		if (has('aud') && p.aud !== '*') return null;
		if (has('inheritAud') && (p.inheritAud !== true || has('aud') || !inherited)) return null;
		const aud = has('aud') ? '*' : p.inheritAud === true ? inherited : undefined;
		return aud ? { resource: 'rpc', methods, aud } : null;
	}
	if (p.resource === 'space') {
		const token = spaceOf(p, inside);
		return token ? { resource: 'space', token } : null;
	}
	return null;
}

// An audience as a scope string writes it: `#` as `%23`, `*`, `:` and `/` as they are.
const audience = (aud: string): string =>
	encodeURIComponent(aud).replace(/%3A/g, ':').replace(/%2F/g, '/');

// A kept permission as one scope string.
function written(k: Kept): string {
	if (k.resource === 'space') return k.token;
	const names = [...(k.resource === 'repo' ? k.collections : k.methods)].sort();
	const field = k.resource === 'repo' ? 'collection' : 'lxm';
	const params = names.length > 1 ? names.map((n) => `${field}=${n}`) : [];
	if (k.resource === 'repo' && k.actions.length < ALL_ACTIONS.length)
		params.push(...k.actions.map((a) => `action=${a}`));
	if (k.resource === 'rpc') params.push(`aud=${audience(k.aud)}`);
	const head = names.length > 1 ? k.resource : `${k.resource}:${names[0]}`;
	return params.length ? `${head}?${params.join('&')}` : head;
}

type PermissionSet = Include & { doc: Record<string, unknown> | null; kept: Kept[] };

// The set an `include:` token names, from the page's set documents, and
// what it grants; null when the token is not an `include:`. A document
// that is not an object, or whose `permissions` is not an array, grants
// nothing.
function setOf(token: string, sets: Record<string, unknown> | undefined): PermissionSet | null {
	const include = parseInclude(token);
	if (!include) return null;
	const found = isObject(sets) && Object.hasOwn(sets, include.nsid) ? sets[include.nsid] : null;
	const doc = isObject(found) ? found : null;
	const prefix = include.nsid.slice(0, include.nsid.lastIndexOf('.') + 1);
	const permissions: unknown[] = Array.isArray(doc?.permissions) ? doc.permissions : [];
	const kept = permissions
		.map((p) => keep(p, prefix, include.aud))
		.filter((k): k is Kept => k !== null);
	return { ...include, doc, kept };
}

// What the set an `include:` token names grants, as scope strings, in the
// order of its permissions; null when the token is not an `include:`.
export const grantOf = (token: string, sets: Record<string, unknown> | undefined): string[] | null =>
	setOf(token, sets)?.kept.map(written) ?? null;

// A set's text for `field` (`title`, `detail`): `<field>:lang`'s `en`, or
// else its first key that begins `en-`, or else `<field>`; it has one when
// that gives a string that is not empty.
function textOf(doc: Record<string, unknown> | null, field: string): string | undefined {
	const langs = doc?.[`${field}:lang`];
	const english = isObject(langs)
		? typeof langs.en === 'string'
			? 'en'
			: Object.keys(langs).find((k) => k.startsWith('en-'))
		: undefined;
	const text = english && isObject(langs) ? langs[english] : doc?.[field];
	return typeof text === 'string' && text ? text : undefined;
}

// 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 };
}

// ---------------------------------------------------- spaces

// What the page knows of spaces: each space type's declaration, by its
// NSID, and the handle of each owner whose handle verifies, by its DID
// (`__authorizeData.spaces` and `spaceHandles`), both unchecked.
export type SpaceData = { declarations?: Record<string, unknown>; handles?: Record<string, unknown> };

// A space as a row or a set's Details says it.
export type Space = { heading: Part[]; sentence: string };

// A space's `manage` operation and its clause, in the order said: for one
// the account owns (`self`), and for every space (`*`), where only those it
// made are changed or deleted. Of another's spaces nothing is said.
const MANAGE: [string, string][] = [
	['create', 'make new ones'],
	['update', "change who's in them"],
	['delete', 'delete them']
];
const MANAGE_MADE: [string, string][] = [
	['update', "change who's in"],
	['delete', 'delete']
];

// What the tokens naming one space ask between them.
type Asked = {
	spaceType: string;
	authority: string;
	skey: string;
	read: boolean;
	readSelf: boolean;
	writes: Map<string, Set<string>>;
	manage: Set<string>;
};

// A space type's declaration, if the page has it.
function declarationOf(data: SpaceData, type: string): Record<string, unknown> | null {
	const d = data.declarations;
	return isObject(d) && Object.hasOwn(d, type) && isObject(d[type]) ? d[type] : null;
}

// <Name>: the declaration's title, or else the NSID's last segment in
// words, its first letter a capital.
function spaceName(data: SpaceData, type: string): string {
	const title = textOf(declarationOf(data, type), 'title');
	if (title) return title;
	const last = (type.split('.').pop() ?? type).replace(/([a-z0-9])([A-Z])/g, '$1 $2').toLowerCase();
	return `${last.charAt(0).toUpperCase()}${last.slice(1)}`;
}

// <Space heading>: whose spaces, of which type, and by which key, said
// from the account's side.
function spaceHeading(data: SpaceData, s: Asked): Part[] {
	const handle = isObject(data.handles) && Object.hasOwn(data.handles, s.authority) ? data.handles[s.authority] : undefined;
	const owner: Part = typeof handle === 'string' && handle ? `@${handle}` : { code: s.authority };
	const named = s.skey === '*' ? '' : ` named “${s.skey}”`;
	const name = s.spaceType === '*' ? '' : spaceName(data, s.spaceType);
	if (s.authority === 'self') return [s.spaceType === '*' ? `All your spaces${named}` : `Your ${name} spaces${named}`];
	if (s.authority === '*')
		return [s.spaceType === '*' ? `Every space${named} you're in` : `${name} spaces${named} you're in`];
	return [owner, s.spaceType === '*' ? `'s spaces${named} you're in` : `'s ${name} spaces${named} you're in`];
}

// <Space clauses>: reading, the writes to the account's own records
// grouped by their actions (`*`'s thing `records of any kind`, what `*`
// covers not said again), then managing; each a sentence.
function spaceSentence(s: Asked): string {
	const clauses: string[] = [];
	if (s.read) clauses.push('read everything in them');
	else if (s.readSelf) clauses.push("see what you've written in them");
	const star = s.writes.get('*');
	const groups = new Map<string, string[]>();
	for (const [c, actions] of s.writes) {
		if (c !== '*' && star && [...actions].every((a) => star.has(a))) continue;
		const key = ALL_ACTIONS.filter((a) => actions.has(a)).join(',');
		groups.set(key, [...(groups.get(key) ?? []), c === '*' ? 'records of any kind' : thingOf(c)]);
	}
	for (const [key, things] of groups)
		clauses.push(`${verbs(new Set(key.split(',')))} your own ${joined(things)}`);
	if (s.authority === 'self') {
		const manage = MANAGE.filter(([m]) => s.manage.has(m)).map(([, said]) => said);
		if (manage.length) clauses.push(joined(manage));
	} else if (s.authority === '*') {
		const made = MANAGE_MADE.filter(([m]) => s.manage.has(m)).map(([, said]) => said);
		const manage = [
			...(s.manage.has('create') ? ['make new ones'] : []),
			...(made.length ? [`${made.join(' or ')} the ones you made`] : [])
		];
		if (manage.length) clauses.push(manage.join(', and '));
	}
	return clauses.length ? sentences(clauses) : 'Asks for nothing this server grants.';
}

// The spaces `space` tokens name, by type, authority and key, each as
// given or by its default, the tokens naming one merged, in the order
// first named. A token naming no collection, of a type that is not `*`,
// writes its declaration's `collections`.
function spacesOf(tokens: Token[], data: SpaceData): Space[] {
	const spaces = new Map<string, Asked>();
	for (const t of tokens) {
		const spaceType = values(t, 'spaceType')[0] ?? '';
		const authority = t.params.get('authority')?.[0] ?? 'self';
		const skey = t.params.get('skey')?.[0] ?? '*';
		const key = JSON.stringify([spaceType, authority, skey]);
		const s: Asked = spaces.get(key) ?? {
			spaceType,
			authority,
			skey,
			read: false,
			readSelf: false,
			writes: new Map(),
			manage: new Set()
		};
		spaces.set(key, s);
		const actions = t.params.get('action') ?? DEFAULT_SPACE_ACTIONS;
		s.read ||= actions.includes('read');
		s.readSelf ||= actions.includes('read_self');
		const declared = declarationOf(data, spaceType)?.collections;
		const collections =
			t.params.get('collection') ??
			(spaceType !== '*' && Array.isArray(declared)
				? declared.filter((c): c is string => typeof c === 'string')
				: []);
		const writes = actions.filter((a) => ALL_ACTIONS.includes(a));
		if (writes.length)
			for (const c of collections) s.writes.set(c, new Set([...(s.writes.get(c) ?? []), ...writes]));
		for (const m of t.params.get('manage') ?? []) s.manage.add(m);
	}
	return [...spaces.values()].map((s) => ({ heading: spaceHeading(data, s), sentence: spaceSentence(s) }));
}

// A token that is a `space` permission, read; else null.
function spaceToken(token: string): Token | null {
	const t = parse(token);
	return t?.resource === 'space' && values(t, 'spaceType').length ? t : null;
}

// A set's grant as its Details' tables: every method once for each
// audience, every action any `repo` permission asks of each collection,
// and its spaces.
function grantTables(kept: Kept[], data: SpaceData): 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]));
	const spaces: Token[] = [];
	for (const k of kept) {
		if (k.resource === 'rpc') add(calls, k.aud, k.methods);
		else if (k.resource === 'space') {
			const t = spaceToken(k.token);
			if (t) spaces.push(t);
		} 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)
		})),
		spaces: spacesOf(spaces, data)
	};
}

// 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, data: SpaceData): Item {
	const title = textOf(set.doc, 'title');
	const detail = textOf(set.doc, 'detail') ?? (title ? set.nsid : undefined);
	return {
		heading: [title ?? set.nsid],
		sentence: detail ? [detail] : [],
		grant: grantTables(set.kept, data)
	};
}

// The scope's tokens, as written, in its order.
export const tokensOf = (scope: string): string[] => scope.split(' ').filter(Boolean);

// Technical details: the scope's tokens as written, in its order, each
// `include:` with the scope strings its set grants.
export const detailsOf = (
	scope: string,
	sets: Record<string, unknown> | undefined
): { token: string; grant: string[] }[] =>
	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,
// its spaces said from `data`. Each set has a row of its own, whatever
// else the scope asks; an `include:` or a `space:` is never a Permission
// row.
export function rowsOf(scope: string, sets?: Record<string, unknown>, data: SpaceData = {}): 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 spaces: Token[] = [];
	const included: Item[] = [];
	const take = (token: string) => {
		const t = parse(token);
		const kind = RESOURCES.find((r) => r === t?.resource);
		const space = spaceToken(token);
		if (t && kind) of.get(kind)?.push(t);
		else if (space) spaces.push(space);
		else others.push(token);
	};
	for (const token of tokens) {
		if (Object.hasOwn(NAMED, token)) continue;
		const set = setOf(token, sets);
		if (set) included.push(setRow(set, data));
		else if (parse(token)?.resource !== 'include') take(token);
	}
	const kind = (r: Resource) => of.get(r) ?? [];
	const rows: (Item | null)[] = [
		generic ? { heading: ['Full access'], sentence: [FULL_ACCESS] } : null,
		kind('identity').length ? identityRow(kind('identity')) : null,
		accountRow(kind('account'), has('transition:email')),
		has('transition:chat.bsky')
			? { heading: ['Direct messages'], sentence: ['Read and send your Bluesky direct messages.'] }
			: null,
		...spacesOf(spaces, data).map((s) => ({ heading: s.heading, sentence: [s.sentence] })),
		...included,
		...(!generic ? dataRows(kind('repo')) : []),
		!generic && kind('blob').length ? uploadsRow(kind('blob')) : null,
		!generic && kind('rpc').length ? servicesRow(kind('rpc')) : null,
		...others.map((t) => ({ heading: ['Permission'], sentence: [{ code: t }] })),
		{ heading: ['Who you are'], sentence: ['See which account is yours.'] }
	];
	return rows.filter((r): r is Item => r !== null);
}