import { BrowserOAuthClient } from '@atproto/oauth-client-browser' /** The parts of an OAuth session this app needs. */ export interface Session { sub: string signOut(): Promise } const CALLBACK_PATH = '/oauth/callback' const RETURN_KEY = 'threadbare:return' const HANDLE_RESOLVER = 'https://bsky.social' let clientPromise: Promise | undefined /** The dev server runs on a loopback address; the deployed site does not. */ function onLoopback(): boolean { return ['127.0.0.1', '[::1]', 'localhost'].includes(location.hostname) } /** The OAuth server rejects a `localhost` redirect, so development maps it to the IP. */ function loopbackOrigin(): string { const host = location.hostname === 'localhost' ? '127.0.0.1' : location.hostname return `http://${host}${location.port ? `:${location.port}` : ''}` } /** * A loopback client id carries its own metadata, so the authorization server * never fetches it. The redirect_uri names this app's real callback. */ function loopbackClientId(): string { return `http://localhost?redirect_uri=${encodeURIComponent(redirectUri())}` } async function getClient(): Promise { if (!clientPromise) { clientPromise = (async () => { if (onLoopback()) { return BrowserOAuthClient.load({ clientId: loopbackClientId(), handleResolver: HANDLE_RESOLVER, responseMode: 'query', allowHttp: true, }) } const response = await fetch(new URL('/client-metadata.json', location.origin)) if (!response.ok) { throw new Error('Could not load the atproto client metadata.') } const clientMetadata = await response.json() return new BrowserOAuthClient({ clientMetadata, handleResolver: HANDLE_RESOLVER, responseMode: 'query', allowHttp: false, }) })().catch((error) => { clientPromise = undefined throw error }) } return clientPromise } export function redirectUri(): string { const base = onLoopback() ? `${loopbackOrigin()}/` : location.origin return new URL(CALLBACK_PATH, base).href } export function isCallback(): boolean { return location.pathname === CALLBACK_PATH || location.pathname === `${CALLBACK_PATH}/` } /** * Restore the session the browser already holds. A failure here leaves the * stored session alone; signing in again replaces it. */ export async function restoreSession(): Promise { const client = await getClient() const restored = await client.initRestore() return restored?.session } /** * Exchange the query parameters at /oauth/callback. Returns undefined when the * page has no OAuth parameters. */ export async function completeCallback(): Promise { const client = await getClient() const params = client.readCallbackParams() if (!params) return undefined const { session } = await client.initCallback(params, redirectUri() as never) return session } /** * Send the browser to the account's authorization server. The intended hash * survives the round trip in sessionStorage. */ export async function startSignIn(handle: string): Promise { sessionStorage.setItem(RETURN_KEY, location.hash || '#scan') const client = await getClient() const url = await client.authorize(handle, { redirect_uri: redirectUri() as never }) location.assign(url.href) } /** Read and clear the hash stored before the authorization redirect. */ export function takeReturnHash(): string { const value = sessionStorage.getItem(RETURN_KEY) sessionStorage.removeItem(RETURN_KEY) return value?.startsWith('#') ? value : '#scan' } /** Revoke the session and remove it from this browser. */ export async function signOut(session: Session): Promise { await session.signOut() }