# Backup codes

> A 2FA recovery codes panel with 1.5px 8×8 Bayer secret veiling, copy-while-veiled, .txt export, used-code audit stamps and inline regeneration.

Two-factor recovery sheets are usually dumped into an exposed preformatted box with a browser confirm dialog for rotation. BackupCodes wraps one-time recovery codes in real account-security ergonomics: unused codes start veiled behind individual 1.5px 8×8 Bayer optical panes (0% CPU at rest) so screen shares stay safe, while already-redeemed codes stay visibly struck through with used timestamps so remaining capacity is auditable at a glance. Copy all lifts every unused code directly to the clipboard even while veiled with a staggered emerald Bayer wavefront, Download .txt exports a formatted plain-text recovery file with issuer and account metadata, low remaining counts surface an amber warning, and Regenerate confirms in place without browser popups.

## Install

```bash
npx shadcn@latest add https://hairlineui.com/r/backup-codes.json
```

Needs React 19, Tailwind CSS v4 and shadcn/ui theme variables (any style, light and dark). Icons from lucide-react.

- npm: `lucide-react`
- Hairline UI components it needs (the CLI installs them too): `text-morph`, `number-roll`
- Docs and live preview: https://hairlineui.com/ui/backup-codes
- Registry item (source): https://hairlineui.com/r/backup-codes.json

## Usage

```tsx
import { BackupCodes } from "@/components/backup-codes";

<BackupCodes
  codes={codes}
  issuer="Acme"
  account="alex@acme.dev"
  onRegenerate={async () => {
    const fresh = await regenerateOnServer();
    setCodes(fresh);
  }}
/>
```

## Wired to a server 2FA rotation endpoint

Generate and hash recovery codes on the server, pass the plaintext batch to BackupCodes once, and wire onRegenerate to rotate.

```tsx
"use client";
import { useState } from "react";
import { BackupCodes, type BackupCodeItem } from "@/components/backup-codes";

export function SecurityRecoverySection({ initial }: { initial: BackupCodeItem[] }) {
  const [codes, setCodes] = useState<BackupCodeItem[]>(initial);

  return (
    <BackupCodes
      codes={codes}
      issuer="Acme Cloud"
      account="alex@acme.dev"
      filename="acme-recovery-codes.txt"
      onRegenerate={async () => {
        const res = await fetch("/api/auth/2fa/backup-codes", { method: "POST" });
        if (!res.ok) throw new Error("Failed to rotate codes");
        setCodes(await res.json());
      }}
    />
  );
}
```

## Props

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `codes` | `Array<string \| BackupCodeItem>` | – | Recovery codes as plain strings or { code, used?, usedAt? } objects. |
| `issuer / account / filename` | `string` | `"Hairline" / — / "recovery-codes.txt"` | Metadata written into downloaded .txt exports and print sheets. |
| `defaultVeiled / allowCopyIndividual` | `boolean` | `true / true` | Start veiled behind Bayer grain and allow one-click copying of individual revealed codes. |
| `onRegenerate / onToggleUsed` | `() => Promise<void> \| void / (code, used) => void` | – | Enable the inline two-step Regenerate confirmation and per-code used toggling. |
| `lowThreshold / onDownload / onPrint / sound` | `number / fn / fn / boolean` | `2 / built-in / built-in / false` | Low-remaining warning threshold, custom export hooks and opt-in Web Audio cues. |

## States

- **veiled grid**: Unused codes sit behind individual 1.5px 8×8 Bayer panes while already-used codes remain visibly struck through so counts stay legible.
- **copy while veiled**: Copy all writes unused codes to the clipboard and ripples a staggered emerald Bayer sweep across the veiled cells.
- **revealed**: Codes display in crisp monospace with single-click individual copy and hover Use controls when onToggleUsed is wired.
- **low remaining**: When unused codes fall at or below lowThreshold, the header count shifts amber and an inline warning banner prompts rotation.
- **confirm regenerate**: The footer turns into an inline hairline confirmation bar with Cancel and async Confirm states.

## What it handles

Recovery codes only protect an account if users can save them effortlessly without exposing them on screen or losing track of how many remain.

- **Per-slot 8×8 Bayer secret veil**: Unused recovery codes stay concealed behind crisp 1.5px Bayer grain at rest; click any slot to peek one code or Reveal codes to open the sheet.
- **Copy all while veiled with emerald wave**: Copies every unused code straight to the clipboard without exposing them on screen, confirming with a staggered emerald Bayer wavefront across the grid.
- **Real .txt download and print sheet**: Generates a formatted plain-text recovery file with issuer, account, date and numbered codes via Blob download, plus a clean print sheet helper.
- **Used stamps and low-capacity warning**: Redeemed codes render struck through in a recessed slot while an amber notice warns automatically when remaining codes reach lowThreshold.
- **Two-step inline Regenerate guard**: Clicking Regenerate opens an inline hairline confirmation bar inside the footer with loading state and zero native browser alerts.
- **Unambiguous code generator included**: Exports generateBackupCodes() using crypto.getRandomValues without ambiguous 0/O/1/I/L characters alongside formatBackupCodesFile().

## Replaces

plain <pre> recovery list, window.confirm() regenerate dialog, custom .txt Blob downloader, manual used-code counter

## Where it fits

- **2FA and MFA enrolment**: Present newly minted recovery codes with one-click Copy all, .txt file download and print actions before completing setup.
- **Account security settings**: Keep active codes veiled by default while showing exactly how many remain and which ones were already used.
- **Passkey and authenticator fallback**: Pair directly with Passkey button, Sudo gate and Verify code to complete your authentication surface.
- **Enterprise recovery rotation**: Guard code rotation behind an inline two-step confirmation so operators never invalidate active codes by misclick.

## Notes

- Veiled slots paint static 1.5px 8×8 Bayer canvases at rest (0 rAF loops / 0% CPU) and run a brief ~0.5s emerald sweep only when Copy all, Download .txt or Regenerate fires.
- generateBackupCodes() omits 0, O, 1, I and L so printed or handwritten recovery codes cannot be misread.
- Under prefers-reduced-motion: reduce, Bayer sweeps stay still while all reveal, copy, export and regenerate flows work unchanged.

License: MIT (https://hairlineui.com/license#components)
