// An app that reads a group on a group host: first as anyone may, then // signed in as the group. An admin of the group approves it at the host, // and it reads the group's meta and members spaces as the group and asks // the host one of its own methods. // // npm start import { once } from 'node:events'; import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import { Client, XrpcResponseError, l } from '@atproto/lex'; import { SpaceReader, delegationTokenProviderFor } from '@atproto/lex-space'; import { NodeOAuthClient, buildAtprotoLoopbackClientMetadata, createDidResolver, requestLocalLock } from '@atproto/oauth-client-node'; import { com, org } from './lexicons/index.ts'; const group = process.argv[2]; if (!group) throw new Error('usage: npm start '); // A PLC directory on http is a test network's, whose hosts are on http too. const plcDirectoryUrl = process.env.PLC_URL ?? 'https://plc.directory'; const allowHttp = plcDirectoryUrl.startsWith('http:'); const didResolver = createDidResolver({ plcDirectoryUrl, allowHttp }); // What the app asks of the group: to read its two spaces, and to list who // asked to join. The host keeps of it what the approving member's roles hold. const scope = [ 'atproto', 'space:org.atgrp.meta?action=read', 'space:org.atgrp.members?action=read', 'rpc:org.atgrp.listJoinRequests?aud=*' ].join(' '); // The two spaces every group keeps, as far as this app reads them. They are // declared here, not generated: the alpha's `lex build` makes a space type // of several collections that TypeScript cannot type. Records of // collections not declared come back with `valid` false. const meta = l.space('literal:self', 'org.atgrp.meta', [ org.atgrp.about.main, org.atgrp.config.main ]); const members = l.space('literal:self', 'org.atgrp.members', [ org.atgrp.role.main, org.atgrp.membership.main, org.atgrp.confirmation.main, org.atgrp.rule.main, com.atproto.label.record.main ]); // The member who approved the app: the host names them beside the tokens // it answers with, `member`, a field of its own, which the OAuth client // doesn't keep. So the client's requests go through this, which reads it. let approver: string | undefined; const fetch: typeof globalThis.fetch = async (input, init) => { const res = await globalThis.fetch(input, init); const url = new URL(input instanceof Request ? input.url : input); if (url.pathname === '/oauth/token' && res.ok) approver = (await res.clone().json()).member; return res; }; // The loopback client, `http://localhost`: an app on this machine, with no // metadata document of its own to publish. One process, so its sessions and // the lock on refreshing them are in memory. const memory = () => { const kept = new Map(); return { get: async (key: string) => kept.get(key), set: async (key: string, value: T) => void kept.set(key, value), del: async (key: string) => void kept.delete(key) }; }; const server = createServer().listen(0, '127.0.0.1'); await once(server, 'listening'); const callback = `http://127.0.0.1:${(server.address() as AddressInfo).port}/callback`; const oauth = new NodeOAuthClient({ clientMetadata: buildAtprotoLoopbackClientMetadata({ scope, redirect_uris: [callback] }), stateStore: memory(), sessionStore: memory(), requestLock: requestLocalLock, plcDirectoryUrl, handleResolver: process.env.HANDLE_RESOLVER, allowHttp, fetch }); const { did } = await oauth.identityResolver.resolve(group); // The group's profile and how it's joined, from its meta space, as // `options` let it be read. const profile = async (options: SpaceReader.Options) => { for await (const r of SpaceReader.openSpace(meta, { authority: did }, options).allRecords()) { if (!r.valid) continue; if (r.collection === org.atgrp.about.$type) console.log( ` ${r.record.displayName}${r.record.description ? `: ${r.record.description}` : ''}` ); if (r.collection === org.atgrp.config.$type) console.log(` Joining: ${r.record.joinPolicy}`); } }; // Signed out: a group whose meta space anyone may read gives a credential // for it with no delegation token. Its host answers `SpaceNotFound` to // anyone else, the same as for a space that isn't there. console.log(`Anyone sees ${group}:`); try { await profile({ didResolver }); } catch (e) { if (!(e instanceof XrpcResponseError && e.error === 'SpaceNotFound')) throw e; console.log(' nothing: only its members see its profile'); } // Signing in as the group: the group's DID document names its host, which // is its authorization server. The host sends the browser to its console, // where a member signs in and approves. const url = await oauth.authorize(did, { scope }); console.log(`\nApprove the app as an admin of ${group}:\n\n ${url}\n`); const [req, res] = await once(server, 'request'); const { session } = await oauth.callback(new URL(req.url, callback).searchParams); res.end('Signed in. Back to the terminal.'); server.close(); // Each space is read with a credential the host gives for a delegation token // the session asks it for. @atproto/lex-space's reader does both, and checks // the host's MACs over what it reads. const client = new Client(session); const signedIn = { delegationTokenProvider: delegationTokenProviderFor(client.agent), didResolver }; const roles = new Map(); const memberships = new Map(); const confirmed = new Set(); const rules: org.atgrp.rule.Main[] = []; const takenDown = new Set(); const now = new Date().toISOString(); for await (const r of SpaceReader.openSpace(members, { authority: did }, signedIn).allRecords()) { if (!r.valid) continue; if (r.collection === org.atgrp.role.$type) roles.set(r.rkey, r.record); // A membership is keyed by its member's DID, and they confirm it with a // confirmation in their own repo, at their own PDS. if (r.collection === org.atgrp.membership.$type) memberships.set(r.rkey, r.record.roles); if (r.collection === org.atgrp.confirmation.$type) confirmed.add(r.repo); if (r.collection === org.atgrp.rule.$type) rules.push(r.record); // Only the group's own labels count, until they lapse. A member it takes // down is shown to no one. if (r.collection === com.atproto.label.record.$type && r.repo === did) { const { uri, val, exp } = r.record; if (val === '!takedown' && (!exp || exp > now)) takenDown.add(uri); } } // Only an admin may give the app the group, whose roles hold the group's // administration set: one who approved it, holding less, may read more of // the group than the app should let them. A session they approved is // given back. const adminSet = 'include:org.atgrp.authManageAdmin'; const isAdmin = (memberships.get(approver ?? '') ?? []).some((key) => roles.get(key)?.permissions?.some((p) => p === adminSet || p.startsWith(`${adminSet}?`)) ); if (!isAdmin) { console.log(`${approver ?? 'Someone'} approved it, but isn't an admin of the group.`); await session.signOut(); process.exit(1); } console.log(`Signed in as ${session.did}, approved by ${approver}\n`); console.log('Its members see:'); await profile(signedIn); console.log('\nRules:'); rules.sort((a, b) => (a.order ?? 0) - (b.order ?? 0)); for (const rule of rules) console.log(` ${rule.title}: ${rule.text}`); console.log('\nMembers:'); for (const [member, held] of memberships) { if (takenDown.has(member)) continue; const names = held.map((k) => roles.get(k)?.displayName ?? k).join(', '); console.log(` ${member} ${names}${confirmed.has(member) ? '' : ' (not confirmed)'}`); } // The host's own methods, typed by their lexicons. The session names the // group, so the call needn't. try { const { requests } = await client.call(org.atgrp.listJoinRequests, {}); console.log(`\nJoin requests: ${requests.length}`); for (const r of requests) console.log(` ${r.member} ${r.message ?? ''}`); } catch (e) { // ScopeMissing: the approving member may not admit anyone. console.log(`\nJoin requests: not granted (${(e as Error).message})`); } // Gives the grant back: the group's admins see it gone from its apps. await session.signOut();