SPB Git

Repository Public

stepup.tsx 3.1 KB 90 lines tsx

1"use client";2import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";3import { apiPost, transport } from "@/api/client";4import { ApiError } from "@/api/errors";5import { useI18n } from "@/i18n";6import { getPasskey, WebAuthnError } from "@/lib/webauthn";7import { Banner, Button, Dialog, Icon } from "@/ui";89export function unwrapPublicKey(pk: Record<string, unknown>): Record<string, unknown> {10  const inner = pk.publicKey;11  return typeof inner === "object" && inner !== null ? (inner as Record<string, unknown>) : pk;12}1314/** Runs the step-up ceremony against the API. Throws WebAuthnError / ApiError. */15export async function runStepUp(): Promise<void> {16  const challenge = await apiPost("/auth/stepup/begin");17  const credential = await getPasskey(unwrapPublicKey(challenge.public_key));18  await apiPost("/auth/stepup/finish", { body: { challenge_id: challenge.challenge_id, credential } });19}2021/**22 * Registers the transport's step-up hook: when any request is refused with `403 step_up_required`, a dialog asks23 * for the passkey (a click is required so the browser accepts the WebAuthn call), then the transport replays the24 * original request once.25 */26export function StepUpProvider({ children }: { children: ReactNode }) {27  const { t } = useI18n();28  const [open, setOpen] = useState(false);29  const [busy, setBusy] = useState(false);30  const [error, setError] = useState<string | null>(null);31  const resolver = useRef<((ok: boolean) => void) | null>(null);3233  const settle = useCallback((ok: boolean) => {34    resolver.current?.(ok);35    resolver.current = null;36    setOpen(false);37    setBusy(false);38    setError(null);39  }, []);4041  useEffect(() => {42    transport.setHooks({43      stepUp: () =>44        new Promise<boolean>((resolve) => {45          resolver.current?.(false);46          resolver.current = resolve;47          setError(null);48          setOpen(true);49        }),50    });51    return () => transport.setHooks({ stepUp: undefined });52  }, []);5354  const verify = async () => {55    setBusy(true);56    setError(null);57    try {58      await runStepUp();59      settle(true);60    } catch (e) {61      setBusy(false);62      if (e instanceof WebAuthnError) setError(e.reason === "cancelled" ? t("stepup.cancelled") : t("stepup.failed"));63      else if (e instanceof ApiError) setError(`${t("stepup.failed")} (${e.code})`);64      else setError(t("stepup.failed"));65    }66  };6768  return (69    <>70      {children}71      <Dialog72        open={open}73        onClose={() => settle(false)}74        title={t("stepup.title")}75        description={t("stepup.body")}76        dismissable={!busy}77        footer={78          <>79            <Button onClick={() => settle(false)} disabled={busy}>{t("common.cancel")}</Button>80            <Button variant="primary" icon="passkey" onClick={verify} loading={busy} autoFocus data-testid="stepup-verify">{t("stepup.verify")}</Button>81          </>82        }83      >84        <p className="row muted"><Icon name="shield" size={16} />{t("stepup.why")}</p>85        {error ? <Banner tone="critical" role="alert">{error}</Banner> : null}86      </Dialog>87    </>88  );89}90
Files main
Menu

Theme