// OAuth session handling. This module must only be used from DOM contexts // (popup, Chrome's offscreen document, Firefox's background page) — // BrowserOAuthClient depends on window/localStorage and does not run in // Chrome's MV3 service worker. The worker learns about the session through the // `session` mirror in storage.local. import { Agent } from '@atproto/api' import { BrowserOAuthClient, type OAuthSession } from '@atproto/oauth-client-browser' import clientMetadata from '../../oauth/client-metadata.json' import { profileAvatarUrl, resolveDid } from './atproto' import { oauthRedirectUri } from './authflow' import { ext } from './platform' import { SUB_KEY, clearSessionMirror, getStoredSession, markSessionExpired, saveSessionMirror, } from './session-store' import type { SessionInfo } from './types' let client: BrowserOAuthClient | undefined function getClient(): BrowserOAuthClient { client ??= new BrowserOAuthClient({ // Metadata is inlined; the hosted copy at client_id must stay identical. clientMetadata: clientMetadata as never, handleResolver: 'https://bsky.social', responseMode: 'query', allowHttp: false, }) return client } /** * The redirect URI for the id this build is actually running under, which is * not the one the OAuth client would pick on its own. * * Both halves of the flow must send the same value: the authorization request * registers it, and the token exchange is checked against what was registered. * The client defaults each half to `clientMetadata.redirect_uris[0]`, and the * metadata lists the store id first, so an unpacked build that authorizes as * itself would exchange as the store — `invalid_grant`, "The redirect_uri * parameter must match the one used in the authorization request". Same shape * of bug as v1.2.1, on the other half of the flow. */ function redirectUri(): `https://${string}` { return oauthRedirectUri(ext.runtime.id) as `https://${string}` } /** * First half of interactive sign-in: resolve the handle, push the * authorization request, and return the consent URL to open. The client * persists the pending state (PKCE verifier, DPoP keys), so the matching * completeAuthorization can run in a later client instance. */ export async function startAuthorization(handle: string): Promise { const url = await getClient().authorize(handle, { redirect_uri: redirectUri() }) return url.href } /** * Second half: exchange the callback redirect URL for the session's profile * info. Deliberately no storage write — this runs in the offscreen document, * which has no ext.storage; the worker persists the mirror (src/signin.ts). */ export async function completeAuthorization(callbackUrl: string): Promise { const params = new URL(callbackUrl).searchParams const { session } = await getClient().callback(params, { redirect_uri: redirectUri() }) return buildSessionInfo(session) } async function buildSessionInfo(session: OAuthSession): Promise { const did = session.sub let handle: string | undefined let avatarUrl: string | undefined try { const resolved = await resolveDid(did) handle = resolved.handle avatarUrl = await profileAvatarUrl(resolved.pds, did) } catch { // handle and avatar are cosmetic; the did is enough } return { did, handle, avatarUrl } } /** * Re-resolve the stored session's handle and avatar, which can change on the * PDS at any time (and predate this field existing at all). Returns the * updated info when something changed, undefined otherwise. */ export async function refreshStoredSession(): Promise { const current = await getStoredSession() if (!current) return undefined try { const resolved = await resolveDid(current.did) const next: SessionInfo = { did: current.did, handle: resolved.handle ?? current.handle, avatarUrl: await profileAvatarUrl(resolved.pds, current.did), } if (next.handle === current.handle && next.avatarUrl === current.avatarUrl) return undefined await saveSessionMirror(next) console.debug('[substandard] refreshed session profile', next) return next } catch (err) { console.debug('[substandard] session profile refresh failed', err) return undefined } } /** * Why a restore failed, in the only two shapes that matter to the caller. * * The client wraps the expected auth failures (`TokenRefreshError`, * `TokenRevokedError`, `TokenInvalidError`) and deletes the stored session * before propagation; those all carry the account's `sub`. A failed fetch, a * 5xx, or a malformed answer does not, and must not be read as "signed out" — * the session may still be perfectly good. Duck-typing `sub` is what survives * minification, where the error classes' constructor names do not. */ export function isSessionGoneError(err: unknown): boolean { return typeof err === 'object' && err !== null && typeof (err as { sub?: unknown }).sub === 'string' } /** What a restore attempt settled on. */ export type SessionRestore = | { status: 'ok' } | { status: 'expired'; reason: string } | { status: 'unreachable'; reason: string } /** * Restore the stored session in the OAuth host. `refresh` forces a token * rotation even when the access token is still valid, which is what the * periodic keepalive uses: a refresh token that is used stays usable (up to * the server's absolute session lifetime), and rotation is the only refresh * a PDS offers. * * Offline is checked before touching the client: a restore that cannot reach * the PDS proves nothing about the session, and some client code paths delete * a session on a failed refresh. Keeping it is the only correct answer. */ export async function restoreSession(sub: string, refresh = false): Promise { if (navigator.onLine === false) return { status: 'unreachable', reason: 'offline' } try { await getClient().restore(sub, refresh) return { status: 'ok' } } catch (err) { const reason = err instanceof Error ? err.message : String(err) console.debug('[substandard] session restore failed', reason, err) return isSessionGoneError(err) ? { status: 'expired', reason } : { status: 'unreachable', reason } } } /** * Restore the persisted session and wrap it in an API agent. The mirror is * only cleared when the client says the session is gone; an unreachable PDS * leaves it (and the OAuth session) alone. */ export async function restoreAgent(): Promise< { agent: Agent } | { status: 'expired' | 'unreachable' } > { const stored = await ext.storage.local.get(SUB_KEY) const sub = stored[SUB_KEY] as string | undefined if (!sub) return { status: 'expired' } if (navigator.onLine === false) return { status: 'unreachable' } try { const session = await getClient().restore(sub) return { agent: new Agent(session) } } catch (err) { const gone = isSessionGoneError(err) console.debug( '[substandard] session restore failed', gone ? 'dropping the session' : 'keeping the session; the PDS was unreachable', err, ) if (gone) await markSessionExpired() return { status: gone ? 'expired' : 'unreachable' } } } /** * Best-effort revocation of one stored session, leaving the mirror alone. * Used on its own when a completed account switch retires the login it * replaced. */ export async function revokeSession(sub: string): Promise { await getClient() .revoke(sub) .catch(() => { // best-effort; the caller's local state moves on regardless }) } export async function signOut(): Promise { const stored = await ext.storage.local.get(SUB_KEY) const sub = stored[SUB_KEY] as string | undefined if (sub) await revokeSession(sub) await clearSessionMirror() }