Repository Public
1// The fetch used by the API client. It is the only place that knows about CSRF and step-up:2// - adds X-MCC-CSRF (kept in memory only) to every non-safe request;3// - on `403 step_up_required`, asks the registered step-up handler to run a passkey ceremony, then replays the4// ORIGINAL request exactly once (same body, same Idempotency-Key);5// - reports 401 so the shell can return to the sign-in page.6// Kept free of React and of the generated client so it can be unit-tested with a fake fetch.78const SAFE = new Set(["GET", "HEAD", "OPTIONS"]);910export interface TransportHooks {11 /** Runs the step-up ceremony. Resolves true when the session was stepped up, false when the user cancelled. */12 stepUp?: (() => Promise<boolean>) | undefined;13 onUnauthenticated?: ((code: string) => void) | undefined;14}1516export interface Transport {17 fetch: (request: Request) => Promise<Response>;18 setCsrf: (token: string | null) => void;19 getCsrf: () => string | null;20 /** Merges the given hooks into the current ones. */21 setHooks: (hooks: TransportHooks) => void;22}2324async function errorCode(response: Response): Promise<string | undefined> {25 try {26 const body: unknown = await response.clone().json();27 const code = (body as { error?: { code?: unknown } } | null)?.error?.code;28 return typeof code === "string" ? code : undefined;29 } catch {30 return undefined;31 }32}3334export function createTransport(baseFetch: (request: Request) => Promise<Response> = (r) => globalThis.fetch(r)): Transport {35 let csrf: string | null = null;36 let hooks: TransportHooks = {};37 let pendingStepUp: Promise<boolean> | null = null;3839 const withCsrf = (request: Request): Request => {40 if (SAFE.has(request.method.toUpperCase()) || !csrf) return request;41 const headers = new Headers(request.headers);42 headers.set("X-MCC-CSRF", csrf);43 return new Request(request, { headers });44 };4546 const stepUpOnce = (): Promise<boolean> => {47 if (!hooks.stepUp) return Promise.resolve(false);48 // concurrent requests that all need a step-up share one ceremony49 pendingStepUp ??= hooks.stepUp().finally(() => {50 pendingStepUp = null;51 });52 return pendingStepUp;53 };5455 return {56 setCsrf: (token) => {57 csrf = token;58 },59 getCsrf: () => csrf,60 setHooks: (h) => {61 hooks = { ...hooks, ...h };62 },63 async fetch(request) {64 const replay = request.clone(); // taken before the body is consumed65 const response = await baseFetch(withCsrf(request));66 if (response.status === 403 && !request.url.includes("/auth/stepup/")) {67 if ((await errorCode(response)) === "step_up_required" && (await stepUpOnce())) {68 return baseFetch(withCsrf(replay)); // one retry only: a second step_up_required is returned as is69 }70 } else if (response.status === 401) {71 hooks.onUnauthenticated?.((await errorCode(response)) ?? "unauthenticated");72 }73 return response;74 },75 };76}77