# Two-factor setup

> Three-step 2FA setup demo with a QR placeholder, six-digit input validation, and copyable sample backup codes.

- Kind: block · Category: Auth · Interactivity: script
- Install: `npx shadcn@latest add @haze/two-factor-setup`
- File: `src/components/haze/blocks/two-factor-setup.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/two-factor-setup

## Use when
- Prototyping a two-factor setup flow with sample credentials
- Previewing how people enter a code and save backup codes before connecting an authentication backend

## Avoid when
- Enrolling users in live two-factor authentication
- Verifying an already-enrolled user during sign-in; use otp-verification

## Alternatives
- [otp-verification](https://hazeui.com/blocks/otp-verification.md)
- [security-settings](https://hazeui.com/blocks/security-settings.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-two-factor-setup" | no | Unique prefix for input label and heading IDs. |
| setupKey | `string` | "JBSW-Y3DP-EHPK-3PXP" | no | Sample setup key displayed in the demo. |
| backupCodes | `string[]` | 6 sample codes | no | Sample backup codes shown on step 3. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- The sample setup key and backup codes have labelled copy buttons that announce success or failure.
- An invalid demo code keeps focus on the labelled input and announces the six-digit requirement.
- Key Tab: Move across the code field, copy buttons, and step controls
- Key Enter / Space: Activate the focused button. Enter in the code field submits the demo code.

## Agent prompts

### Install and use

Install the Haze UI block "Two-factor setup" with `npx shadcn@latest add @haze/two-factor-setup`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import TwoFactorSetup from "@/components/haze/blocks/two-factor-setup.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/blocks/two-factor-setup.md

### Customize with real content

Adapt the Haze two-factor-setup block for our product. Replace the demo values of these props with our real content: id, setupKey, backupCodes, class. Keep the layout, the heading level rules and these accessibility details: The sample setup key and backup codes have labelled copy buttons that announce success or failure. An invalid demo code keeps focus on the labelled input and announces the six-digit requirement. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using two-factor-setup, check it fits: use it when prototyping a two-factor setup flow with sample credentials; previewing how people enter a code and save backup codes before connecting an authentication backend. Avoid it when enrolling users in live two-factor authentication; verifying an already-enrolled user during sign-in; use otp-verification. Alternatives: @haze/otp-verification, @haze/security-settings.

## Example requests that should lead here
- Create a three-step two-factor setup demo with a QR placeholder, six-digit code validation, and copyable sample backup codes

## Source

```astro
---
import { ArrowLeft, ArrowRight, Copy, QrCode, ShieldCheck } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id?: string;
  setupKey?: string;
  backupCodes?: string[];
  class?: string;
}

const {
  id = "haze-two-factor-setup",
  setupKey = "JBSW-Y3DP-EHPK-3PXP",
  backupCodes = ["8412-9041", "3920-1184", "6745-2209", "1108-7732", "5591-4420", "9034-6158"],
  class: className,
} = Astro.props;
---

<section aria-labelledby={`${id}-title`} data-haze-2fa-setup class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}>
  <div class="mx-auto max-w-md rounded-2xl border border-border bg-card p-6 sm:p-7">
    <header class="flex flex-wrap items-center justify-between gap-2 border-b border-border pb-4">
      <div class="flex items-center gap-2">
        <ShieldCheck class="size-4 text-muted-foreground" aria-hidden="true" />
        <h2 id={`${id}-title`} class="text-base/6 font-semibold tracking-tight text-foreground">Two-factor setup</h2>
      </div>
      <span data-tfa-step-label class="font-mono text-xs text-muted-foreground tabular-nums">Step 1 of 3</span>
    </header>

    <p class="mt-4 rounded-lg border border-frame bg-muted/40 px-3 py-2 text-xs/5 text-foreground"><strong class="font-semibold">Demo only.</strong> This walkthrough uses sample credentials.</p>

    <form data-tfa-form>
      <div data-tfa-pane="0" class="mt-5 space-y-4">
        <h3 tabindex="-1" class="text-sm font-semibold text-foreground">Sample setup details</h3>
        <div class="flex flex-col items-center justify-center rounded-xl border border-border bg-muted/40 p-4 sm:p-6">
          <div class="grid size-28 place-items-center rounded-xl border border-frame-strong bg-card text-foreground shadow-key" aria-hidden="true">
            <QrCode class="size-16" aria-hidden="true" />
          </div>
          <p class="mt-2 text-xs text-muted-foreground">QR placeholder</p>
          <p class="mt-3 text-xs text-muted-foreground">Sample setup key</p>
          <div class="mt-1 flex max-w-full flex-wrap items-center justify-center gap-2">
            <code class="min-w-0 wrap-anywhere rounded-md border border-border bg-card px-2.5 py-1 font-mono text-xs text-foreground">{setupKey}</code>
            <button type="button" disabled data-tfa-copy={setupKey} aria-label="Copy sample setup key" class="inline-flex size-8 cursor-pointer items-center justify-center rounded-lg border border-frame bg-field text-muted-foreground hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-45 transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
              <Copy class="size-3.5" aria-hidden="true" />
            </button>
          </div>
        </div>
      </div>

      <div data-tfa-pane="1" hidden class="mt-5 space-y-4">
        <div class="grid gap-1.5">
          <label for={`${id}-totp`} class="text-sm font-semibold text-foreground">Demo code</label>
          <p id={`${id}-code-hint`} class="text-xs/5 text-muted-foreground">Enter any six digits to continue the demo.</p>
          <input id={`${id}-totp`} data-tfa-code disabled required type="text" inputmode="numeric" pattern="[0-9]{6}" maxlength="6" aria-describedby={`${id}-code-hint ${id}-code-error`} class="h-11 rounded-xl border border-frame-input bg-field px-3.5 text-center font-mono text-base tracking-[0.35em] text-foreground aria-invalid:border-destructive-border focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden transition-[color,background-color,border-color,box-shadow] duration-150 hover:border-frame-foreground aria-invalid:focus-visible:ring-destructive/24" />
          <p id={`${id}-code-error`} data-tfa-error role="alert" class="text-xs/5 text-destructive"></p>
        </div>
      </div>

      <div data-tfa-pane="2" hidden class="mt-5 space-y-4">
        <h3 tabindex="-1" class="text-sm font-semibold text-foreground">Sample backup codes</h3>
        <ul role="list" class="grid grid-cols-2 gap-2 rounded-xl border border-border bg-muted/40 p-3 font-mono text-xs text-foreground">
          {backupCodes.map((c) => <li class="wrap-anywhere rounded-md border border-border bg-card px-2.5 py-1.5 text-center tabular-nums">{c}</li>)}
        </ul>
        <button type="button" disabled data-tfa-copy={backupCodes.join("\n")} class="inline-flex h-8 w-full cursor-pointer items-center justify-center gap-1.5 rounded-lg border border-frame bg-field text-xs font-medium text-foreground hover:border-frame-strong hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-45 transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
          <Copy class="size-3.5" aria-hidden="true" />
          Copy sample backup codes
        </button>
      </div>

      <footer class="mt-6 flex items-center justify-between gap-2 border-t border-border pt-4">
        <button type="button" data-tfa-prev disabled class="inline-flex h-9 cursor-pointer items-center gap-1 rounded-lg border border-frame bg-field px-3 text-xs font-medium text-foreground hover:bg-accent disabled:cursor-not-allowed disabled:opacity-45 focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
          <ArrowLeft class="size-3.5" aria-hidden="true" />
          Back
        </button>
        <button type="submit" data-tfa-next disabled class="inline-flex h-9 cursor-pointer items-center gap-1.5 rounded-lg bg-primary px-4 text-xs font-medium text-primary-foreground hover:opacity-90 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:cursor-not-allowed disabled:opacity-45 transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
          <span data-tfa-next-label>Continue</span>
          <ArrowRight class="size-3.5" aria-hidden="true" />
        </button>
      </footer>

      <p data-tfa-status role="status" tabindex="-1" class="mt-3 min-h-4 text-xs/4 text-muted-foreground"></p>
    </form>
  </div>
</section>

<script>
  function initTwoFactorSetups() {
    document.querySelectorAll<HTMLElement>("[data-haze-2fa-setup]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      const panes = Array.from(root.querySelectorAll<HTMLElement>("[data-tfa-pane]"));
      const form = root.querySelector<HTMLFormElement>("[data-tfa-form]");
      const label = root.querySelector<HTMLElement>("[data-tfa-step-label]");
      const code = root.querySelector<HTMLInputElement>("[data-tfa-code]");
      const error = root.querySelector<HTMLElement>("[data-tfa-error]");
      const prev = root.querySelector<HTMLButtonElement>("[data-tfa-prev]");
      const next = root.querySelector<HTMLButtonElement>("[data-tfa-next]");
      const nextLabel = root.querySelector<HTMLElement>("[data-tfa-next-label]");
      const status = root.querySelector<HTMLElement>("[data-tfa-status]");
      if (!form || !label || !code || !error || !prev || !next || !nextLabel || !status) return;
      root.setAttribute("data-enhanced", "");
      let step = 0;

      const clearError = () => {
        code.removeAttribute("aria-invalid");
        error.textContent = "";
      };
      const showStep = (index: number) => {
        step = index;
        panes.forEach((pane, i) => { pane.hidden = i !== step; });
        label.textContent = `Step ${step + 1} of ${panes.length}`;
        prev.disabled = step === 0;
        next.disabled = false;
        nextLabel.textContent = step === panes.length - 1 ? "Finish demo" : "Continue";
        code.disabled = step !== 1;
        clearError();
        status.textContent = "";
        if (step === 1) code.focus();
        else panes[step]?.querySelector("h3")?.focus();
      };

      next.disabled = false;
      code.addEventListener("input", clearError);
      code.addEventListener("invalid", (event) => {
        event.preventDefault();
        code.setAttribute("aria-invalid", "true");
        error.textContent = "Enter six digits to continue.";
        code.focus();
      });

      prev.addEventListener("click", () => showStep(step - 1));
      form.addEventListener("submit", (event) => {
        event.preventDefault();
        if (step < panes.length - 1) {
          showStep(step + 1);
          return;
        }
        next.disabled = true;
        nextLabel.textContent = "Demo complete";
        status.textContent = "Two-factor setup demo complete.";
        status.focus();
      });
      root.querySelectorAll<HTMLButtonElement>("[data-tfa-copy]").forEach((button) => {
        button.disabled = false;
        button.addEventListener("click", async () => {
          try {
            await navigator.clipboard.writeText(button.dataset.tfaCopy ?? "");
            status.textContent = "Copied to clipboard.";
          } catch {
            status.textContent = "Couldn't copy to the clipboard. Select the sample text to copy it manually.";
          }
        });
      });
    });
  }
  initTwoFactorSetups();
  if (!document.documentElement.hasAttribute("data-haze-two-factor-setup-listener")) {
    document.documentElement.setAttribute("data-haze-two-factor-setup-listener", "");
    document.addEventListener("astro:page-load", initTwoFactorSetups);
  }
</script>
```
