Something went wrong. Try again.
Something went wrong. Try again.
coding_club gate.mjs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365#!/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 <data>/sessions.json)// CHAT_TOKENS chat token store file (default <data>/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 // secondsconst 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 // msconst 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 = `<!doctype html><html><head><meta charset="utf-8"><title>pi-collab</title><style>body{font-family:system-ui,sans-serif;background:#1e1e1e;color:#ddd;display:grid;place-items:center;min-height:100vh;margin:0}.box{padding:2rem;border:1px solid #444;border-radius:8px;max-width:26rem}input{width:100%;padding:.5rem;margin:.5rem 0;box-sizing:border-box;background:#2a2a2a;color:#ddd;border:1px solid #555;border-radius:4px}button{width:100%;padding:.5rem;background:#3794ff;border:0;border-radius:4px;color:#fff;cursor:pointer}</style></head><body><div class="box"><h1>pi-collab</h1><p>Sign in with your atproto handle to reach the chat.</p><form action="/oauth/login" method="get"><input name="handle" placeholder="you.bsky.social" autofocus><button type="submit">log in</button></form></div></body></html>`
const AUTH_SHELL_PAGE = `<!doctype html><html><head><meta charset="utf-8"><title>pi-collab — terminal</title><style>body{font-family:ui-monospace,monospace;background:#1e1e1e;color:#ddd;display:grid;place-items:center;min-height:100vh;margin:0}.box{padding:2rem;border:1px solid #444;border-radius:8px;max-width:40rem;text-align:center}#tok{user-select:all;background:#2a2a2a;border:1px solid #555;border-radius:6px;padding:.6rem;font:inherit;word-break:break-all}</style></head><body><div class="box"><h1>pi-collab — terminal</h1><p>Copy this token and paste it into the terminal client when asked.<br>It lets the terminal read and post to the chat only.</p><pre id="tok">…</pre><p style="opacity:.7;font-size:.8rem">This window can be closed after you copy it.</p></div><script>fetch("/chat/token", {method:"POST"}).then(r=>r.json()).then(j=>{ document.getElementById("tok").textContent = j.token || ("error: " + JSON.stringify(j));}).catch(e=>{ document.getElementById("tok").textContent = "error: " + e; });</script></body></html>`
// ---- 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})`)})