Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219// The OAuth sidecar: the only process that holds a user's credential, and the// credential gate for the whole chat.//// Adapted from aligned.click (oauth/server.mjs): atproto OAuth binds every// access token to a key with DPoP, so whoever holds the key must be the one// making the request. This sidecar is that key-holder — the authenticated// request path, not a login helper. Runs as a separate process; the auth proxy// (gate.mjs) is its only caller.//// Loopback development mode (no PUBLIC_URL): short-lived sessions, fine for// local use on 127.0.0.1. With a public URL it becomes a confidential client// (private_key_jwt) and sessions outlive a few days.//// GET /health is it up, and as what// GET /client-metadata.json the client_id document (public mode)// GET /jwks.json the public half of the signing key// GET /oauth/login?handle= 302 to the user's own server// GET /oauth/callback code -> a stored session// GET /oauth/sessions which DIDs are logged in// GET /oauth/logout sign out one DID// POST /xrpc/<nsid> one call, as one DIDimport { createServer } from "node:http"import { join } from "node:path"import { NodeOAuthClient } from "@atproto/oauth-client-node"import { requestLocalLock } from "@atproto/oauth-client"import { loadOrCreateKey } from "./keys.mjs"import { jsonStore } from "./store.mjs"
const PORT = Number(process.env.OAUTH_PORT || 4098)const STORE_DIR = process.env.OAUTH_STORE_DIR || join(import.meta.dirname, "..", "private", "oauth")const PUBLIC_URL = process.env.PUBLIC_URL?.replace(/\/$/, "")// Where the browser comes back to. Not this process — the redirect has to land// on the auth proxy (gate.mjs), because that is the origin the person is// actually using and the only thing that can set their cookie.const PROXY_URL = (process.env.PROXY_URL || "http://127.0.0.1:8000").replace(/\/$/, "")const SCOPE = "atproto transition:generic"
const stateStore = jsonStore(join(STORE_DIR, "state.json"))const sessionStore = jsonStore(join(STORE_DIR, "sessions.json"))
const isProduction = Boolean(PUBLIC_URL)const redirectUri = isProduction ? `${PUBLIC_URL}/oauth/callback` : `${PROXY_URL}/oauth/callback`
const key = isProduction ? await loadOrCreateKey(join(STORE_DIR, "client-key.json")) : null
const clientMetadata = isProduction ? { client_id: `${PUBLIC_URL}/client-metadata.json`, client_name: "pi-collab", client_uri: PUBLIC_URL, redirect_uris: [redirectUri], scope: SCOPE, grant_types: ["authorization_code", "refresh_token"], 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: `${PUBLIC_URL}/jwks.json`, } : { client_id: `http://localhost?redirect_uri=${encodeURIComponent(redirectUri)}` + `&scope=${encodeURIComponent(SCOPE)}`, client_name: "pi-collab (development)", redirect_uris: [redirectUri], scope: SCOPE, grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], application_type: "native", token_endpoint_auth_method: "none", dpop_bound_access_tokens: true, }
const client = new NodeOAuthClient({ clientMetadata, keyset: key ? [key] : undefined, stateStore, sessionStore, handleResolver: "https://bsky.social", requestLock: requestLocalLock,})
const send = (res, status, body, type = "application/json") => { const text = type === "application/json" ? JSON.stringify(body, null, 2) : String(body) res.writeHead(status, { "content-type": type, "content-length": Buffer.byteLength(text) }) res.end(text)}
const readBody = (req) => new Promise((resolve, reject) => { let data = "" req.on("data", (chunk) => { data += chunk if (data.length > 1e6) reject(new Error("body too large")) }) req.on("end", () => { try { resolve(data ? JSON.parse(data) : {}) } catch { reject(new Error("body is not JSON")) } }) req.on("error", reject) })
const routes = { "GET /health": async () => ({ ok: true, mode: isProduction ? "production" : "loopback", client_id: clientMetadata.client_id, confidential: Boolean(key), sessions: (await sessionStore.keys()).length, }),
"GET /client-metadata.json": async () => { if (!isProduction) throw httpError(404, "no client metadata in loopback mode — the client_id carries it") return clientMetadata },
"GET /jwks.json": async () => { if (!key) throw httpError(404, "no signing key in loopback mode") return { keys: [{ ...key.publicJwk, alg: "ES256" }] } },
"GET /oauth/login": async (url, _req, res) => { const handle = url.searchParams.get("handle") if (!handle) throw httpError(400, "?handle= is required") const authorizeUrl = await client.authorize(handle, { scope: SCOPE }) if (url.searchParams.get("json") === "1") return { authorize: authorizeUrl.toString() } res.writeHead(302, { location: authorizeUrl.toString() }) res.end() return null },
"GET /oauth/callback": async (url) => { const { session } = await client.callback(url.searchParams) return { did: session.did, message: "logged in — this window can be closed" } },
"GET /oauth/sessions": async () => ({ dids: await sessionStore.keys() }),
"GET /oauth/logout": async (url) => { const did = url.searchParams.get("did") if (!did) throw httpError(400, "?did= is required") const session = await client.restore(did) await session.signOut() return { did, signedOut: true } },}
async function xrpc(url, req, res) { const nsid = url.pathname.slice("/xrpc/".length) const did = url.searchParams.get("did") if (!did) throw httpError(400, "?did= is required — a call is made as somebody") if (!nsid) throw httpError(400, "no method named")
if (!(await sessionStore.get(did))) { throw httpError(401, `${did} has not logged in — no session was ever stored for it`) } let session try { session = await client.restore(did) } catch (err) { throw httpError(401, `session for ${did} is no longer usable (${err.message}) — log in again`) }
const init = { method: req.method, headers: {} } if (req.method === "POST") { const body = await readBody(req) init.body = JSON.stringify(body) init.headers["content-type"] = "application/json" } const query = new URLSearchParams(url.searchParams) query.delete("did") const path = `/xrpc/${nsid}${query.size ? `?${query}` : ""}`
const upstream = await session.fetchHandler(path, init) const text = await upstream.text() res.writeHead(upstream.status, { "content-type": upstream.headers.get("content-type") || "application/json", "content-length": Buffer.byteLength(text), }) res.end(text) return null}
function httpError(status, message) { const err = new Error(message) err.status = status return err}
const server = createServer(async (req, res) => { const url = new URL(req.url, `http://127.0.0.1:${PORT}`) try { if (url.pathname.startsWith("/xrpc/")) { await xrpc(url, req, res) return } const handler = routes[`${req.method} ${url.pathname}`] if (!handler) return send(res, 404, { error: "no such route", path: url.pathname }) const body = await handler(url, req, res) if (body !== null) send(res, 200, body) } catch (err) { const status = err.status || 500 send(res, status, { error: err.constructor.name, message: err.message }) if (status >= 500) console.error(`[oauth] ${req.method} ${url.pathname}`, err) }})
server.listen(PORT, "127.0.0.1", () => { console.log( `oauth sidecar: :${PORT} ` + `(${isProduction ? "production, confidential" : "loopback development"})`, ) console.log(` client_id: ${clientMetadata.client_id}`) console.log(` store: ${STORE_DIR}`)})