Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768// One-shot OAuth client work in the offscreen document. Sign-in keeps that// document open for the consent window; the periodic session check does not// need it afterwards, so it opens one only when there is no sign-in already// in progress and closes what it opened.//// The same-document rule matters because an interactive sign-in's authorize// message must not be cut off by a keepalive that decided the document was// its own. `hasOffscreenDocument` is the conservative check: if we cannot// tell, we leave the document alone.
import { ensureOffscreenDocument, hasOffscreenDocument } from './offscreen'import type { SessionRestore } from './oauth'import type { OffscreenMsg } from './types'import { ext } from './platform'
const OFFSCREEN = { url: 'offscreen.html', justification: 'The AT Protocol OAuth client keeps its sign-in state in DOM storage',} as const
async function toOffscreen<T>(msg: OffscreenMsg): Promise<T> { 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}
/** * One restore attempt in a DOM context, closing the document if we opened it. * * Chrome has no DOM in its service worker, so it uses the offscreen document. * A browser whose background page is itself a DOM context (Firefox) has no * offscreen API; there the OAuth client can be imported directly. That branch * is also what keeps this usable before the Firefox platform layer lands. */export async function restoreInOffscreen( sub: string, refresh: boolean,): Promise<SessionRestore> { if (typeof ext.offscreen?.createDocument !== 'function') { const { restoreSession } = await import('./oauth') return restoreSession(sub, refresh) } const existed = (await hasOffscreenDocument()) === true // Built here, not at module scope: Firefox has no `ext.offscreen`, and this // module is loaded by its background page too. await ensureOffscreenDocument({ url: OFFSCREEN.url, reasons: [ext.offscreen.Reason.LOCAL_STORAGE], justification: OFFSCREEN.justification, }) try { return await toOffscreen<SessionRestore>({ target: 'offscreen', type: 'oauth-restore', sub, refresh, }) } finally { if (!existed) { await ext.offscreen.closeDocument().catch(() => { // already gone }) } }}