#!/usr/bin/env node // Auth gate: the only way in. atproto login happens here, in front of the // WebSocket chat (which requires a token to join). A cookie names a session, a // session names a DID; the browser can mint a narrower chat token that the // terminal client uses to reach the conversation. // // The gate never sees a credential: the oauth sidecar holds them, and this // proxy only asks it to start/complete a login and answers with its own random // cookie — the same split as coding_club's gate. // // Routes: // GET /oauth/login?handle=&next= start login (302 to the user's own PDS; next bounces back) // GET /oauth/callback finish login, set cookie, 302 next (or /auth/shell) // GET /oauth/logout?next= clear the cookie // GET /login the login form // GET /auth/shell show a chat token for the terminal client // POST /chat/token mint a chat token (authed) // GET /me who this cookie is // GET /health is it up // // Env: // OAUTH_URL oauth sidecar base (default http://127.0.0.1:4098) // PORT listen port (default 8443) // SESSIONS session store file (default /sessions.json) // CHAT_TOKENS chat token store file (default /chat/tokens.json) // DATA_DIR base dir for stores (default ./data) import { createServer } from "node:http" import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs" import { randomBytes } from "node:crypto" import { dirname, join } from "node:path" const OAUTH_URL = (process.env.OAUTH_URL || "http://127.0.0.1:4098").replace(/\/$/, "") const PORT = Number(process.env.PORT || 8443) const DATA_DIR = process.env.DATA_DIR || join(import.meta.dirname, "data") const SESSIONS_FILE = process.env.SESSIONS || join(DATA_DIR, "sessions.json") const CHAT_TOKENS_FILE = process.env.CHAT_TOKENS || join(DATA_DIR, "chat", "tokens.json") const COOKIE = "pi_session" const SESSION_TTL = 7 * 24 * 60 * 60 // seconds const CHAT_TOKEN_TTL = 7 * 24 * 60 * 60 // seconds // ---- json store ------------------------------------------------------------- function jsonStore(path) { mkdirSync(dirname(path), { recursive: true }) const read = () => { try { return JSON.parse(readFileSync(path, "utf8")) } catch (err) { if (err.code === "ENOENT") return {} throw new Error(`${path} is unreadable: ${err.message}`) } } const write = (data) => { const tmp = `${path}.tmp` writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 0o600 }) renameSync(tmp, path) } return { get(key) { return read()[key] }, set(key, value) { const data = read() data[key] = value write(data) }, pop(key) { const data = read() const value = data[key] delete data[key] write(data) return value }, } } // ---- sessions (browser cookie -> DID) --------------------------------------- const sessions = jsonStore(SESSIONS_FILE) function userForSession(token) { if (!token) return null const entry = sessions.get(token) if (!entry) return null if (entry.created + SESSION_TTL * 1000 < Date.now()) { sessions.pop(token) return null } return entry.did } function loginSession(did) { const token = randomBytes(32).toString("base64url") sessions.set(token, { did, created: Date.now() }) return token } function logoutSession(token) { sessions.pop(token) } // ---- chat tokens (terminal client -> DID) ---------------------------------- const chatTokens = jsonStore(CHAT_TOKENS_FILE) function mintChatToken(did) { const token = randomBytes(32).toString("base64url") chatTokens.set(token, { did, expires: Date.now() + CHAT_TOKEN_TTL * 1000 }) return token } function userForChatToken(token) { if (!token) return null const entry = chatTokens.get(token) if (!entry) return null if (entry.expires < Date.now()) { chatTokens.pop(token) return null } return entry.did } // ---- DID -> handle resolution (best-effort, cached) ------------------------- // The DID is the stable identifier; the handle is just display and may change, // so it is looked up fresh each time and cached briefly. const HANDLE_TTL = 5 * 60 * 1000 // ms const handleCache = new Map() async function lookupHandle(did) { try { const res = await fetch(`https://plc.directory/${did}`, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(10_000), }) if (!res.ok) return null const doc = await res.json() for (const uri of doc.alsoKnownAs ?? []) { if (uri.startsWith("at://")) return uri.slice(5).split("/")[0] || null } } catch { /* best-effort */ } return null } async function resolveHandle(did) { if (!did) return "" const hit = handleCache.get(did) if (hit && hit[1] > Date.now()) return hit[0] const handle = (await lookupHandle(did)) || did handleCache.set(did, [handle, Date.now() + HANDLE_TTL]) return handle } // ---- HTTP helpers ----------------------------------------------------------- function reply(res, status, body, contentType = "text/html; charset=utf-8", extra = []) { let buf = body if (typeof body === "object" && !(body instanceof Buffer)) { buf = Buffer.from(JSON.stringify(body)) contentType = "application/json" } else if (typeof body === "string") { buf = Buffer.from(body) } const headers = { "Content-Type": contentType, "Content-Length": buf.length, "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff", } for (const [name, value] of extra) { if (name.toLowerCase() === "set-cookie") { // Multiple Set-Cookie headers must survive together (e.g. the OAuth // callback sets pi_session and clears pi_next in one response). // Object.fromEntries would keep only the last, dropping the session. res.appendHeader("Set-Cookie", value) } else { headers[name] = value } } res.writeHead(status, headers) res.end(buf) } function cookieToken(req) { const header = req.headers.cookie ?? "" for (const part of header.split(";")) { const [name, ...rest] = part.trim().split("=") if (name === COOKIE) return rest.join("=") } return null } function setCookie(res, token) { return ["Set-Cookie", `${COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL}`] } function cookieValue(req, name) { for (const part of (req.headers.cookie ?? "").split(";")) { const [n, ...rest] = part.trim().split("=") if (n === name) return rest.join("=") } return null } // The web client lives on the bridge origin (localhost:8000) but the session // cookie lives here (localhost:8443). Same-site (ports don't count for // SameSite), so the client can read /me and mint tokens if we answer with the // right CORS headers — but only for loopback origins. const NEXT_SAFE = /^(https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?(\/.*)?|\/.*)$/ function corsOrigin(req) { const origin = req.headers.origin if (origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(origin)) return origin return null } async function askSidecar(path) { const res = await fetch(`${OAUTH_URL}${path}`, { signal: AbortSignal.timeout(30_000) }) if (!res.ok) { const text = await res.text().catch(() => "") throw new Error(`oauth sidecar ${res.status}: ${text.slice(0, 200)}`) } return res.json() } // ---- pages ------------------------------------------------------------------ const LOGIN_PAGE = `pi-collab

pi-collab

Sign in with your atproto handle to reach the chat.

` const AUTH_SHELL_PAGE = `pi-collab — terminal

pi-collab — terminal

Copy this token and paste it into the terminal client when asked.
It lets the terminal read and post to the chat only.

…

This window can be closed after you copy it.

` // ---- server ---------------------------------------------------------------- const server = createServer(async (req, res) => { const url = new URL(req.url, `http://127.0.0.1:${PORT}`) const { pathname, searchParams } = url try { // ---- unauthenticated routes -------------------------------------- const origin = corsOrigin(req) if (origin) { res.setHeader("Access-Control-Allow-Origin", origin) res.setHeader("Access-Control-Allow-Credentials", "true") res.setHeader("Vary", "Origin") } if (req.method === "OPTIONS") { res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS") res.setHeader("Access-Control-Allow-Headers", "Content-Type") res.writeHead(204) res.end() return } if (pathname === "/health") { return reply(res, 200, { ok: true }, "application/json") } if (pathname === "/login" || pathname === "/oauth/login") { const handle = (searchParams.get("handle") ?? "").trim() if (!handle) return reply(res, 200, LOGIN_PAGE) const out = await askSidecar(`/oauth/login?handle=${encodeURIComponent(handle)}&json=1`) if (!out.authorize) return reply(res, 400, out, "application/json") // Optional ?next= round-trips through the PDS in a short-lived cookie so // the web client can bounce the browser back to its own origin after login. const extra = [] const next = (searchParams.get("next") ?? "").trim() if (next) { if (!NEXT_SAFE.test(next)) return reply(res, 400, { error: "unsafe next" }, "application/json") extra.push(["Set-Cookie", `pi_next=${encodeURIComponent(next)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=600`]) } return reply(res, 302, "", "text/plain", [["Location", out.authorize], ...extra]) } if (pathname === "/oauth/callback") { const out = await askSidecar(`/oauth/callback?${searchParams.toString()}`) if (!out.did) return reply(res, 400, out, "application/json") const token = loginSession(out.did) const extra = [setCookie(res, token)] let location = "/auth/shell" const pending = cookieValue(req, "pi_next") if (pending) { const next = decodeURIComponent(pending) if (NEXT_SAFE.test(next)) { // Web flow: browsers routinely drop a cookie set in the cross-site // redirect chain from the PDS, so also hand the room's chat token // straight to the client in the URL fragment. The web app reads it, // stores it, and joins — no reliance on a stored cookie. location = next + (next.includes("#") ? "&" : "#") + "tok=" + mintChatToken(out.did) } extra.push(["Set-Cookie", `pi_next=; Path=/; HttpOnly; Max-Age=0`]) } return reply(res, 302, "", "text/plain", [["Location", location], ...extra]) } if (pathname === "/oauth/logout") { logoutSession(cookieToken(req)) const next = (searchParams.get("next") ?? "").trim() const extra = [["Set-Cookie", `${COOKIE}=; Path=/; HttpOnly; Max-Age=0`]] const location = next && NEXT_SAFE.test(next) ? next : "/login" if (location !== "/login") extra.push(["Set-Cookie", `pi_next=; Path=/; HttpOnly; Max-Age=0`]) return reply(res, 302, "", "text/plain", [["Location", location], ...extra]) } // ---- authenticated routes ---------------------------------------- const sessionDid = userForSession(cookieToken(req)) const auth = req.headers.authorization ?? "" const chatDid = auth.toLowerCase().startsWith("bearer ") ? userForChatToken(auth.slice(7).trim()) : null const did = sessionDid || chatDid if (!did) { return reply(res, 302, "", "text/plain", [["Location", "/login"]]) } if (pathname === "/auth/shell") { if (chatDid && !sessionDid) return reply(res, 403, { error: "browser only" }, "application/json") return reply(res, 200, AUTH_SHELL_PAGE) } if (pathname === "/chat/token" && req.method === "POST") { if (!sessionDid) return reply(res, 403, { error: "browser only" }, "application/json") return reply(res, 200, { token: mintChatToken(did) }, "application/json") } if (pathname === "/me") { return reply(res, 200, { did, handle: await resolveHandle(did) }, "application/json") } return reply(res, 404, { error: "no such route", path: pathname }, "application/json") } catch (err) { const status = err.status || 500 reply(res, status, { error: err.constructor.name, message: err.message }, "application/json") if (status >= 500) console.error(`[gate] ${req.method} ${pathname}`, err) } }) server.on("error", (err) => { if (err.code === "EADDRINUSE") { console.error(`\n✗ Port ${PORT} is already in use.`); console.error(" Another gate or the coding_club stack may be running there."); console.error(` Stop it, or start on another port: PORT=${PORT + 1} node gate.mjs\n`); process.exit(1); } throw err; }); server.listen(PORT, "0.0.0.0", () => { console.log(`[gate] atproto gate on :${PORT} (oauth ${OAUTH_URL})`) })