// The API the pages call (spec/OAUTH.md, "The API"): a JSON body, the // `csrf-token` cookie as `x-csrf-token`, and the answer as a value, never // thrown. import type { Account } from './data'; import { usePasskey, type CredentialJSON } from './webauthn'; export type Endpoint = | 'sign-in' | 'consent' | 'reject' | 'passkey-options' | 'passkey-sign-in' | 'passkey-register'; // An answer: its status (0 when none came), its JSON body if it had one, // and Retry-After in seconds if given. export type Answer = { status: number; body: Record | null; retryAfter: number | null; }; function csrfToken(): string { for (const c of document.cookie.split(';')) { const at = c.indexOf('='); if (at > 0 && c.slice(0, at).trim() === 'csrf-token') { try { return decodeURIComponent(c.slice(at + 1).trim()); } catch { return c.slice(at + 1).trim(); } } } return ''; } // Call `endpoint` with `body`, and with `Authorization: Bearer ` // when a sign-in gave an ephemeral token. export async function call(endpoint: Endpoint, body: object, token?: string): Promise { const headers: Record = { 'content-type': 'application/json', 'x-csrf-token': csrfToken() }; if (token) headers.authorization = `Bearer ${token}`; let res: Response; try { res = await fetch(`/@atproto/oauth-provider/~api/${endpoint}`, { method: 'POST', mode: 'same-origin', headers, body: JSON.stringify(body), credentials: 'same-origin' }); } catch { return { status: 0, body: null, retryAfter: null }; } let json: unknown = null; try { json = await res.json(); } catch { json = null; } const retry = res.headers.get('retry-after'); const seconds = retry === null ? NaN : Number(retry); return { status: res.status, body: json !== null && typeof json === 'object' ? (json as Record) : null, retryAfter: Number.isFinite(seconds) ? seconds : null }; } // Send the browser to the `url` a `consent` or `reject` answered, if it // answered one, even one carrying an `error`. Answers whether it did. export function follow(a: Answer): boolean { const url = a.status === 200 ? a.body?.url : undefined; if (typeof url !== 'string') return false; location.assign(url); return true; } // What the sign-in form holds. export type Credentials = { identifier: string; password: string; remember: boolean }; // The outcome of a `sign-in`: the account signed in, with its ephemeral // token if it has one; the email factor asked for; or an answer that is // neither, for its alert. export type SignInOutcome = | { kind: 'signed-in'; account: Account; token?: string } | { kind: 'factor' } | { kind: 'refused'; answer: Answer }; // `sign-in` with what the form holds, and `emailOtp` when a code was typed. export async function signIn(c: Credentials, emailOtp?: string): Promise { const body = { locale: 'en', identifier: c.identifier, password: c.password, remember: c.remember }; const a = await call('sign-in', emailOtp === undefined ? body : { ...body, emailOtp }); const signedIn = signedInBy(a); if (signedIn) return signedIn; if (a.status === 401 && a.body?.error === 'second_authentication_factor_required') return { kind: 'factor' }; return { kind: 'refused', answer: a }; } // The account a `sign-in` or `passkey-sign-in` answer signed in, if it did. function signedInBy(a: Answer): { kind: 'signed-in'; account: Account; token?: string } | null { const account = a.body?.account as Account | undefined; if (a.status !== 200 || !account || typeof account.did !== 'string') return null; const token = a.body?.ephemeralToken; return { kind: 'signed-in', account, token: typeof token === 'string' ? token : undefined }; } // The outcome of signing in with a passkey (spec/PASSKEYS.md, "Signing // in"): the account signed in; no credential from the browser; options that // did not come; or a `passkey-sign-in` answer that signed nothing in. export type PasskeyOutcome = | { kind: 'signed-in'; account: Account; token?: string } | { kind: 'no-passkey' } | { kind: 'no-options' } | { kind: 'refused'; answer: Answer }; // `passkey-options`, then the browser's passkey, then `passkey-sign-in`. // The autofill gives the page's own options (`__passkeyOptions`) and asks // for none, its asking waiting on the identifier field (`conditional`); // `signal` ends it. export async function passkeySignIn( remember: () => boolean, given?: PublicKeyCredentialRequestOptionsJSON, signal?: AbortSignal ): Promise { let options = given; if (!options) { const o = await call('passkey-options', {}); const asked = o.body?.options; if (o.status !== 200 || !asked || typeof asked !== 'object') return { kind: 'no-options' }; options = asked as PublicKeyCredentialRequestOptionsJSON; } const credential = await usePasskey(options, !!given, signal); if (!credential) return { kind: 'no-passkey' }; const a = await call('passkey-sign-in', { locale: 'en', credential, remember: remember() }); return signedInBy(a) ?? { kind: 'refused', answer: a }; } // `passkey-register` with the credential the browser made. export const registerPasskey = (credential: CredentialJSON): Promise => call('passkey-register', { credential });