// Backend (server-side) ATProto OAuth (PLAN §8.3, "server-write" path). The server runs a // confidential OAuth client, holds each player's session/tokens, and performs PDS writes on their // behalf — writing the town.deception.game declaration to the host's repo and each signed // town.deception.game.result to its player's repo at round end. // // The browser never sees tokens: it hits /oauth/login → we redirect to the player's PDS → the PDS // redirects back to /oauth/callback → we store the OAuth session and hand the browser an opaque // `sid` cookie. Every later request (control plane + the WebSocket upgrade) is identified by that // cookie, so the player's DID is server-verified rather than an untrusted URL param. // // Two configurations, chosen by APP_URL: // • Loopback (local dev): APP_URL is http://127.0.0.1[:port]. No hosted metadata or keyset // needed — the client_id encodes the (loopback) metadata. token auth method "none". // • Hosted (prod / https tunnel): we serve /client-metadata.json + /jwks.json and sign client // assertions with an ES256 keyset. client_id = ${APP_URL}/client-metadata.json. import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto' import { existsSync, readFileSync, writeFileSync } from 'node:fs' import { join } from 'node:path' import { Agent } from '@atproto/api' import { spriteRecordExists } from './atproto.js' import { DATA_DIR, SqliteStore } from './store.js' import { NodeOAuthClient, JoseKey, atprotoLoopbackClientMetadata, buildAtprotoLoopbackClientId, requestLocalLock, type NodeSavedState, type NodeSavedSession, type OAuthClientOptions, } from '@atproto/oauth-client-node' // Browser-facing origin (where the SPA runs and the OAuth redirect lands). In dev this is the Vite // server, which proxies /oauth, /api, /ws, /client-metadata.json and /jwks.json to this API. const APP_URL = (process.env.APP_URL ?? 'http://127.0.0.1:5173').replace(/\/$/, '') // Granular repo write scopes — one per collection the server writes on the player's behalf. We // deliberately avoid transition:generic (which grants writes to the entire repo): the consent // screen names exactly what we touch. Note repo scopes cannot be pinned to a specific rkey (the // permission spec only scopes to the collection), so we self-enforce the actor.rpg.stat rkey // (deception.town) in the write path. Requires the PDS to honor granular repo: scopes. const BASE_SCOPE = [ 'atproto', 'repo:town.deception.game', // host's game declaration 'repo:town.deception.game.result', // each player's signed round result 'repo:actor.rpg.stat', // win tracking (rkey deception.town, enforced server-side) 'repo:equipment.rpg.item', // thrift-shop: write/delete items the player donates or withdraws 'repo:equipment.rpg.give', // thrift-shop: the paired give attestation the player writes on donate ] // The sprite-write scope is requested conditionally: only a player who has NO actor.rpg.sprite/self // record yet needs it (so they can clone the default actor into their repo — /api/sprite/default). // A player who already has a sprite is never asked to grant repo write to it. The scope is still // advertised in the published client metadata (METADATA_SCOPE) — it must be there for any login to // be allowed to request it — but it is omitted from authorize() when the player already has a sprite. const SPRITE_SCOPE = 'repo:actor.rpg.sprite' const SCOPE = BASE_SCOPE.join(' ') const METADATA_SCOPE = [...BASE_SCOPE, SPRITE_SCOPE].join(' ') const isLoopback = /^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(APP_URL) // Resolve handles via an XRPC endpoint rather than the default Node DNS resolver — the latter // enables SSRF-protected fetch that requires Node 22+ and otherwise throws at client construction. const HANDLE_RESOLVER = process.env.HANDLE_RESOLVER ?? 'https://bsky.social' // --- persistent stores ------------------------------------------------------ // OAuth state + sessions live in .data/store.db (SQLite/WAL, see store.ts). tsx watch restarts the // API on every edit and prod restarts on deploy; an in-memory store lost every login each time. // Now sessions survive restarts (a mounted volume in prod), so a player stays able to write to their // PDS without re-authenticating. Losing state only aborts an in-flight login; losing a session forces // a re-login, which /api/session detects (restore fails) and clears the cookie for. const stateStore = new SqliteStore('oauth-state') const sessionStore = new SqliteStore('oauth-sessions') // --- client construction ---------------------------------------------------- let clientPromise: Promise | null = null async function buildClient(): Promise { const redirectUri = `${APP_URL}/oauth/callback` if (isLoopback) { const clientId = buildAtprotoLoopbackClientId({ scope: METADATA_SCOPE, redirect_uris: [redirectUri] }) return new NodeOAuthClient({ clientMetadata: atprotoLoopbackClientMetadata(clientId), handleResolver: HANDLE_RESOLVER, stateStore, sessionStore, requestLock: requestLocalLock, }) } // Hosted: confidential client signing assertions with an ES256 keyset published at /jwks.json. const key = await JoseKey.generate(['ES256'], 'sabotage-1') hostedKeyset = [key] const clientMetadata: OAuthClientOptions['clientMetadata'] = { client_id: `${APP_URL}/client-metadata.json`, client_name: 'deception.town', client_uri: APP_URL, redirect_uris: [redirectUri], grant_types: ['authorization_code', 'refresh_token'], scope: METADATA_SCOPE, response_types: ['code'], application_type: 'web', token_endpoint_auth_method: 'private_key_jwt', token_endpoint_auth_signing_alg: 'ES256', dpop_bound_access_tokens: true, jwks_uri: `${APP_URL}/jwks.json`, } return new NodeOAuthClient({ clientMetadata, keyset: [key], handleResolver: HANDLE_RESOLVER, stateStore, sessionStore, requestLock: requestLocalLock, }) } let hostedKeyset: JoseKey[] = [] export function getOAuthClient(): Promise { if (!clientPromise) clientPromise = buildClient() return clientPromise } // --- flow helpers (used by the HTTP endpoints) ------------------------------ /** Build the PDS authorization URL to redirect the browser to. The requested scope includes the * sprite-write permission ONLY when this identity has no actor.rpg.sprite/self record yet — a player * who already has a sprite is never asked to grant repo write to it (they'll never set a default). */ export async function startLogin(handle: string): Promise { const client = await getOAuthClient() const scope = (await spriteWriteNeeded(handle)) ? METADATA_SCOPE : SCOPE const url = await client.authorize(handle, { state: randomUUID(), scope }) return url.toString() } /** Resolve the login identifier to a DID and report whether it lacks a self sprite (→ request write). * Best-effort: if we can't resolve or check, default to requesting the scope so the player can still * set a default actor — an unused granted scope is harmless, a missing one would block the choice. */ async function spriteWriteNeeded(handle: string): Promise { try { const did = await resolveDid(handle) if (!did) return true return !(await spriteRecordExists(did)) } catch { return true } } /** Resolve a handle (or a bare DID) to a DID via the handle resolver's com.atproto.identity.resolveHandle. */ async function resolveDid(handle: string): Promise { const h = handle.trim().replace(/^@/, '') if (h.startsWith('did:')) return h const url = `${HANDLE_RESOLVER.replace(/\/$/, '')}/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(h)}` const res = await fetch(url) if (!res.ok) return null const data = (await res.json()) as { did?: string } return data.did ?? null } /** Complete the callback; returns the authenticated DID and a signed cookie token naming it. */ export async function completeCallback(params: URLSearchParams): Promise<{ did: string; sid: string }> { const client = await getOAuthClient() const { session } = await client.callback(params) const did = session.did return { did, sid: signDid(did) } } /** The DID named by a signed cookie token, or null if absent/tampered. */ export function didForSid(sid: string | null | undefined): string | null { if (!sid) return null return verifyToken(sid) } /** Restore a player's OAuth session as an authenticated Agent for PDS writes. */ export async function agentForDid(did: string): Promise { const client = await getOAuthClient() const session = await client.restore(did) return new Agent(session) } /** True if the server currently holds an OAuth session for this DID (can write to its PDS). */ export async function hasSession(did: string): Promise { return (await sessionStore.get(did)) != null } export async function logout(sid: string | null | undefined): Promise { const did = didForSid(sid) if (!did) return // Revoke tokens and drop the stored session; the cookie is cleared by the caller regardless. try { const client = await getOAuthClient() const session = await client.restore(did) await session.signOut() } catch { /* best-effort */ } } // --- metadata endpoints (hosted mode) --------------------------------------- export async function clientMetadataJson(): Promise { return (await getOAuthClient()).clientMetadata } export async function jwksJson(): Promise { await getOAuthClient() return { keys: hostedKeyset.map((k) => k.publicJwk).filter(Boolean) } } // --- cookie helpers --------------------------------------------------------- // The cookie carries the DID itself, HMAC-signed: `.`. No server-side // sid→DID map — the DID is recovered (and authenticated) straight from the cookie, so identity // survives restarts without any stored state. Tokens stay server-side in the session store. export const SID_COOKIE = 'sabotage_sid' const cookieSecret = loadCookieSecret() function loadCookieSecret(): Buffer { if (process.env.COOKIE_SECRET) return Buffer.from(process.env.COOKIE_SECRET) // Hosted: a generated secret would change on every restart and log everyone out — require one. if (!isLoopback) { throw new Error('COOKIE_SECRET is required in hosted mode: fly secrets set COOKIE_SECRET=$(openssl rand -hex 32)') } // Dev: generate once and keep it in .data so tsx-watch restarts don't invalidate every cookie. const path = join(DATA_DIR, 'cookie-secret') if (!existsSync(path)) writeFileSync(path, randomBytes(32).toString('hex'), { mode: 0o600 }) return Buffer.from(readFileSync(path, 'utf8').trim(), 'hex') } function signDid(did: string): string { const payload = Buffer.from(did).toString('base64url') const sig = createHmac('sha256', cookieSecret).update(payload).digest('base64url') return `${payload}.${sig}` } function verifyToken(token: string): string | null { const dot = token.lastIndexOf('.') if (dot < 0) return null const payload = token.slice(0, dot) const expected = createHmac('sha256', cookieSecret).update(payload).digest() const actual = Buffer.from(token.slice(dot + 1), 'base64url') if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) return null const did = Buffer.from(payload, 'base64url').toString('utf8') return did.startsWith('did:') ? did : null } export function parseCookies(header: string | null | undefined): Record { const out: Record = {} if (!header) return out for (const part of header.split(';')) { const i = part.indexOf('=') if (i < 0) continue out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim()) } return out } export function sidCookie(sid: string): string { // Lax so the cookie rides the top-level redirect back from the PDS; not Secure in http dev. const secure = APP_URL.startsWith('https') ? '; Secure' : '' return `${SID_COOKIE}=${sid}; Path=/; HttpOnly; SameSite=Lax${secure}` } export function clearSidCookie(): string { return `${SID_COOKIE}=; Path=/; HttpOnly; Max-Age=0; SameSite=Lax` } export const appUrl = APP_URL