// An app that joins a group for a person. Signed in to their own PDS, it // makes their inbox, where groups write invites, reads the invite the group // sent them, asks the group's host to let them in, and once in, confirms // the membership in their own repo. // // npm start [message to the group] import { once } from 'node:events'; import { createServer } from 'node:http'; import type { AddressInfo } from 'node:net'; import { Client, XrpcResponseError, l } from '@atproto/lex'; import { SpaceClient, memberspace } from '@atproto/lex-space'; import { NodeOAuthClient, buildAtprotoLoopbackClientMetadata, createDidResolver, requestLocalLock } from '@atproto/oauth-client-node'; import { com, org } from './lexicons/index.ts'; const [person, group, message] = process.argv.slice(2); if (!person || !group) throw new Error('usage: npm start [message]'); // 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:'); // What the app asks of the person, at their own PDS: to make their inbox // and read the invites in it, to write their confirmation in any group's // members space, and to ask a group's host to let them in. A group host's // permission set `include:org.atgrp.authParticipate` holds these and more, // where the person's PDS can read its lexicon. const scope = [ 'atproto', 'space:org.atgrp.inbox?action=read&manage=create', 'space:org.atgrp.members?authority=*&collection=org.atgrp.confirmation&action=create', 'rpc:org.atgrp.requestJoin?aud=*' ].join(' '); // The members space, as far as this app writes it. It is declared here, // not generated: the alpha's `lex build` makes a space type of several // collections that TypeScript cannot type. const members = l.space('literal:self', 'org.atgrp.members', [org.atgrp.confirmation.main]); // 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 }); // The person signs in at their own PDS, as to any app. const url = await oauth.authorize(person, { scope }); console.log(`Sign in as ${person}:\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(); const client = new Client(session); const didResolver = createDidResolver({ plcDirectoryUrl, allowHttp }); console.log(`Signed in as ${session.did}`); // The group, and its host: the PDS its DID document names. The host's own // DID, which calls to it through the person's PDS are addressed to, is what // it says it is (`describeServer`). const { did: groupDid, didDoc } = await oauth.identityResolver.resolve(group); const pds = didDoc.service?.find( (s) => s.id === '#atproto_pds' || s.id === `${groupDid}#atproto_pds` ); const hostUrl = String(pds?.serviceEndpoint); const described = await new Client(hostUrl).call(com.atproto.server.describeServer); const host = `${described.did}#atgrp` as const; // The inbox: a space of the person's own, at their PDS, that any group may // write in (`publicWrite`) and only they read. A group's invite waits there // once the inbox is made; the host keeps its own list besides, so an // invite sent before still admits them. let inbox: SpaceClient; try { const policy = memberspace.policy.$build({ publicWrite: true }); inbox = await SpaceClient.createSpace(client.agent, org.atgrp.inbox, { policy }, { didResolver }); console.log('Made your inbox, where groups write their invites'); } catch (e) { if (!(e instanceof XrpcResponseError && e.error === 'SpaceAlreadyExists')) throw e; inbox = SpaceClient.openSpace( org.atgrp.inbox, { authority: session.did }, { agent: client.agent, didResolver } ); } // The group's invite, in the group's own repo in the inbox, read with a // credential the person's PDS gives for their delegation token. for await (const r of inbox.allRecords()) { if (!r.valid || r.repo !== groupDid || r.collection !== org.atgrp.invite.$type) continue; console.log(`\n${group} invited you${r.record.message ? `: ${r.record.message}` : ''}`); } // Asking to join, of the group's host, through the person's PDS: it signs // the call as them (service auth) and sends it on to the host, which the // `atproto-proxy` header names. A live invite lets them in whatever the // group's join policy; otherwise `approval` leaves the request waiting. const asked = await client.call( org.atgrp.requestJoin, { group: groupDid, ...(message ? { message } : {}) }, { service: host } ); if (asked.status !== 'admitted') { console.log(`\nAsked to join ${group}: waiting for its admins.`); } else { // Their side of the membership: a confirmation in their own repo in the // group's members space, at their own PDS, which apps that show only // members who've taken up their place look for. const space = SpaceClient.openSpace( members, { authority: groupDid }, { agent: client.agent, didResolver } ); await space.put(org.atgrp.confirmation.$build({ createdAt: l.currentDatetimeString() })); console.log(`\nJoined ${group}, and confirmed it.`); } await session.signOut();