// Where the OAuth client runs. It needs DOM globals (window, localStorage, // IndexedDB), which Chrome's MV3 service worker does not have — so on Chrome // the worker opens an offscreen document and messages it, exactly as before. // Firefox's MV3 background page is a DOM context, so the same client can run // there directly, with no message hop and no document to close. // // The Firefox branch imports ./oauth dynamically, and that has to stay // dynamic: a static import would put the browser OAuth client into Chrome's // service-worker bundle, and evaluating it there is the failure this module // exists to avoid. import { ensureOffscreenDocument } from './offscreen' import { ext, hasOffscreenSupport } from './platform' import type { OffscreenMsg, SessionInfo } from './types' async function ensure(): Promise { await ensureOffscreenDocument({ url: 'offscreen.html', reasons: [ext.offscreen.Reason.LOCAL_STORAGE], justification: 'The AT Protocol OAuth client keeps its sign-in state in DOM storage', }) } async function toOffscreen(msg: OffscreenMsg): Promise { const res = await ext.runtime.sendMessage(msg) if (res && typeof res === 'object' && '__error' in res) { throw new Error(String((res as { __error: unknown }).__error)) } return res as T } /** * Begin interactive sign-in and return the consent URL to open. On Chrome the * offscreen document is created here; on Firefox the client resolves the * handle in the background page. */ export async function authorize(handle: string): Promise { if (!hasOffscreenSupport()) { const { startAuthorization } = await import('./oauth') return startAuthorization(handle) } await ensure() return toOffscreen({ target: 'offscreen', type: 'oauth-authorize', handle }) } /** Finish the flow by exchanging the callback URL for a session. */ export async function callback(url: string): Promise { if (!hasOffscreenSupport()) { const { completeAuthorization } = await import('./oauth') return completeAuthorization(url) } await ensure() return toOffscreen({ target: 'offscreen', type: 'oauth-callback', url }) } /** Best-effort revocation, used when an account switch retires the old login. */ export async function revoke(sub: string): Promise { if (!hasOffscreenSupport()) { const { revokeSession } = await import('./oauth') return revokeSession(sub) } await ensure() await toOffscreen({ target: 'offscreen', type: 'oauth-revoke', sub }) } /** * Tear down the Chrome offscreen document once the flow is over. On Firefox * there is nothing created to close. */ export async function close(): Promise { if (!hasOffscreenSupport()) return await ext.offscreen.closeDocument().catch(() => { // already gone }) }