// atproto OAuth, entirely in the browser. Tokens never reach our server. import { atprotoLoopbackClientMetadata, BrowserOAuthClient, buildAtprotoLoopbackClientId, type OAuthSession, } from "@atproto/oauth-client-browser"; import { OAUTH_SCOPE } from "../shared/lexicon.ts"; const HANDLE_RESOLVER = "https://bsky.social"; export interface Auth { readonly session: OAuthSession | null; signIn(handle: string): Promise; signOut(): Promise; } // Restores a saved session, or completes a login redirect if we're on one. export async function createAuth(): Promise { const client = await createClient(); let session = (await client.init())?.session ?? null; return { get session() { return session; }, async signIn(handle) { await client.signInRedirect(handle, { scope: OAUTH_SCOPE }); }, async signOut() { if (session) await client.revoke(session.sub); session = null; }, }; } // Local dev must run on 127.0.0.1 (not localhost) for the loopback client. async function createClient(): Promise { const { hostname, port, origin } = window.location; if (hostname === "127.0.0.1") { const clientId = buildAtprotoLoopbackClientId({ scope: OAUTH_SCOPE, redirect_uris: [`http://127.0.0.1:${port}/`] }); return new BrowserOAuthClient({ clientMetadata: atprotoLoopbackClientMetadata(clientId), handleResolver: HANDLE_RESOLVER }); } return BrowserOAuthClient.load({ clientId: `${origin}/client-metadata.json`, handleResolver: HANDLE_RESOLVER }); }