Something went wrong. Try again.
spool is a community-first, lightweight discussion forum, issue tracker, and announcement hub for your project.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186import crypto from "node:crypto";import { Agent } from "@atproto/api";import { NodeOAuthClient, type NodeSavedSession, type NodeSavedState,} from "@atproto/oauth-client-node";import { eq } from "drizzle-orm";import { Hono } from "hono";import { getCookie, setCookie, deleteCookie } from "hono/cookie";import { db } from "../db/index.js";import { atprotoOauthSession, atprotoOauthState, users } from "../db/schema.js";import { createSession, type AuthEnv } from "./session.js";import { listPendingTangledRepos, refreshPendingTangledRepos } from "./tangledSync.js";
const APP_URL = process.env.APP_URL ?? "http://localhost:5173";
// AT Protocol's OAuth spec requires redirect_uris to use a loopback IP// address, never the hostname "localhost" (RFC 8252 section 8.3).const redirectUri = new URL("/auth/atproto/callback", APP_URL);redirectUri.hostname = "127.0.0.1";const redirectUriString = redirectUri.toString();
// "atproto" alone only proves identity — reading a profile via the AppView// (app.bsky.actor.getProfile) needs the broader "transition:generic" scope// too, or Bluesky's API rejects it with a missing-scope error.const scope = "atproto transition:generic";
// "http://localhost" is a dev-only client_id convention: AT Proto// authorization servers accept it without fetching a hosted// client-metadata document. A production deployment needs a real// client_id URL pointing at a metadata document hosted by this app.const clientId = `http://localhost?redirect_uri=${encodeURIComponent(redirectUriString)}&scope=${encodeURIComponent(scope)}`;
const stateStore = { async set(key: string, value: NodeSavedState) { const serialized = JSON.stringify(value); await db .insert(atprotoOauthState) .values({ key, value: serialized }) .onConflictDoUpdate({ target: atprotoOauthState.key, set: { value: serialized } }); }, async get(key: string) { const [row] = await db .select() .from(atprotoOauthState) .where(eq(atprotoOauthState.key, key)); return row ? (JSON.parse(row.value) as NodeSavedState) : undefined; }, async del(key: string) { await db.delete(atprotoOauthState).where(eq(atprotoOauthState.key, key)); },};
const sessionStore = { async set(did: string, value: NodeSavedSession) { const serialized = JSON.stringify(value); await db .insert(atprotoOauthSession) .values({ did, value: serialized }) .onConflictDoUpdate({ target: atprotoOauthSession.did, set: { value: serialized } }); }, async get(did: string) { const [row] = await db .select() .from(atprotoOauthSession) .where(eq(atprotoOauthSession.did, did)); return row ? (JSON.parse(row.value) as NodeSavedSession) : undefined; }, async del(did: string) { await db.delete(atprotoOauthSession).where(eq(atprotoOauthSession.did, did)); },};
const client = new NodeOAuthClient({ clientMetadata: { client_id: clientId, redirect_uris: [redirectUriString], scope, grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], application_type: "native", // No client secret: a loopback dev client can't keep one confidential. token_endpoint_auth_method: "none", dpop_bound_access_tokens: true, }, stateStore, sessionStore, // No requestLock: we never call client.restore(), so concurrent token // refresh — the only thing the lock protects against — never happens here.});
const auth = new Hono<AuthEnv>();
auth.get("/atproto", async (c) => { // The OAuth callback always lands on redirectUri's host (127.0.0.1), since // that's what AT Proto's loopback convention requires. If this request // came in on a different host (e.g. someone browsing at "localhost"), our // CSRF cookie would be set on that other host and never be sent back on // the callback. Normalize to the callback's host before setting anything. const requestUrl = new URL(c.req.url); if (requestUrl.hostname !== redirectUri.hostname) { requestUrl.hostname = redirectUri.hostname; return c.redirect(requestUrl.toString()); }
const rawHandle = c.req.query("handle"); if (!rawHandle) { return c.text("Missing handle — e.g. ?handle=you.bsky.social", 400); } // Bluesky's UI displays handles with a leading "@", but the handle // itself doesn't include one — strip it if someone typed it that way. const handle = rawHandle.replace(/^@/, "");
// `state` defends against CSRF: the authorization server echoes it back // and we compare it to the cookie, same pattern as the GitHub flow. const state = crypto.randomBytes(16).toString("hex"); setCookie(c, "atproto_oauth_state", state, { httpOnly: true, sameSite: "Lax", path: "/", maxAge: 600, });
let url: URL; try { url = await client.authorize(handle, { state }); } catch { return c.text(`Could not find a Bluesky account for "${handle}"`, 400); } return c.redirect(url.toString());});
auth.get("/atproto/callback", async (c) => { const expectedState = getCookie(c, "atproto_oauth_state"); deleteCookie(c, "atproto_oauth_state", { path: "/" });
const params = new URL(c.req.url).searchParams; const { session, state } = await client.callback(params);
if (!state || state !== expectedState) { return c.text("OAuth state mismatch — try signing in again", 400); }
const agent = new Agent(session); const profile = await agent.getProfile({ actor: session.did }); const handle = profile.data.handle; const avatarUrl = profile.data.avatar ?? null;
const [user] = await db .insert(users) .values({ atprotoDid: session.did, username: handle, avatarUrl }) .onConflictDoUpdate({ target: users.atprotoDid, set: { username: handle, avatarUrl }, }) .returning();
// Stage the repos this user owns on Tangled that haven't already been // synced or declined — the user picks which become Spools next, rather // than everything being synced automatically. Must happen before the // sessionStore.del() below — the Agent needs the stored session to still // exist while it's in use (see the getProfile() bug this exact ordering // was already fixed for). await refreshPendingTangledRepos(agent, session.did, handle, user.id);
// We only needed the DID/handle/repos to sync locally — we don't keep // using their AT Proto session afterwards, so don't let its tokens linger // in the database. await sessionStore.del(session.did);
await createSession(c, user.id);
const pending = await listPendingTangledRepos(user.id); // Not APP_URL: the session cookie we just set is scoped to this request's // host (127.0.0.1, forced above), so redirecting anywhere else would // immediately lose it. // A top-level path, not under /auth or /api — both of those prefixes are // proxied straight to this server (see web/vite.config.ts), so a frontend // route can't live under either. const destinationPath = pending.length > 0 ? "/select-repos" : "/"; return c.redirect(new URL(destinationPath, redirectUri).toString());});
export default auth;